形参和实参
def greet_user(username):
"""显示简单的问候语"""
print(f'hello,{username}!')
greet_user("王君君")
#习题8-1
def display_message(content):
print(f'你本章学习的是:{content}')
display_message('函数')
#习题8-2
def favorite_book(title):
print(f"One of my favorite book is {title}.")
favorite_book('海底世界')
def description_animals(name,type='二哈'):
print(f"我养了一只:{type}")
print(f"它的名字叫做{name}\n")
description_animals(name="欢欢")
description_animals(type='金毛',name="欢欢")
"""
One of my favorite book is 海底世界.
我养了一只:二哈
它的名字叫做欢欢
我养了一只:金毛
它的名字叫做欢欢
"""
#8-4 给予默认值
def make_shirt(size='大号',character='I Love Python'):
print(f'您订购的尺码是:{size},印到后面的字样是{character}')
make_shirt()
make_shirt("中号")
make_shirt(character="hahah")
"""
您订购的尺码是:大号,印到后面的字样是I Love Python
您订购的尺码是:中号,印到后面的字样是I Love Python
您订购的尺码是:大号,印到后面的字样是hahah
"""
#8-5传递默认实参
def describe_city(city='台湾',country='中国'):
print(f"{city}是{country}的")
describe_city()
describe_city("兰州")
describe_city('东京','日本')
"""
台湾是中国的
兰州是中国的
东京是日本的
"""
实参个数可选
def get_formatted_name(first_name,last_name,middle_name=''):
full_name=f"{first_name} {middle_name} {last_name}"
return full_name.title()
name=get_formatted_name('王','俊','俊')
print(name)
结合使用函数和while循环
def get_formatted_name(first_name,last_name):
full_name=f"{first_name} {last_name}"
return full_name.title()
while True:
print('\n请告诉我你的名字:')
print("输入q退出")
f_name=input("first_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(f"\nHello,{formatted_name}")
习题8-7
def make_album(name,album,number=None):
zidian={'名字':name,'专辑':album}
if number:
zidian['number']=number
return zidian
TheAlbum=make_album('陈奕迅','十年')
print(TheAlbum)
习题8-8
#8-8
def make_album(name,album):
zidian={'名字':name,'专辑':album}
return zidian
while True:
print('\n请输入歌手的名字:')
print('输入q退出')
歌手名=input('歌手名:')
if 歌手名=='q':
break
专辑名=input('专辑名:')
if 专辑名=='q':
break
TheAlbum=make_album(歌手名,专辑名)
print(TheAlbum)
列表作为实参传入
def greet_users(names):
for name in names:
print(f"hello,{name}!")
usernames=['王菲','李俊','小李']
greet_users(usernames)
在函数中修改列表
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design=unprinted_designs.pop()
print(f"正在打印:{current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
print(f"这些被打印好了:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs=['phone case','robot pendant','摄像机']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
"""
正在打印:摄像机
正在打印:robot pendant
正在打印:phone case
这些被打印好了:
摄像机
robot pendant
phone case
"""
#习题8-9
def show_messages(messages):
for message in messages:
print(message)
messages=['q','w','e','r']
show_messages(messages)
#习题8-10
def show_messages(messages,completed_messages):
while messages:
show_message=messages.pop()
print(f"正在显示的是:{show_message}")
completed_messages.append(show_message)
def send_messages(completed_messages):
for completed_message in completed_messages:
print(f"需要发送的是:{completed_message}")
messages=['q','w','e','r']
completed_messages=[]
show_messages(messages,completed_messages)
send_messages(completed_messages)
#习题8-11
def show_messages(messages,completed_messages):
while messages:
show_message=messages.pop()
print(f"正在显示的是:{show_message}")
completed_messages.append(show_message)
def send_messages(completed_messages):
for completed_message in completed_messages:
print(f"需要发送的是:{completed_message}")
messages=['q','w','e','r']
completed_messages=[]
show_messages(messages[:],completed_messages)
send_messages(completed_messages)
print(f"原来的列表{messages}")
传递任意数量的实参
def build_profile(first,last,**user_info):
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile=build_profile('wang','jun',location='lanzhou',field='math')
print(user_profile)
#8-12
def sandwich(*stuff):
print(f"客户点了{stuff}")
sandwich('菠萝')
sandwich('菠萝','橘子','苹果')
sandwich('栗子','红薯')
#8-13
def introduce_me(hobby,result,**user_info):
user_info['爱好']=hobby
user_info['成果']=result
return user_info
user_profile=introduce_me('篮球','第一',location='兰州',field='体育')
print(user_profile)
#{'location': '兰州', 'field': '体育', '爱好': '篮球', '成果': '第一'}
#8-14
def make_car(size,company,**cars_info):
cars_info['型号']=size
cars_info['厂商']=company
return cars_info
car=make_car(12,'中国',国旗='五星红旗',轮胎='国产')
print(car)
#{'国旗': '五星红旗', '轮胎': '国产', '型号': 12, '厂商': '中国'}