Python Forum

Full Version: Variables not returning
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why is y not returned?
def numbers():
    x = 2
    y = x+2
    return x
    return y
print(numbers())
Because as soon as a return is encountered, execution returns to the caller. If you want to return multiple values, put them in a collection (list, tuple, dict, set) or an object.
def numbers():
    x = 2
    y = x+2
    return x, y

print(numbers())
x, y = numbers()
print(x, y)
Output:
(2, 4) 2 4
If for some reason you still want behavior of returning values one at the time you can use yield:

>>> def func():
...     yield 1
...     yield 2
...
>>> x, y = func()
>>> x
1
>>> y
2
>>> for i in func():
...     print(i)
...
1
2
>>> print(*func())
1 2