如何将一个else语句与多个if语句一起使用

2024-06-02 04:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图做出一个登录提示,我希望只有在没有错误的情况下才打印“Success”。这是我正在使用的代码:

if not is_email(email) or not is_name(name) or password != confirmPassword or not is_secure(password):
    if not is_email(email):
        print('Not a valid email')
    if not is_name(name):
        print('Not a valid name')
    if password != confirmPassword:
        print('Passwords don\'t match')
    if not is_secure(password):
        print('Password is not secure')
else:
    print('Success')

有没有办法缩短代码?我想让它一次显示所有的错误,所以我不使用elif


Tags: or代码nameifisemail错误not
3条回答

避免重复测试的一种方法:

ok = True
if not is_email(email):
    print('Not a valid email')
    ok = False
if not is_name(name):
    print('Not a valid name')
    ok = False
if password != confirmPassword:
    print('Passwords don\'t match')
    ok = False
if not is_secure(password):
    print('Password is not secure')
    ok = False
if ok:
    print('Success')

它不短,但清晰,节省了额外的比较,因此速度更快,不浪费时间

一种方法是使用标志:

has_errors = False

if not is_email(email):
    print(...)
    has_errors = True
...

if not has_errors:
    print("Success!")

这个怎么样

flags = [is_email(email), is_name(name), password != confirmPassword, is_secure(password)]
prints = ['Not a valid email', 'Not a valid name', 'Passwords don\'t match', 'Password is not secure']

for index in range(len(flags)):
    if flags[index] == False:
        print(prints[index])

相关问题 更多 >