2

当我这样做时

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
4

2 回答 2

2

在和elif之间使用:ifelse

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需要链接任意数量的 s,在这种情况下,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
于 2017-01-22T12:31:49.840 回答
-1

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

但是,如果您不需要此功能,只需将第二个替换为ifan即可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 语句来测试前面的条件是否得到满足。

于 2017-01-22T02:08:28.827 回答