簡體   English   中英

用戶輸入退出以中斷循環

[英]User input Exit to break while loop

我正在為計算機做一個生成隨機數的任務,並讓用戶輸入他們的猜測。 問題是我應該給用戶一個輸入'Exit'的選項,它會打破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.")

您正在嘗試將字符串'Exit'解析為整數。 您可以在鑄造線周圍添加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")

最簡單的解決方案可能是創建一個函數,將顯示的消息作為輸入,並在測試滿足您的條件后返回用戶輸入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM