【问题标题】:User input and while loop用户输入和while循环
【发布时间】:2013-10-27 19:25:30
【问题描述】:

我正在尝试编写一个 Python 程序,它要求用户使用 1、2 或 3 进行选择。如果用户不输入这些,它会提示用户只输入这些数字。

一旦用户输入 1、2 或 3,程序就会再次要求它输入 1、2 或 3。这样重复 10 次,如果用户没有输入 1、2 或 3,它会提示用户仅输入这些数字。这是我目前所拥有的;

while(choice>3 or choice<1):
    choice = int(input("Please enter a value from 1 - 3 only:" ))
    while (((choice == 1 or choice == 2 or choice == 3) and (count < 10))):
            run program

问题是如果用户最初输入 1、2 或 3,程序不会运行。但是,如果用户第一次输入 1、2 或 3 以外的内容,程序的行为就像我想要的那样。

【问题讨论】:

  • 这是预期的行为。 if choice is ǸOT 1,2,3, then skip the block else execute the block!

标签: python loops input while-loop


【解决方案1】:

当输入 1,2,3 时它不会运行,因为 while 循环排除了这些数字。

代码:

while(choice>3 or choice<1):

1,2, and 3 将跳过此块-因此块内的代码将不会运行,程序将不执行任何操作。

【讨论】:

  • 是的,我明白,我知道我可以在我的第一个 while 循环之上创建另一个 while 循环,即 while (((choice == 1 or choice == 2 or choice == 3) 和(count
【解决方案2】:

使用尽可能与您所拥有的代码相似的代码:

try_count = 0
choice = ""
valid = False

while True:
    print("Please enter a number between 1 and 3")
    while True:
        try_count += 1

        choice = input("")

        try: #make sure the user has entered a number
            choice = int(choice)
            if choice >= 1 or choice <= 3: #if the value is outside our range
                valid = True
                break #then we're done!
        except:
            continue #if the user didn't enter a number, go around again

        if try_count >= 10: #if we've done this ten times exit
            try_count = 0
            break #exit to the outer loop

        if valid: #if we've got a proper value, we're done
            break #exit the loop

【讨论】:

    【解决方案3】:

    就像上面提到的 Blue Ice 一样,问题在于这一行:

    while(choice>3 or choice<1):
    

    问题是你只在选择大于 3 或小于 1 时才运行这个 while 循环,但在这个循环内你正在测试这个条件:

    while (((choice == 1 or choice == 2 or choice == 3) and (count < 10))):
    

    此代码始终无法访问,因为要运行第一个 while 循环,它需要 1、2 或 3 以外的数字才能进入循环。这意味着这个 while 循环永远不会运行,因为您要测试的第一个条件被保证为假,因此您和比较永远不会评估为真,因为无论如何True and False is False

    就我个人而言,我不会像您那样创建输入提示,因为它不像其他选项那样易于维护。可以使用字典在 python 中创建菜单,这是我喜欢的方式。您所做的是将键存储为选项,将值存储为对您要执行的函数的引用。我更喜欢这个,因为它消除了在循环中设置所有布尔测试的需要,并且它使添加或删除选项更容易。

    创建您要求的菜单的代码如下所示。

    options = {     1 : option_1,
                    2 : option_2,
                    3 : option_3
    }
    
    user_input = int(raw_input("1, 2, or 3"))
    
    #The () are required because otherwise you will get the memory address of the function and the funciton itself won't run
    options[user_input]()
    

    这当然意味着你必须将你的代码放在一个函数中(这样做的语法看起来像这样)

    def function():
        do stuff
    

    注意在字典中函数是如何在没有 () 的情况下存储的。这样做是因为没有括号,它是对函数本身的引用(如果您执行打印,您会看到它为您提供内存地址),使用括号,函数将执行。然后,您只需通过在字典查找中添加括号来调用该函数,如下所示 options[user_input]()

    对不起,我不完全理解你在 10 次之后的提示是做什么的,因为你应该在每次他们搞砸时提示他们更正他们的输入,但我相信使用这种方法来做你想做的事想做的事情看起来像这样:

    #Count to see how many times they mess up
    count = 0
    #Options dictionary
    options = {     1 : option_1,
                    2 : option_2,
                    3 : option_3
    }
    
    #I am using Python 3 BTW
    print("Enter 1, 2 or 3 ")
    #And I am assuming they will give good input
    user_input = int(raw_input("1, 2, or 3"))
    #This more closly mimics what you are doing but like I said I would avoid this so you don't have to hard code how many options you have
    #while((user_input is not 1) or (user_input is not 2) or (user_input is not 3))
    #try this
    #It makes sure you are not out of bounds for an any number of elements
    while(user_input < 0 and user_input > len(options)):
        #if you are ask for new input
        user_input = int(raw_input("1, 2, or 3"))
        #increment count
        count += 1
        #check if they messed up 10 times 
        if(count == 10):
            print("Enter 1, 2, or 3")
            #reset count so it will tell them on the next 10th time
            count = 0
    
    #to break the while loop above you must have valid input so call the function 
    options[user_input]()
    
    #And of course you need to define you functions to do the different options
    def option_1():
        do option_1 stuff
    
    def option_2():
        do option_2 stuff
    
    def option_3():
        do option_3 stuff
    

    同样,虽然这与您所拥有的非常不同,但以这种方式添加新选项要容易得多,因为您只需添加一个新函数并将选项添加到字典中,您不必担心测试对于您拥有的每个选项。

    TL;DR:Python 字典是输入的方式,不要针对每种情况进行测试

    【讨论】:

      【解决方案4】:

      或者你可以使用这个示例代码:

      choices_menu = '''
      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data'''
      
      choice = 0
      while(choice>3 or choice<1):
          print choices_menu
          choice = raw_input("Your choice (Input number 1 to 3) ? ")
          try:
              choice = int(choice)
              if choice >= 1 and choice <= 3:
                  break
          except:
              continue
      
      print choice
      

      结果:

      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data
      Your choice (Input number 1 to 3) ? -1
      
      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data
      Your choice (Input number 1 to 3) ? 0
      
      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data
      Your choice (Input number 1 to 3) ? 5
      
      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data
      Your choice (Input number 1 to 3) ? 4
      
      Please select input menu :
      Enter 1> Show latest 100 data
      Enter 2> Show latest 1000 data
      Enter 3> Show all data
      Your choice (Input number 1 to 3) ? 3
      3
      
      Process finished with exit code 0
      

      【讨论】:

        猜你喜欢
        • 2013-11-16
        • 2020-02-15
        • 1970-01-01
        • 2020-07-07
        • 2014-01-03
        • 2016-01-11
        • 1970-01-01
        • 1970-01-01
        • 2016-05-20
        相关资源
        最近更新 更多