Custom function:
def 函数名(参数列表):
函数体
[return 返回值] #可以没有返回reuturn ,也可以返回空 return,
Reprinted in: How to return multiple values from a function in Python - Flame Rabbit (zadmei.com) https://www.zadmei.com/rhcpzdhs.html
1. Custom functions can return tuples, lists, dictionaries, etc.
2. Tuples and lists can be used to return ordered arrays; dictionaries can be used to return unordered arrays;
3. When returning the dictionary, pay attention to the uniqueness of the key keyword.
4. Return a tuple or list. You can use multiple variables to receive the return value.
Example
1. Use tuples to return multiple values
#自定义函数,返回一个元组
def get_info():
name = "Tom"
age = 18
gender = "male"
return name, age, gender
info = get_info()
print(info)
name, age, gender = get_info() #使用多个变量接收元组返回值
print(name, age, gender)
The output is:
('Tom', 18, 'male')
Tom 18 male
In this example, we define a function called get_info, which returns a tuple containing three values: name, age, and gender. Outside the function, we call the function and assign the return value to a variable called info. Finally, we print the value of this variable and get a tuple of three elements.
We also used multiple variables to receive the return value and printed the values of these variables separately.
2. Use a list to return multiple values
#自定义函数,返回一个列表
def get_info():
name = "Tom"
age = 18
gender = "male"
return [name, age, gender]
info = get_info() #返回列表
print(info)
name, age, gender = get_info() #使用多个变量接收元组返回值
print(name, age, gender)
The output is:
['Tom', 18, 'male'] #print(info)
Tom 18 male
In this example, we define a function called get_info, which returns a list containing three values: name, age, and gender. Outside the function, we call the function and assign the return value to a variable called info. Finally, we print the value of this variable and get a list of three elements.
We also used multiple variables to receive the return value and printed the values of these variables separately.
3. Example 3: Using a dictionary to return multiple values
#自定义函数返回一个字典
def get_info():
info = {"name": "Tom", "age": 18, "gender": "male"}
return info
info = get_info()
print(info) #字典
name, age, gender = get_info().values() #多个变量接收返回的字典数据
print(name, age, gender)
The output is:
{'name': 'Tom', 'age': 18, 'gender': 'male'}
Tom 18 male
In this example, we define a function called get_info, which returns a dictionary containing three key-value pairs: name, age, and gender. Outside the function, we call the function and assign the return value to a variable called info. Finally, we print the value of this variable and get a dictionary containing three key-value pairs.
We also used the dictionary's values() method to get the values in the dictionary, used multiple variables to receive the return values, and printed the values of these variables respectively.