在我的课堂上,我们被要求为音乐组织者创建一个包含三个选项的菜单,下面的代码是我全部代码的一部分。每当我运行程序时,不会出现错误,但当我输入1时,终端会再次弹出选项菜单,而不是“输入艺术家名称”:
知道为什么吗
#创建选项菜单
option = 0
while option != 3:
print("What would you like to do?")
print(" 1. count all the songs by a particular artist")
print(" 2. print the contents of the database")
print(" 3. quit")
option = int(input("Please enter 1, 2, or 3: "))
# For option 1: find a all the songs on a certain album
if option == 1:
# Set the user input to a variable
Artistname = str("Enter artist name: ")
artistFound = False
for i in range(len(artistList)):
# For all the artist names in the list, compare the user input to #the artist names
if artistList[i] == Artistname:
artistFound = True
# count songs associate with artist
number+=1
print(count, "songs by",artistList[i])
# If the user input isn't in the list, then print out invalid
if artistFound == false:
print("Sorry, that is not an artist name")
尝试此操作以获取用户输入
使用break退出while循环或按3
该行:
将字符串
"Enter artist name: "
绑定到名为Artistname
的变量,因此代码正在artistList
中查找值为"Enter artist name: "
的项,该值可能不在列表中另一个问题是:
false
在Python中不是有效的标识符。这应该会引发一个异常,如果不是,您可能在其他地方为false
分配了一个值要解决此问题,您需要从用户处获取输入:
现在
artist_name
将包含用户输入的一些值,您的搜索代码现在将查找列表中更可能存在的内容请注意,使用^{} 可以大大减少搜索代码:
相关问题 更多 >
编程相关推荐