我正在学习在 while 循环中使用函数。我的目标是要求用户在 while 循环内输入,并将输入用作函数中的参数。但是如果任何时刻的输入是 == 'q',则循环应该终止。 功能如下:
def make_album(artist_name, album_name, tracks = None):
if tracks:
album = {
'artist': artist_name,
'album': album_name,
'number of tracks': tracks
}
return album
else:
album = {
'artist': artist_name,
'album': album_name,
}
return album
它被放置在 while 循环内:
create_album = True
while create_album:
artist = input("Enter atrist's name: ").title()
if artist == 'q'.lower():
create_album = False
album = input("Enter album's name: ").capitalize()
if album == 'q'.lower():
create_album = False
number_of_tracks = input("(Optional) Enter number of tracks: ")
if number_of_tracks =='q'.lower():
create_album = False
elif number_of_tracks:
print(make_album(artist, album, number_of_tracks))
else:
print(make_album(artist, album))
尽管每个输入都会使用 if 语句进行检查,并且如果输入是“q”,则应将 create_album 的值更改为 False,但它仅在代码的最后部分正常工作:
number_of_tracks = input("(Optional) Enter number of tracks: ")
if number_of_tracks =='q'.lower():
create_album = False
如何修复程序,以便在用户输入“q”时随时终止 while 循环?
我尝试过改变各种方法来解决这个问题。
1)
if artist == 'q'.lower():
break
结果是:
Enter album's name:
2)
if artist == 'q'.title():
create_album = False
if artist == 'q':
create_album = False
if artist == 'Q':
create_album = False
结果是:
Enter album's name:
一旦您确定用户输入了“q”,您就将
create_album
设置为 False
,但随后您就会进入下一个输入。
您可以在
break
主体中添加 continue
,或者在本例中甚至添加 if
:
if artist == 'q'.lower():
create_album = False
break
但是对于这段代码来说,拥有
create_album
确实没有任何意义。 相反,您可以将整个内容替换为:
while True:
artist = input("Enter atrist's name: ").title()
if artist == 'q'.lower():
break
album = input("Enter album's name: ").capitalize()
if album == 'q'.lower():
break
number_of_tracks = input("(Optional) Enter number of tracks: ")
if number_of_tracks =='q'.lower():
break
elif number_of_tracks:
print(make_album(artist, album, number_of_tracks))
else:
print(make_album(artist, album))