gpt4 book ai didi

python - 多个 if 语句 - "else"仍然可以使用吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:12 24 4
gpt4 key购买 nike

我正在尝试编写多个 if 语句来检查密码是否满足所有条件,而不是使用 if-elif 语句,它可以工作但一次只能验证一个条件。

我的代码似乎不起作用。当我输入包含字母和数字但太长/太短的密码时,代码的输出告诉我它太长/太短但也会触发“else”条件。然后代码不会循环返回。

谁能帮我理解这里的概念?非常感谢。

import re


while True :
password = input('Enter a password')
if not len(password) >= 6:
print('password too short')
if not len(password) <= 12:
print('password too long')
if not re.search(r'[a-z]', password):
print('password must contain at least a lowercase alphabet')
if not re.search(r'[0-9]', password):
print('password must contain at least a number')
else:
print('your password is fine')
break

最佳答案

你想写这样的东西

import re

while True :
ok = True
password = input('Enter a password')
if not len(password) >= 6:
print('password too short')
ok = False
if not len(password) <= 12:
print('password too long')
ok = False
if not re.search(r'[a-z]', password):
print('password must contain at least a lowercase alphabet')
ok = False
if not re.search(r'[0-9]', password):
print('password must contain at least a number')
ok = False
if ok:
print('your password is fine')
break

关于python - 多个 if 语句 - "else"仍然可以使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com