我正在尝试使用Automate the Boring Stuff一书中的一个小程序。
我想确保输入非int变量的人不会使程序崩溃。代码踢出一个错误,说“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.')
答案 0 :(得分:2)
您的缩进不正确。请注意,try
块及其下方的所有内容都不再位于for
循环中。
答案 1 :(得分:1)
嗯,首先,请记住始终在此处发布您的代码,这样您就可以避免掉线。
在查看代码时,我可以轻松地告诉您一些事情:
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
语句的例外1}}因为未创建guess
变量,下一个if
语句if guess "<" secretNumber:
会抛出异常。
3)这段代码有点破碎,因为如果它抛出异常并且没有创建猜测,if
循环中的最后for
语句也会抛出异常,所以我建议你在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.')
仍有改进的余地,但这将满足您的要求。
度过美好的一天=)。