How to access a variable defined inside a function

2019-01-15 23:28发布

问题:

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

回答1:

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

or

op, n1, n2, ans = get_two_nums()
question(op, n1, n2, ans)


回答2:

Why not return a tuple?

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

def question():
    op, num1, num2, answer = get_two_nums()
    response = int(input("What is {} {} {}? ".format(num1, op, num2)))
    if response == answer:
        # the rest of your logic here


回答3:

You cannot simply pass them, because variables in get_two_nums are defined only in scope of get_two_numsfunction. So basically you have two options:

  1. Return their values as tuple into scope of another function as @TimPietzcker and @Tgsmith61591 proposed.

  2. Define variables within get_two_nums function as globals ( see global statement, for more info) as in code snipper below:

    def get_two_nums():
        global num1
        num1 = 'value1'
        global num2
        num2 = 'value2'
        global num3
        num3 = 'value3'
    
    def question():
        # Call get_two_nums to set global variables for further using
        get_two_nums()
        response = int(input("What is {} {} {}? ".format(num1, num2, num3)))
        if response == answer:
            # Some code here ...
    

WARNING: Using global variables should be avoided, see Why are global variables evil? to get better idea of what i am talking about ...