当我尝试从我创建的菜单中选择一个sepcific选项时,它只是再次输出菜单

2024-10-03 13:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的课堂上,我们被要求为音乐组织者创建一个包含三个选项的菜单,下面的代码是我全部代码的一部分。每当我运行程序时,不会出现错误,但当我输入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")

Tags: thetoininputifartist选项count
2条回答

尝试此操作以获取用户输入

Artistname =input("Enter artist name: ")

使用break退出while循环或按3

该行:

Artistname = str("Enter artist name: ")

将字符串"Enter artist name: "绑定到名为Artistname的变量,因此代码正在artistList中查找值为"Enter artist name: "的项,该值可能不在列表中

另一个问题是:

if artistFound == false:

false在Python中不是有效的标识符。这应该会引发一个异常,如果不是,您可能在其他地方为false分配了一个值

要解决此问题,您需要从用户处获取输入:

artist_name = input("Enter artist name: ")

现在artist_name将包含用户输入的一些值,您的搜索代码现在将查找列表中更可能存在的内容

请注意,使用^{}可以大大减少搜索代码:

artist_name = input("Enter artist name: ")
artist_count = artist_list.count(artist_name)
if artist_count > 0:
    print('{} songs by {}'.format(artist_count, artist_name))
else:
    print("Sorry, that is not an artist name")

相关问题 更多 >