这个Python验证代码有什么问题?

2024-03-29 06:47:16 发布

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

我试图用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.

Tags: thetoansweraddifthatisas
1条回答
网友
1楼 · 发布于 2024-03-29 06:47:16

函数通常位于其他代码的顶部,不需要缩进:

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

相关问题 更多 >