定义函数
def greet_user():
#greet_user是函数名称
print("Hello")
#这个函数的功能,是打印Hello
greet_user()
#这里是直接引用这个函数
向函数传递信息
def greet_user(username):
#括号里的username可以是你输入的任何值,这个值赋值给username
print(f"Hello,{username.title()}!)
greet_user('jesse')
#其中username是形参,jesse是实参
传递实参`
位置实参
def describe_pet(animal_type,pet_name):
print(f"\nI have a {animal_type}.")
print(f"My{animal_type}'s name is {pet_name}")
describe_pet('hamster','harry')
#'hamster','harry'是实参,他们分别与animal_type,pet_name是一一对应的
describe_pet('dog','willie')
#这个就是再次调用了这个函数,只不过里面的实参变了
关键字实参
def describe_pet(animal_type,pet_name):
print(f"\nI have a {animal_type}.")
print(f"My{animal_type}'s name is {pet_name}")
describe_pet(animal_type='hamster',pet_name='harry')
#使用这种形式就不需要在乎位置顺序了
默认值
def describe_pet(pet_name,animal_type='log'):
#这里的pet_type='dog'是默认值,调用这个函数时,如果没有定义pet_type的值,那么他就默认是该值
避免实参的错误
返回值`
def get_fomartted_name(first_name,last_name):
full_name=f"{first_name}{last_name}"
return full_name.title()
musician=get_formatted_name('jimi','hendrix')
#这里相当于把return的值赋值给了musician
print(musician)
让实参变成可选的
def get_formatted_name(first_name,last_name,middle_name='')
if middle_name:
full_name=f"{first_name}{middle_name}{last_name}"
else:
full_name=f"{first_name}{last_name}"
return full_name.title()
musician=get_formatted_name('jimi','hendrix')
print(musician)
musician=get_formatted_name('jion','hooker','lee')
print(musician)
返回字典
def build_person(first_name,last_name):
person={'first':first_name,'last':last_name)
return person
musician=build_person('jini','hendrix')
print(musician)
你可以扩展这个函数
def build_person(first_name,last_name,age=None):
person={'first':first_name,'last':last_name}
if age:
person['age']=age
#往person这个字典里添加这个'age'=age的键值对
return person
musician=build_person('jimi','hendrix',age=27)
print(musician)
结合使用函数和while循环
def get_formatted_name(first_name,last_name):
full_name=f"{first_name}{last_name}"
return full_name.title()
while true:
print(f"\n Please tell me your name")
print(f"\n (enter 'q' at any time to quit)")
f_name=input("Frist_name:")
if f_name='q':
break
l_name=input("last_name:")
if l_name='q':
break
formatted_name=get_formatted_name(f_name,l_name)
print(formatted_name)
传递列表
def greet_users(names):
for name in names:
msg=f"Hello,{name.title}"
print(msg)
usernames=['hannah','try','margot']
greet_users(usernames)
在函数中修改列表
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design=unprinted_designs.pop()
print(f" Printing model:{current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
print(f"The following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
禁止函数修改列表
这里就需要用原列表的副本
例如上面的unprinted_designs列表
副本表示为 unprinted_designs[:]
传递任意数量的实参
def make_pizza(*toppings):
#*toppings 是让python建一个名为toppings的空元组,并将收到的值全部封装在这个元组中
print(toppings)
make_pizza('a')
make_pizza('a','b','c')
('a',)
('a','b','c')
结合使用位置实参和任意数量的实参
def make_pizza(size,*toppings):
#python会先匹配位置实参,关键字实参,再将剩下的实参集中收到最后一个形参中
print(f"\nMaking a {size}-inch pizza with the following toppings:"}
for topping in toppings:
print(f"{topping}")
make_pizza(6,'a')
make_pizza(5,'a','b','c','d','f')
使用任意数量的关键字实参
def build_profile(first,last,**user_info):
#**user_info让python建立一个名为user_info的空字典
user_info['first_name']=first
uesr_info['last_name']=last
return uesr_info
user_profile=build_profile('a','b',location='jin',field='physics')
#这里的location和field没有''
print(user_profile)