How to return more than one value from a function in Python? [duplicate]

故事扮演 提交于 2019-12-20 08:27:55

问题


How to return more than one variable from a function in Python?


回答1:


You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly



回答2:


Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)



回答3:


Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)


来源:https://stackoverflow.com/questions/423710/how-to-return-more-than-one-value-from-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!