python函数可以与各种语句相结合,以达到提高效率简化流程的目的:
- 通过函数创建字典 eg. 将歌手与专辑对应,并储存在字典当中
def make_ablum(name, album):
"""返回整洁的字典格式"""
album_details = {'singer': name, 'album': album_name}
return album_details
#已经定义好了字典,现在可以输入几个对应值来检测
album_details_1 = make_album('Jay', 'Fantasy')
album_details_2 = make_album('Taylor Swift', 'Style')
album_details_3 = make_album('elva', 'the fifth ave')
print(album_details_1)
print(album_details_2)
print(album_details_3)
2 在函数中添加可选参数,也就是说,如果添加,则会显示;若不添加,则自动忽略。 只需要用if语句就可以实现这个功能 eg.在上面的歌手与专辑的对应中,添加个歌曲数量的统计
def make_album(name, album_name, number_of_songs = ""):
#number_of_songs 先用空字符代替
"""将歌曲数设置为可选参数"""
album_details = {'singer': name, 'album': album_name}
if number_of_songs:
album_details['number of songs'] = number_of_songs
#只要填入歌曲数,则if语句为真,相应的,会在字典中添加
return album_details
#定义好以后,可以分别用含歌曲数和不含的两组值来测试
detail_1 = make_album('Jay', 'Fantasy')
detail_2 = make_album('Taylor Swift', 'Style', '1')
print(detail_1)
print(detail_2)
3 除了与if语句相结合,同样也可以与while语句结合,比如下面的例子。通过和while结合,通过用户自己的输入,编写好字典的相关信息。并加入指示,使用户可以停止该循环:
def make_album(name, album_name, number_of_songs):
"""将歌曲数设置为可选参数,在用while语句通过用户输入调用"""
album_details = {'singer': name, 'album': album_name}
if number_of_songs:
album_details['number of songs'] = number_of_songs
return album_details
#函数定义好以后,就可以与while语句相结合
while True:
print("\nPlease tell me the details of your favorite album:")
print("(enter 'q' at any time to quit)")
name = input("Singer's name: ")
if name == "q":
break
#break的使用可以使用户操作停止该循环
album_name = input("Favorite album:")
if album_name == "q":
break
number_of_songs = input("How many songs in the album?")
if number_of_songs == "q":
break
album_details = make_album(name, album_name, number_of_songs)
print("Thanks for the following information!")
print(album_details)