Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to print variable from function outside the function returns an error

I wrote this test function to explore the uses of functions and of basic algebra in Python:

def algebra(x, y):
    addition = x + y
    multiplication = x * y
    exp = 2
    exp_sum = x**exp + y**exp
    return(addition, multiplication, exp_sum)

print(exp)

The algebra function works fine, but when I try print(exp) outside of the function returns an error. I have read somewhere about global and local variables, but I am not sure if those are the concepts that explain what’s going on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are on the right track there. Global variables are those that are initialized outside of function. Your exp variable was initialized inside of the function, and since there is no print statement in the function, you could only print it locally from inside of the function. However, if you had initialized exp in the global space, then you could call it from inside the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading