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

2024-06-26 14:41:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序是一个简单的算术测验,但我想知道如何使它不只是停止时,我不输入整数

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")

Tags: nameinputiftimeissleeprandomwhat
1条回答
网友
1楼 · 发布于 2024-06-26 14:41:44

将对int(input())的调用包装在try-except子句中。 尝试将str类型的值转换为int将始终引发ValueErrorexception

所以,无论您想在哪里捕获这个非法的转换,也就是说,无论何时调用int(input()),都要在try中包装它,除了为了handle它:

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

不要为了保持问题总数相同而增加except子句中的questionNo计数器

相关问题 更多 >