想知道如何添加一些代码,使我的程序能够处理输入的字母

时间:2015-10-11 11:04:31

标签: python math

我的程序是一个简单的算术测验但是我想知道如何制作它以便它不会在我不输入整数时停止。

questionNo=0
score=0

name=input("What is your name?")
print("Welcome ",name," to your arithmetic quiz!")

time.sleep(1)

while questionNo<10:
    function=random.randint(1,3)
    if function==1:
        rNumber1=random.randint(1,100)
        rNumber2=random.randint(1,100)
        print("Question is : ", rNumber1," + ",rNumber2)
        guess=int(input("What is the answer?"))
        ans=rNumber1+rNumber2
        if ans==guess:
            print("Correct!")
            score+=1
            time.sleep(1)
        else:
            print("Wrong")
            time.sleep(1)

    elif function==2:
        rNumber1=random.randint(1,10)
        rNumber2=random.randint(1,10)
        print("Question is : ", rNumber1," X ",rNumber2)
        guess=int(input("What is the answer?"))
        ans=rNumber1*rNumber2
        if ans==guess:
            print("Correct!")
            score+=1
            time.sleep(1)
        else:
            print("Wrong")
            time.sleep(1)

    else:
        rNumber1=random.randint(1,100)
        rNumber2=random.randint(1,100)
        print("Question is : ", rNumber1," - ",rNumber2)
        guess=int(input("What is the answer?"))
        ans=rNumber1-rNumber2
        if ans==guess:
            print("Correct!")
            score+=1
            time.sleep(1)
        else:
            print("Wrong")
            time.sleep(1)
    questionNo+=1

print("Well done ",name,"! You got ",score,"/10")

1 个答案:

答案 0 :(得分:0)

int(input())条款中给try-except打电话。 尝试将str类型的值转换为int将始终提升ValueError exception

因此,无论您想要捕获此非法转换,只要调用int(input()),请将其包含在try-except中,以便 handle 它:

try:
    guess = int(input("What is the answer?"))
except ValueError:
    print("You must enter a number as the answer!")
    continue

并且不要增加questionNo子句中的except计数器,以便总共保留相同数量的问题。