- 定义一个简单函数
def greet_user(username):
print("hello!" + str(username))
username_1 = input("Please input your name!\n")
greet_user(username_1)# username_1为实参
这里username是函数的形参,用户可以把实参传入进函数,这个函数就是和你打个招呼。
# 这里第二个形参有默认值,如果不传入实参,默认为China
def describe_city(des_city,des_country = 'China'):
print(des_city.title() + ' is in ' + des_country)
city = {
'wuxi': 'China',
'NewYork': 'USA',
'London': 'UK'
}
for key, val in city.items():
describe_city(key.title(), val)
- 带有返回值的函数
"""返回简单值"""
def get_formatted_name(first_name, last_name, middle_name=""):
if middle_name:
full_name = first_name + str(middle_name) + last_name
else:
full_name = first_name + last_name
return full_name # 返回值
name = get_formatted_name('mahani', 'Li', 2)
print(name.title())
这是结合while语句和带返回字典的函数的一个例子
def city_country(city, country):
message = {}# 创建一个字典
message[city] = country #为字典添加键——值
return message
while flag:
input_city = input("Please input the city")
if input_city == 'Q':
break
input_country = input("Where is the city locates?\n(Input Q to quit)")
if input_country == 'Q':
break
message = city_country(input_city, input_country)
print(message)
3.传递列表的函数
def greet_users(names):
for name in names: #需要写循环遍历列表
msg = "Hello, " + name.title() + "!"
print(msg)
names = ['ke', 'ling', 'king']
greet_users(names)
"""该实例可以修改列表中的元素"""
unprinted_designs = ['robot pendant', 'phone case']
finished_designs = []
def pop_designs(unprint_designs, completed_list):
while unprinted_designs:
completed_thing = unprint_designs.pop()
completed_list.append(completed_thing)
def show_completed(finish_designs):
for finish_design in finish_designs:
print(finish_design)
pop_designs(unprinted_designs, finished_designs)
show_completed(finished_designs) #原列表都进入该列表中
show_completed(unprinted_designs) # 打印原列表,为空
- 传递任意数量的实参
形参加个*号创建一个空元组来存储传入不定数量的实参
# 创建一个名为 toppings 的空元组
def make_pizza(size, *toppings):
""" 概述要制作的比萨 """
print("\nMaking a pizza with the following toppings:")
print(size)
for topping in toppings:
print("- " + topping)
形参加个**号创建一个空字典,来接受任意数量的键——值对
def complete_mes(first_name, last_name, **mes):
profile = {}
profile['first_name'] = first_name
profile['last_name'] = last_name
for key, value in mes.items():
profile[key] = value
return profile
# example
user_profile = complete_mes('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
- 将函数存储在模块中
用法可以看批注。
"""将func_learning中的函数导入到该文件"""
import func_learning as func
"""你还可以导入模块中的特定函数,还可以通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数"""
from func_learn import make_pizza
"""调用库中所用函数"""
from send_list_func import *
func.greet_user('model')
make_pizza(10, 'extra cheese', 'pienapple', 'mushroom')
"""这样调用不太容易理解(如果不熟悉库的话)"""
pop_designs(unprinted_designs, finished_designs)
show_completed(finished_designs)