如何从函数外部访问函数内部定义的变量

Mat*_*att 0 python variables scope function

我坚持在另一个函数中使用在前一个函数中定义的变量。例如,我有这个代码:

def get_two_nums():
    ...
    ...
    op = ...
    num1 = ...
    num2 = ...
    answer = ...

def question():
    response = int(input("What is {} {} {}? ".format(num1, op, num2)))
    if response == answer:
        .....
Run Code Online (Sandbox Code Playgroud)

我将如何在第二个函数中使用第一个函数中定义的变量?先感谢您

Tim*_*ker 5

变量是函数的局部变量;您需要将return要共享给调用者的相关值并将它们传递给使用它们的下一个函数。像这样:

def get_two_nums():
    ...
    # define the relevant variables
    return op, n1, n2, ans

def question(op, num1, num2, answer):
    ...
    # do something with the variables
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话

question(*get_two_nums()) # unpack the tuple into the function parameters
Run Code Online (Sandbox Code Playgroud)

或者

op, n1, n2, ans = get_two_nums()
question(op, n1, n2, ans)
Run Code Online (Sandbox Code Playgroud)