Python 使用try和except时出现问题
这是我的代码:Python 使用try和except时出现问题,python,try-catch,except,Python,Try Catch,Except,这是我的代码: import random # Imports the random module score = 0 operator = ['*','+','-'] for i in range (1,11): print('This is question ',str(i)) NumOne = random.randint(1,12) NumTwo = random.randint(1,12) Op = random.choice(operator)
import random # Imports the random module
score = 0
operator = ['*','+','-']
for i in range (1,11):
print('This is question ',str(i))
NumOne = random.randint(1,12)
NumTwo = random.randint(1,12)
Op = random.choice(operator)
Answer = eval(str(NumOne) + Op + str(NumTwo))
while True:
try:
userAnswer = int(input('What is the answer to {} {} {}'.format(NumOne,Op,NumTwo)))
continue
except ValueError:
print('That isn\'t a valid input')
if userAnswer == Answer:
print('That is the correct answer. You have scored a point')
score +=1
else: print('That is the incorrect answer')
print('You have scored',score,'out of 10.\nThat is equal to ',(score/10)*100)
基本上,当我运行这个时,它会给我一个问题。我回答了这个问题,然后它又问了我同样的问题
因此:
什么是1+1?
然后我输入2
它再次要求1+1,这不仅仅是随机数的概率,它重复了好几次
对于如何提出不同问题的任何帮助,我都表示感谢。我已经尝试了几种解决方案。这将有助于澄清有关while循环的一些内容 给定while循环:
while x:
y()
函数y()将被无限期调用,直到xFalse
关键字“中断”和“工作”如下所示:
while x:
y()
if z:
break
将在x变为False
或z变为True
时结束,以先发生者为准。这相当于:
while x and not z:
y()
你已经给出了一个无限循环。 如果输入While True,则它要求您回答的值将永远不会更改,因为它永远不会知道您应该做什么
import random # Imports the random module
score = 0
go = False
operator = ['*','+','-']
for i in range (1,11):
go = False
print('This is question ',str(i))
NumOne = random.randint(1,12)
NumTwo = random.randint(1,12)
Op = random.choice(operator)
Answer = eval(str(NumOne) + Op + str(NumTwo))
while go != True:
try:
userAnswer = int(input('What is the answer to {} {} {}'.format(NumOne,Op,NumTwo)))
go = True
except ValueError:
print('That isn\'t a valid input')
if userAnswer == Answer:
print('That is the correct answer. You have scored a point')
score +=1
else:
print('That is the incorrect answer')
print('You have scored',score,'out of 10.\nThat is equal to ',(score/10)*100)
不同的是,它现在要求的是一个有效的答案,如果它得到了一个,它将进入下一个问题。希望这有帮助 也许你想用
break
而不是continue
?是的,刚刚尝试过,效果很好,但我只是在等待回复时尝试了更多的解决方案,发现如果你使用,done=False,while not done而不是while true,并在回答正确后声明done=true,这也行。但是,你的答案更有效,而且总体来说是一个更好的答案,thanks@Thom9soncontinue
只需返回最内部循环的顶部即可。您的逻辑是“如果此代码没有抛出ValueError,请永远再次运行”