Python 想知道如何添加一些代码,使我的程序能够处理正在输入的字母
我的程序是一个简单的算术测验,但我想知道如何使它,使它不只是停止时,我没有输入一个整数Python 想知道如何添加一些代码,使我的程序能够处理正在输入的字母,python,math,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:
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")
questionNo=0
分数=0
name=输入(“你叫什么名字?”)
打印(“欢迎”,姓名,“参加您的算术测验!”)
时间。睡眠(1)
而questionNo则将对int(input())
的调用包装在一个try except
子句中。
尝试将类型为str
的值转换为int
将始终引发ValueError
因此,无论您想在何处捕获这种非法转换,也就是说,无论何时调用int(input())
,都要在try中包装它,除非是为了它:
try:
guess = int(input("What is the answer?"))
except ValueError:
print("You must enter a number as the answer!")
continue
不要在except
子句中增加questionNo
计数器,以保持总的问题数相同。在进行必要的更改后添加代码,讨论如何使其可读,而不仅仅是工作。您使用的是Python2.x还是Python3.x,而每次触发异常时都会触发一个新问题。也就是说,如果你想避免提问,你可以输入一些字符……当然可以。如果你想“避免”一个问题,只需增加questionNo
,如果不想,就不要。你的异常处理总是会过早地结束循环,从而创建一个新问题。我认为这是一个错误,但你的里程可能会有所不同。