python - 如何在 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 语句,但不明白该怎么做。
如果有人可以通过改进代码来解决这个问题,那就太好了。
提前致谢
解决方案
尝试分解您的代码并在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
推荐阅读
- angular - 如何使用 TypeScript 在类中创建静态常量?
- css - Simple_form 样式(去除边框和文本对齐中心)
- android - contentResolver 中的 loadThumbnail() 是否会从默认 Thumbnails 文件夹中加载缩略图?
- webpack - 如何仅为 .mod.css 文件启用 css 模块?下一页
- python - 将行向量数据框除以标量数据框
- css - 如何将伪 webkit 滚动条的 z 索引设置在所有元素之上
- hibernate - Grails 多对多连接表
- asp.net - VB.NET/ASP.NET 使用 OAuth 发送自动 Gmail 外发邮件
- mysql - 需要 mysqlclient 1.3.13 或更新版本;你有 0.9.3
- node.js - 等待每个 playStream() 完成,然后再开始读取下一个