我正在尝试使用Python进行数学测验并且为此我想制作一个验证规则,这意味着如果用户放置的东西不是数字,它会再次询问它们,因为它是无效的。
我试图做到这一点,我想出的错误与我正常做的一样。有帮助吗?
if operator=="+":
#this is a if statement which states that if the operator is
#add then the answer should be num1 add num2 as the add function was randomly
#picked
def inputNumber(message):
while True:
try:
useranswer=int(input(actualquestion))
except ValueError:
print("This is not an integar!")
continue
else:
return usseranswer
break
actualanswer=num1 + num2 #this states that the answer is equal to the rando
#ly picked num1 add num2 as the operator is add.
if useranswer==actualanswer:
#this if function states that if the users answer is equal to the real answer
#the programme worked out before hand.
score+=1 #if the answer is right you will add 1 to the score
questions+= 1 #you will add 1 to the question also as 1 qw has been asked.
答案 0 :(得分:1)
您的函数通常位于其他代码的顶部,不需要缩进:
def inputNumber(message):
while True:
try:
return int(input(message))
except ValueError:
print("This is not an integer!")
result = inputNumber("Please enter a number: ")
print(result)
例如,以下内容可以满足您的需求:
Please enter a number: hello
This is not an integer!
Please enter a number: 123
123