python - 用户输入 Exit 以中断 while 循环

标签 python input while-loop exit break

我正在为计算机做一个作业,以生成一个随机数并让用户输入他们的猜测。问题是我应该给用户一个输入“退出”的选项,这将打破 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.")

最佳答案

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

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

关于python - 用户输入 Exit 以中断 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48797648/

相关文章:

c++ - 为什么不是 while ((i <= 9) && square == pow(i, 2)) { cout << i << square;我++;按照我的意愿打印出来?

python - 暂停 Python 生成器

python - 如何通过 API 使用 For 循环从 Google Drive 下载文件

python - numpy 数组切片的意外结果(查看与复制)

javascript - 如果 aria-valuenow = 0,则将类添加到按钮

python - 是否可以使用 getch() 获取不同长度的输入?

javascript - 使用 Javascript 比较 html 文本输入并重定向到另一个页面

java - 具有有限迭代和 IF 语句的复杂循环

python - 如何使用 PyQt5 将本地 html 文件转换为 pdf?

java - 如果里面 while