我的程序是一个简单的算术测验,但我想知道如何使它不只是停止时,我不输入整数
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")
将对
int(input())
的调用包装在try-except
子句中。 尝试将str
类型的值转换为int
将始终引发ValueError
exception所以,无论您想在哪里捕获这个非法的转换,也就是说,无论何时调用
int(input())
,都要在try中包装它,除了为了handle它:不要为了保持问题总数相同而增加
except
子句中的questionNo
计数器相关问题 更多 >
编程相关推荐