用户输入退出以中断while循环

Posted

技术标签:

【中文标题】用户输入退出以中断while循环【英文标题】:User input Exit to break while loop 【发布时间】:2018-07-25 15:26:53 【问题描述】:

我正在为计算机分配一个随机数并让用户输入他们的猜测。问题是我应该给用户一个输入“退出”的选项,它会破坏 While 循环。我究竟做错了什么?我正在运行它,它说guess = int(input("Guess a number from 1 to 9:"))这行有问题

import random

num = random.randint(1,10)
tries = 1
guess = 0

guess = int(input("Guess a number from 1 to 9: "))

while guess != num:
    if guess == num:
        tries = tries + 1
        break
    elif guess == str('Exit'):
        break
    elif guess > num:
        guess = int(input("Too high! Guess again: "))
        tries = tries + 1
        continue
    else:
        guess = int(input("Too low! Guess again: "))
        tries = tries + 1
        continue

print("Exactly right!")
print("You guessed " + str(tries) + " times.")

【问题讨论】:

您遇到的错误是什么? 猜一个从 1 到 9 的数字:退出 Traceback(最近一次调用最后一次):文件“C:/Users/Sherry/Desktop/1.py”,第 7 行,在 中guess = int(input("Guess a number from 1 to 9:")) ValueError: invalid literal for int() with base 10: 'Exit' >>> 【参考方案1】:

您正在尝试将字符串“退出”解析为整数。 您可以在铸造线周围添加 try/except 并处理无效输入。

import random

num = random.randint(1,9)
tries = 1
guess = 0

guess = input("Guess a number from 1 to 9: ")

try:
  guess = int(guess) // try to cast the guess to a int
  while guess != num:
    if guess == num:
        tries = tries + 1
        break
    elif guess > num:
        guess = int(input("Too high! Guess again: "))
        tries = tries + 1
        continue
    else:
        guess = int(input("Too low! Guess again: "))
        tries = tries + 1
        continue

  print("Exactly right!")
  print("You guessed " + str(tries) + " times.")    

except ValueError: 
    if guess == str('Exit'):
      print("Good bye")
    else:  
      print("Invalid input")

【讨论】:

我试过了,它只是导致其他行不起作用,因为其他行需要输入数字【参考方案2】:

最简单的解决方案可能是创建一个函数,将显示的消息作为输入,并在测试它是否满足您的条件后返回用户输入:

def guess_input(input_message):
    flag = False
    #endless loop until we are satisfied with the input
    while True:
        #asking for user input
        guess = input(input_message)
        #testing, if input was x or exit no matter if upper or lower case
        if guess.lower() == "x" or guess.lower() == "exit":
            #return string "x" as a sign that the user wants to quit
            return "x"
        #try to convert the input into a number
        try:
            guess = int(guess)
            #it was a number, but not between 1 and 9
            if guess > 9 or guess < 1:
                #flag showing an illegal input
                flag = True
            else:
                #yes input as expected a number, break out of while loop
                break
        except:
            #input is not an integer number
            flag = True

        #not the input, we would like to see
        if flag:
            #give feedback
            print("Sorry, I didn't get that.")
            #and change the message displayed during the input routine
            input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
            continue
    #give back the guessed number
    return guess

你可以在你的主程序中调用它

#the first guess
guess = guess_input("Guess a number from 1 to 9: ")

#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")

【讨论】:

以上是关于用户输入退出以中断while循环的主要内容,如果未能解决你的问题,请参考以下文章

如何根据 C 函数中函数的输入退出 while 循环?

用户输入和while循环

通过将 esc 作为用户的输入退出循环[重复]

While 循环使用用户输入和命令运行

我怎样才能退出 do-while 循环?

while循环合理运用-判断成绩脚本