如何从函数外部访问函数内定义的变量
问题描述:
我坚持使用另一个函数中前一个函数中定义的变量。例如,我有这样的代码:
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
答
变量是函数的局部变量,你需要 return
你想要分享给调用者的相关值,并将它们传递给使用它们的下一个函数。像这样:
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:
def get_two_nums():
...
# define the relevant variables
return op, n1, n2, ans
def question(op, num1, num2, answer):
...
# do something with the variables
现在您可以拨打电话
Now you can call
question(*get_two_nums()) # unpack the tuple into the function parameters
或
op, n1, n2, ans = get_two_nums()
question(op, n1, n2, ans)