Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多个if语句-can";否则";还可以用吗?_Python_If Statement - Fatal编程技术网

Python 多个if语句-can";否则";还可以用吗?

Python 多个if语句-can";否则";还可以用吗?,python,if-statement,Python,If Statement,我试图编写一个多if语句来检查密码是否满足所有条件,而不是使用一个if-elif语句,该语句可以工作,但一次只验证一个条件 我的代码似乎不起作用。当我输入一个包含字母和数字但太长/短的密码时,代码的输出告诉我它太长/短,但也会触发“else”条件。然后,代码不会循环返回 有谁能帮我理解这里的概念吗?非常感谢 import re while True : password = input('Enter a password') if not len(password) >

我试图编写一个多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
重新导入
尽管如此:
密码=输入('输入密码')
如果不是len(密码)>=6:
打印('密码太短')

如果不是len(password)您希望编写类似

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
重新导入
尽管如此:
ok=正确
密码=输入('输入密码')
如果不是len(密码)>=6:
打印('密码太短')
ok=错误

如果不是len(密码)则
否则
仅适用于最后一个
如果


相反,您可以收集列表中的所有消息并打印它们,或者如果列表为空,则发出“ok”消息并中断循环。因此,
if
s将添加到列表中而不打印。最后一个
else
将是一个if,用于检查列表是否为空。如果
,则重复列表并打印每个元素。这样你的程序应该正好长3行。在我将其发布到代码中之前,我先让您试一试:)

ELSE语句被用作IF/ELIF语句链的“catch all”

您的示例没有如您所期望的那样工作的原因是,如果您已经编写了,您的ELSE只适用于最后一个示例。您认为使用ELIF可以解决这个问题是正确的,但不会按照您的意愿行事

为了使这个逻辑起作用,我建议在任何IF语句之前创建一个新变量'valid=True'。然后在每个IF下打印错误消息并设置valid=False

然后你可以用你的ELSE替换你的ELSE
如果有效==True:


希望这有助于

在每次指示密码错误的情况下使用关键字
继续
。在这种情况下,while循环将从头开始,省略进一步的命令。同时,移除else@Slowpoke你不会看到所有的错误,如果你使用的密码是
1234
,你只会触发“太短”而不是另一个errors@PatrickArtner好的,明白了。这与FFF建议代码解决方案完全相同-只是更多的文本和更少的代码。。。