如何在请求用户输入的 for 循环中使用 try-except 命令?

How to use the try-except command in a for loop asking for user input?

摘要:我在做一个猜数字的游戏。这会给你 7 次尝试猜测号码。之后它会告诉你号码。我试图通过使用 Try 和 except 方法来消除输入单词 (eg.six) 而不是 6 的人为错误。这就是我编写代码的方式。

工具:我正在使用 Windows 10 和 python 3.10.2 版本。

问题:我遇到了 try 和 except 方法不起作用的问题。例如。当我在用户输入的单词中键入 six/five 时,它不会打印 That is not a number。相反,它给了我 Traceback error。这是我正在避免并试图制作干净代码的东西。

    # This a guess the number game.


    import random  
    secretNumber=random.randint(1,20)

    for guessesTaken in range(1,7):
        print('Take a guess.')
        guess=int(input())

    #### Why this conditioning is importtant? ####
    #     Because it will only improve our guesses
        try:
            if guess < secretNumber:
                 print('Too Low')
            elif guess > secretNumber:
                 print('Too high')
            else:
                 break        #This is for the correct guess
        except:
            print('That is not a number')

    if guess == secretNumber:
        print('Good Game. '+'You guessed it correctly in '+ str(guessesTaken)+' 
    guesses')
    else:
         print('Nope. The number I was thinking of was '+str(secretNumber)) 
  

input 在 try 块之前抛出错误,将 input() 移到 try 块中

    # This a guess the number game.


    import random  
    secretNumber=random.randint(1,20)

    for guessesTaken in range(1,7):
        print('Take a guess.')
 

    #### Why this conditioning is importtant? ####
    #     Because it will only improve our guesses
        try:
            guess=int(input())
            if guess < secretNumber:
                 print('Too Low')
            elif guess > secretNumber:
                 print('Too high')
            else:
                 break        #This is for the correct guess
        except:
            print('That is not a number')

    if guess == secretNumber:
        print('Good Game. '+'You guessed it correctly in '+ str(guessesTaken)+' 
    guesses')
    else:
         print('Nope. The number I was thinking of was '+str(secretNumber))