You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入与验证码生成数值一致却验证失败,代码问题排查求助

验证码验证功能问题排查

你的代码核心问题是类型不匹配:

  • 变量a是random.randint()生成的整数类型
  • input()函数获取的用户输入是字符串类型
  • 字符串和整数直接用==比较永远不相等,所以即使输入内容看起来一致,也会判定为错误

修复方法(二选一即可)

方法1:将用户输入转为整数

修改判断逻辑,同时建议增加输入合法性校验,避免非数字输入导致报错:

from captcha.image import ImageCaptcha
import random
import os

a = random.randint(1111, 9999)

image = ImageCaptcha(width=250,height=90)

text = a
generated_imge = image.generate(str(text))

image.write(str(a), 'captcha.png')
while True:
    user_input = input('What is the captcha:')
    try:
        if int(user_input) == a:
            print('Correct')
            break
        else:
            print('Incorrect Try again')
    except ValueError:
        print('Please enter a valid number')

方法2:将生成的验证码转为字符串存储

初始化验证码时直接转为字符串,后续全程用字符串类型比较:

from captcha.image import ImageCaptcha
import random
import os

a = str(random.randint(1111, 9999))  # 直接生成字符串类型的验证码

image = ImageCaptcha(width=250,height=90)

text = a
generated_imge = image.generate(text)

image.write(a, 'captcha.png')
while True:
    user_input = input('What is the captcha:')
    if user_input == a:
        print('Correct')
        break
    else:
        print('Incorrect Try again')

内容的提问来源于stack exchange,提问作者Lord_Kordec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:25:17