Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variables not returning
#1
Why is y not returned?
def numbers():
    x = 2
    y = x+2
    return x
    return y
print(numbers())
Reply
#2
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.
Reply
#3
def numbers():
    x = 2
    y = x+2
    return x, y

print(numbers())
x, y = numbers()
print(x, y)
Output:
(2, 4) 2 4
Reply
#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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020