用户输入退出以中断循环

时间:2018-02-14 22:59:16

标签: python input while-loop exit break

我正在为计算机做一个生成随机数的任务并让用户输入他们的猜测。问题是我应该给用户一个选项来输入'退出'它会破坏While循环。我究竟做错了什么?我正在运行它并说它出现了错误的行guess = int(输入("猜数字从1到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.")

2 个答案:

答案 0 :(得分:2)

您正在尝试解析字符串'退出'到整数。 您可以在转换线周围添加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")

答案 1 :(得分: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): ")