我写了一个程序,为用户生成随机数猜测。我正在努力捕捉所有可能的错误。唯一一个我似乎无法弄清楚的是这个。一开始我要求用户按Enter键继续游戏。如果程序输入字符串甚至是特殊字符和标点符号,程序就会捕获。我唯一无法阻止的是,如果他们输入一个数字,程序就会终止。这就是我所拥有的。问题出在try块的第一个while循环中。任何建议或帮助将不胜感激。 提前谢谢。
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while True:
if cont != '':
try:
int(cont)
str(cont)
break
except ValueError:
print('Just hit enter')
cont = input()
continue
elif cont == '':
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
答案 0 :(得分:1)
输入数字时会发生什么,程序会尝试将数字转换为int
(有效),然后转换为str
(也有效),之后会中断。相反,请尝试以下方法:
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while cont != '':
cont = input('Press enter to continue')
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
num = int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
答案 1 :(得分:-1)
while True:
if cont != '':
try:
int(cont)
str(cont)
break
它在这里做的是尝试将cont
转换为int,如果成功则尝试将其转换为字符串(这实际上总是可行的)。如果成功,则会中断while循环并结束程序。
在尝试解析它int(cont)
时,除了int之外的任何其他场景,它会引发错误并继续执行您的程序。
一旦他按下进入续约。在输入文本之前,你没有理由证明他没有写东西。