superepicprogrammer
superepicprogrammer

Reputation: 83

How to use one else statement with multiple if statements

So I'm trying to make a login prompt and I want it to print 'Success' only if there are no errors. This is the code I'm using:

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')

Would there be any way to make this code shorter? I want to make it show all the errors at once so I'm not using elif.

Upvotes: 6

Views: 106

Answers (4)

Samwise
Samwise

Reputation: 71444

Another approach: accumulate the errors into a list, and then you can check the error list for truthiness instead of re-checking all the error conditions. This also saves you from having to maintain another piece of state and have another line of code in each if block to update it.

errors = []
if not is_email(email):
    errors.append('Not a valid email')
if not is_name(name):
    errors.append('Not a valid name')
if password != confirmPassword:
    errors.append('Passwords don\'t match')
if not is_secure(password):
    errors.append('Password is not secure')
print("\n".join(errors or ["Success"]))

Upvotes: 1

bituniverse
bituniverse

Reputation: 98

How about this?

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])

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83527

One way is to use a flag:

has_errors = False

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

if not has_errors:
    print("Success!")

Upvotes: 1

Grismar
Grismar

Reputation: 31319

A way to avoid repeating the tests:

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')

It's not shorter, but it's clear and saves the extra comparisons, so it's faster and not as wasteful.

Upvotes: 4

Related Questions