麻烦使用try和except

时间:2015-11-30 21:51:17

标签: 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)
    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,这不仅仅是随机数的机会,而是重复几次。

对于如何提出不同的问题,我们已经尝试了多种解决方案,感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这有望澄清有关while循环的一些内容。

给出一个while循环:

while x:
    y()

函数y()将被无限调用,直到x为False

关键字中断并按以下方式工作:

while x:
    y()
    if z:
        break

当x变为False或z变为True时,将结束,以先发生者为准。这相当于:

while x and not z:
    y()

答案 1 :(得分:0)

你给了一个无限循环。 你键入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)

这有什么不同,它现在要求一个有效的答案,如果它得到一个,它继续下一个问题。希望这有帮助!