Python try/except

Python try/except

我正在尝试自动化无聊的东西一书中的一个小程序。

我想确保输入非整型变量的人不会使程序崩溃。代码踢出一个错误,指出 "break" 命令不在循环中。任何帮助,将不胜感激。

import random
print ('Hello. What is your name?')
name = input()
secretNumber=random.randint(1,20)
print('Well ' + name + ', I\'m thinking of a number between 1 and 20.')

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

except ValueError:
    print ('I said guess a number not letters or words.')

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break

if guess == secretNumber:
    print('Good job! You guessed it.')
else:
    print('Nope the number I was thinking of was ' + str(secretNumber)+' sorry.')

您的缩进不正确。请注意,try 块及其下方的所有内容都不再位于您的 for 循环中。

好吧,首先,请记住始终post您的代码在这里,这样您就可以避免反对票。

看着你的代码,我可以很容易地告诉你一些事情:

1) 缩进这段代码,因为它实际上在 for 循环之外。

try:
    guess = int(input())

except (ValueError, NameError):
    print ('I said guess a number not letters or words.')
    break

if guess < secretNumber:
    print('Your guess is too low.')
elif guess > secretNumber:
    print('Your guess is too high.')
else:
    break

2) 你应该在 except 块中中断(就像我上面做的那样),这样它就不会执行下一个 if 语句块,否则你也会得到异常NameError 因为没有创建 guess 变量,所以下一个 if 语句 if guess "<" secretNumber: 会抛出异常。

3) 此代码有点损坏,因为如果它抛出异常并且未创建猜测,则 for 循环中的最后一个 if 语句也会抛出异常,所以我建议您在 for 语句之前初始化该变量,如下所示:guess = 0.

您的最终代码应如下所示:

import random
print ('Hello. What is your name?')
name = input()
secretNumber=random.randint(1,20)
print('Well ' + name + ', I\'m thinking of a number between 1 and 20.')
guess = 0

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

    except (ValueError, NameError):
        print ('I said guess a number not letters or words.')
        break

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break

if guess == secretNumber:
    print('Good job! You guessed it.')
elif guess == 0:
    None
else:
    print('Nope the number I was thinking of was ' + str(secretNumber)+' sorry.')

仍有改进的余地,但这将满足您的要求。

祝你有美好的一天=)。