【问题标题】:When I try to choose a sepcific option from the menu I created it just outputs the menu again当我尝试从我创建的菜单中选择特定选项时,它只是再次输出菜单
【发布时间】:2016-02-05 23:25:46
【问题描述】:

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

【问题讨论】:

  • 请关注PEP-8
  • 尽可能避免使用索引。整个艺术家查找代码可以简化为artistList.find(Artistname)artistList.index(Artistname)
  • count 定义/分配在哪里?

标签: python loops count increment


【解决方案1】:

试试这个来获取用户输入

Artistname =input("Enter artist name: ")

使用 break 退出 while 循环或按 3

【讨论】:

  • 如果你使用的是python2,那就是
  • 对于python3它的输入()
  • 我正在使用python3.4,我应该对这个版本做一些不同的事情吗?我尝试将其更改为 raw_input,它输出“输入艺术家姓名:”,但是当我尝试在其中输入艺术家时,它再次输出菜单
  • 我的错...我的意思是对于 python3 它的 input()....查看您要求用户输入选项的行
  • 也因为它没有找到任何艺术家并且你没有使用任何中断......它仍然在while循环中
【解决方案2】:

行:

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 将包含用户输入的一些值,您的搜索代码现在将寻找更可能存在于列表中的内容。

请注意,使用list.count() 可以大大减少您的搜索代码:

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2013-01-29
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多