Python3 如果如果否则

Python3 if if else

当我这样做的时候

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
if x[0].islower():
    print("The first password letter must be uppercase")
else:
    print("Password saved")
    password = x

我得到

>The password must contain at least 9 letters
>Password saved

我应该怎么做才能让程序停止:

>The password must contain at least 9 letters

问题是代码中有两个 if 过滤器。我假设您想要 "The password must contain at least 9 letters""The first password letter must be uppercase" 如果满足两个条件都可以返回的结构。

但是,如果您不需要此功能,只需将第二个 if 替换为 elif 即可。

如果您需要此功能,请尝试以下操作:

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
if x[0].islower():
    print("The first password letter must be uppercase")
if len(x) >= 9 and x[0].isupper():
    print("Password saved")
    password = x

这只是添加了第三个 if 语句来测试前面的条件是否满足。

ifelse之间使用elif

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
elif x[0].islower():
    print("The first password letter must be uppercase")
else:
    print("Password saved")
    password = x

elif只有在if没有被执行,并且elif的条件为真时才会执行。您还可以根据需要链接任意多个 elif,在这种情况下,将执行条件匹配的第一个 elif


更新: 因为 OP 在评论中说他希望一次显示所有错误,所以我会使用这样的东西:

x = "Hello"
errors = []
if len(x) <= 9:
    errors.append("The password must contain at least 9 letters")
if x[0].islower():
    errors.append("The first password letter must be uppercase")

if errors:
    print('\n'.join(errors))
else:
    print("Password saved")
    password = x