1

When I try to call a, b in function add, I get a is not defined even though I am returning the values. How do I make it return both a and b?

def numbers():
        a= input ("a:")
        a = int(a)
        b= input ("b:")
        b = int(b)
        return a
        return b
    
def add():
    numbers()
    print (a)
    print (b)
add()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sam
  • 1,206
  • 2
  • 12
  • 27
  • There are two separate problems in the code. The first is the linked duplicate. The second is that functions **return values, not variables**. Within `add`, the result from the `numbers()` call needs to be assigned to local names, or else used directly. Calling `numbers()` **does not** create local `a` and `b` variables. The error message only complains about `a` because the error causes the program to terminate; there is no opportunity to complain about `b`, but it would if it got that far. – Karl Knechtel Jun 05 '22 at 16:37

2 Answers2

5

A return statement almost always causes a function to immediately terminate, and no other statement in the function will run. So once you return a, you'll never get to return b. You need to return both of them at the same time.

Additionally, returning a value from a function will not automatically put those names into the scope that called the function. You need to manually assign the values to something.

def numbers():
       a= input ("a:")
       a = int(a)
       b= input ("b:")
       b = int(b)
       return a,b

def add():
    a,b = numbers()
    print (a)
    print (b)

add()
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Thanks a lot. I am doing python for a class but I don't have a good basic knowledge. This is what I was looking for. – Sam Dec 21 '15 at 17:04
0

I think so:


def numbers():
        a= input ("a:")
        a = int(a)
        b= input ("b:")
        b = int(b)
        return a, b

def add(a, b):
    print (a)
    print (b)
    return a, b

def main():
    another_a, another_b = numbers()
    another_a, another_b = add(another_a, another_b)

main()
mrvol
  • 2,575
  • 18
  • 21