首页 > 解决方案 > 如何在 Python 中创建一个简单的输入数学验证码?

问题描述

我正在努力在 Python 中创建一个简单的输入数学验证码。

这是我尝试过的

from random import randint

x = randint(1,10)
y = randint(1,10)

z = x + y

captcha_ans = input(f"What is the sum of {x} + {y} ? ")
captcha_ans = int(captcha_ans)

if captcha_ans == z:
    print("Great")
else:
    print("Try Again")

我希望如果答案是错误的,代码不应该只是要求再试一次,而是重复相同的问题,有/没有改变数字。

我尝试为此使用 while 语句,但不明白该怎么做。

如果有人可以通过改进代码来解决这个问题,那就太好了。

提前致谢

标签: python

解决方案


尝试分解您的代码并在while循环中检查答案。检查评论以获取解释

from random import randint

# create a function that will take input from use
# and check if it is correct or not
# if correct it will return True
# otherwise it will return False
def take_answer_from_user():
    x = randint(1,10)
    y = randint(1,10)

    z = x + y

    captcha_ans = input(f"What is the sum of {x} + {y} ? ")
    captcha_ans = int(captcha_ans)
    return captcha_ans == z

# For the first time, take input from user and store the True, False
# result in the variab;e is_correct
is_correct = take_answer_from_user()

# check if is_correct is False, that means user did not provide correct
# answer
# If wrong, use while loop unless answer is correct
while(not is_correct):
    print("Try Again")
    is_correct = take_answer_from_user()
# if user provides correct answer, then wile loop will be closed and
# finally print great
print('Great')
What is the sum of 2 + 9 ? 4
Try Again
What is the sum of 4 + 7 ? 5
Try Again
What is the sum of 10 + 6 ? 16
Great

推荐阅读