返回简单值
#返回简单值
def get_user_name(firstName,lastName):
name=firstName+lastName
return name
SC_name=get_user_name("stephen","curry")
print(SC_name.title())
效果:
让实参变成可选的(定义的时候将形参赋默认值)
#为了让实参变成可选项,可以给实参赋默认值,并将其放在形参末尾
def get_format_name(firstName,lastName,middleName=""):
if(middleName!=""):
full_name = f"{firstName} {middleName} {lastName}"
else:
full_name=f"{firstName} {lastName}"
return full_name.title()
kd_name=get_format_name("kevin","durant")
print(kd_name)
效果:
返回字典(函数可以返回任何类型的值)
#返回字典
people_favourite_car={}
def add_dictionary(name,favourite_car):
people_favourite_car["name"]=name
people_favourite_car["favourite_car"]=favourite_car
return people_favourite_car
add_dictionary("SC","cadillac")
print(people_favourite_car)
效果:
使返回的字典可扩展(形参赋默认值)
#返回字典
#定义一个存放字典的列表
favourite_car_list=[]
def add_dictionary(name,favourite_car,age=None):
#定义一个字典
people_favourite_car = {}
if age:
people_favourite_car["age"]=age
people_favourite_car["name"] = name
people_favourite_car["favourite_car"] = favourite_car
return people_favourite_car
#把字典加入到列表中
favourite_car_list.append(add_dictionary("SC","cadillac"))
favourite_car_list.append(add_dictionary("KD","ferrari",36))
print(favourite_car_list)
效果:
传递列表
#传递列表
def greet_players(players):
for player in players:
print(f"hello!,{player}")
greet_players(["kd","sc","aj"])
效果:
在函数中修改列表(永久性)
#在函数中修改列表(对列表的修改是永久性的)
def print_register_users(unregister_users,register_users):
while unregister_users:
current_user=unregister_users.pop()
register_users.append(current_user)
def show_register_users(register_users):
for register_user in register_users:
print(f"{register_user}")
unregister_users=["kevin durant","stephen curry","james harden","paul george"]
register_users=[]
print_register_users(unregister_users,register_users)
show_register_users(register_users)
效果:
非永久性修改只需要把传入的列表改成切片副本即可
def print_register_users(unregister_users,register_users):
while unregister_users:
current_user=unregister_users.pop()
register_users.append(current_user)
def show_users(register_users):
for user in register_users:
print(f"{user}")
unregister_users=["kevin durant","stephen curry","james harden","paul george"]
register_users=[]
print_register_users(unregister_users[:],register_users)
show_users(register_users)
print("----------")
show_users(unregister_users)
效果:
#使用任意数量的关键字实参 用**
def print_superstars_team(name,**superstar_info):
superstar_info["name"]=name
return superstar_info
nba_player_team = print_superstars_team("sc",team="warrior",age="36")
print(nba_player_team)
效果: