def function_1():
return (5)
return (6)
return(7)
result_1 = function_1()
print(result_1)
Why is is that when I print the call of function_1(), only the first value, 5, is printed?
def function_1():
return (5)
return (6)
return(7)
result_1 = function_1()
print(result_1)
Why is is that when I print the call of function_1(), only the first value, 5, is printed?
You need to return multiple values as a tuple.
def function_1():
return 5, 6, 7
result_1 = function_1()
print(result_1)
a, b, c = function_1()
print(a, b, c)
This outputs:
(5, 6, 7)
5 6 7
When you're returning value 5 by this return (5)
line then funtion_1
returns the value and terminates the function. That's why subsequent lines are not getting executed. If you want to return multiple values from a function then you can return them as a tuple
,list
etc. Like:
def function_1():
return(5,6,7)
Why is is that when I print the call of function_1(), only the first value, 5, is printed?
Value "5" is getting printed because when you will call function_1
then function_1
will always return "5" and it wont execute next lines in that function. That's the reason you are always getting same value.
You can use yield
instead, making a generator. return
stops the function execution. The code will be like:
def function_1():
yield (5)
yield (6)
yield (7)
for result in function_1():
print(result)
You function will terminate on the first successful return
statement, which in this case is 5
. As others have suggested, you could wrap these values in a tuple
or a list
. You could also return a dictionary containing these multiple values:
def function_1():
return {'first': 5, 'second': 6, 'third': 7}
Then you can call it like this:
>>> result_1 = function_1()
>>> result_1
{'first': 5, 'second': 6, 'third': 7}
>>> result_1['first']
5
>>> result_1['second']
6
>>> result_1['third']
7