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.
CodePudding user response:
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.
CodePudding user response:
exp
variable is in algebra
function/local scope, where as the print
expression is in global scope. In short, local variables can't be accessed from global scope.
but if exp
is defined globally and accessed/modified into a function. That change will be reflected in global scope as well. For example:
`
#defining a variable globally
exp = -1
def algebra(x, y):
addition = x y
multiplication = x * y
# using the global `exp` variable so that if `exp` changes in this scope it will be reflect in the global scope
global exp
exp = 2
exp_sum = x**exp y**exp
return(addition, multiplication, exp_sum)
algebra(5, 7)
print(exp) # exp = 2, since `exp` variable is changed while calling `algebra` function
`
Based on the requirement, the best way is to print/access exp
variable locally from function scope. For example:
def algebra(x, y):
addition = x y
multiplication = x * y
exp = 2
exp_sum = x**exp y**exp
print(exp)
return(addition, multiplication, exp_sum)
CodePudding user response:
I think what you’re looking for might be the answer in the linked post. If you name your variable algebra.exp you would be able to access that variable later outside of the function.
See Access a function variable outside the function without using "global"