【问题标题】:Creating a list of five numbers创建一个包含五个数字的列表
【发布时间】:2017-02-20 21:28:49
【问题描述】:

我正在尝试让 Python 提示用户选择五个数字并将它们存储在系统中。到目前为止,我有:

def main():
    choice = displayMenu()
    while choice != '4':
        if choice == '1':
            createList()
        elif choice == '2':
            print(createList)
        elif choice == '3':
            searchList()
        choice = displayMenu()

    print("Thanks for playing!")


def displayMenu():
    myChoice = '0'
    while myChoice != '1' and myChoice != '2' \
                  and myChoice != '3' and myChoice != '4':
         print ("""Please choose
                        1. Create a new list of 5 integers
                        2. Display the list
                        3. Search the list
                        4. Quit
                        """)
         myChoice = input("Enter option-->")

         if myChoice != '1' and myChoice != '2' and \
            myChoice != '3' and myChoice != '4':
             print("Invalid option. Please select again.")

    return myChoice 

#This is where I need it to ask the user to give five numbers 

def createList():
    newList = []
    while True:
        try:
            num = (int(input("Give me five numbers:")))
            if num < 0:
                Exception

            print("Thank you")
            break
        except:
            print("Invalid. Try again...")

    for i in range(5):
        newList.append(random.randint(0,9))
    return newList

运行程序后,它允许我选择选项 1 并要求用户输入五个数字。但是,如果我输入多个数字,它会说无效,如果我只输入一个数字,它会说谢谢并再次显示菜单。我哪里错了?

【问题讨论】:

    标签: python list add


    【解决方案1】:
    numbers = [int(x) for x in raw_input("Give me five numbers: ").split()]
    

    假设用户输入了由空格分隔的数字,这将起作用。

    【讨论】:

    • 非常感谢!当我尝试将其切换到此选项时,在我选择选项一后,它继续说“无效。再试一次”。一遍又一遍。
    • @J.Gunter 因为您在if num &lt; 0 行将列表与 0 进行比较。这里 num 将是一个数字列表。您应该尝试:if any([x&lt;0 for x in a]):
    【解决方案2】:

    使用 raw_input() 代替 input()。

    使用 Python 2.7 input() 将输入评估为 Python 代码,这就是您出错的原因。 raw_input() 返回用户输入的逐字字符串。在 python 3 中你可以使用 input(),raw_input() 不见了。

        my_input = raw_input("Give me five numbers:")  # or input() for Python 3
        numbers = [int(num) for num in my_input.split(' ')]
        print(numbers)
    

    【讨论】:

      【解决方案3】:

      @DmitryShilyaev 已正确诊断问题。如果要在一行中读取 5 个数字,可以使用 split 拆分 input 返回的字符串,并将该列表的每个元素转换为 int

      【讨论】:

      • 谢谢。你介意给我看看那会是什么样子吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多