当我这样做的时候
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
答案 0 :(得分:2)
在elif
和if
:
else
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
答案 1 :(得分:-1)
问题是代码中有两个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语句测试,表明以前的条件已经完成。