如何让程序在算术测验中将字符串输入识别为错误的答案?

时间:2015-10-03 12:25:52

标签: python string int

我对python和编程很新。对于我的学校任务,我被要求开发一个基本的算术测验。但是,当我输入一个字母而不是整数时,我得到一个ValueError。我想要做的是让代码将字符串输入识别为错误的答案,我不太清楚如何做到这一点。我支持任何凌乱的代码,因为这是我第一次发布问题,我也尝试过研究这个问题,但我没有运气,因为我得到的答案与我的标准不符。这是我的完整代码:

import random
import math
import operator as op

def test():
    #First randomly generated number
    num1 = random.randint(1, 10)
    #Second randomly generated number
    num2 = random.randint(1, num1)                                               

    #List of the signs that the program is allowed to use in order to generate the question
     ops =     {                                                                      
        '+': op.add,
        '-': op.sub,
        '*': op.mul,
    }

    ##=> ['+', '*', '-']
    keys =     list(ops.keys())                                                      
    #e.g. '+' is chosen at random
    rand_key =     random.choice(keys)                                               
    #e.g. op.add
    operation =     ops[rand_key]                                                    

    correct_result = operation(num1, num2)

    #Asks the user the randomly generated question
    print ("What is {} {} {}?".format(num1, rand_key, num2))                     
   #User inputs the answer that he/she thinks is right
    user_answer= int(input("You answered: "))                                    

    if user_answer != correct_result:
        #This is what happens when he/she gets a wrong answer
        print ("Unfortunately are wrong!. The correct answer is     {}".format(correct_result))
        return False
     else:
        #This is what happens when he/she gets a right answer
        print("Well done! You got the right answer! Here’s the next     question")                                          
    return True

#Asks the user for his/her name
username = input("What is your name?      ")                                          
print("Hi {}! Welcome to the Arithmetic quiz!".format(username))

#The amount of correct questions the user starts with (default)
correct_answers =     0                                                              
#The amount of questions that are going to be asked
num_questions =     10                                                               
#Loops the process
for i in     range(num_questions):                                                   
if test():
    correct_answers +=1


#Prints out the final score
print("{}: You got {}/{} questions     correct.".format(                                                     
#Along with the username
    username,                                                                    
#And the right number of correct answers
        correct_answers,                                                              
#Out of 10 (the original number of questions asked)
num_questions,        

))                                                      

0 个答案:

没有答案