I am stuck on using variables defined in a previous function in another function. For example, I have this code:
def get_two_nums():
...
...
op = ...
num1 = ...
num2 = ...
answer = ...
def question():
response = int(input("What is {} {} {}? ".format(num1, op, num2)))
if response == answer:
.....
How will I use the variables defined in the first function in the second function? Thank you in advance
Why not return a tuple?
Variables are local to the functions; you need to
return
the relevant values you want to share to the caller and pass them to the next function that uses them. Like this:Now you can call
or
You cannot simply pass them, because variables in
get_two_nums
are defined only in scope ofget_two_nums
function. So basically you have two options:Return their values as tuple into scope of another function as @TimPietzcker and @Tgsmith61591 proposed.
Define variables within
get_two_nums
function as globals ( see global statement, for more info) as in code snipper below:WARNING: Using global variables should be avoided, see Why are global variables evil? to get better idea of what i am talking about ...