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

为什么这段Python代码无法检测输入密码中的空格?

密码合法性校验代码问题修复

问题根因

  • 长度校验属于密码字符串的全局判断,不需要放在for循环内部重复执行
  • 现有逻辑只要遍历到任意一个非空格字符且长度符合要求,就会把contra标记为True,后续就算遍历到空格也不会把标记改回False,因此带空格的密码只要长度达标就会误判为合法
  • 原代码长度判断逻辑为>8,和「至少8位」的要求不符,需改为>=8才会包含长度刚好为8位的合法密码

修复后代码(保留for循环练习用法)

contra = True

pass_=input("Introduce tu contraseña: ")

# 先判断长度是否合规
if len(pass_) < 8:
    contra = False
else:
    # 遍历字符判断是否存在空格
    for i in pass_:
        if i == " ":
            contra = False
            # 找到空格后可提前终止循环,无需继续遍历
            break

if contra:
    print("password ok")
else:
    print("wrong password")

简化写法(无需练习for循环时可用)

直接用字符串in运算符判断空格,代码更简洁:

pass_=input("Introduce tu contraseña: ")
if len(pass_) >= 8 and " " not in pass_:
    print("password ok")
else:
    print("wrong password")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:15:01