Multiple if statements - can "else" still be used?

Viewed 1967

I'm trying to write a multiple if statements to check if a password meets all conditions, rather than using an if-elif statement which works but only verifies one condition at a time.

My code doesn't seem to work. When I input a password that contains alphabets and numbers but is too long/short, the output of the code tells me it's too long/short but also triggers the "else" condition. The code then does not loop back.

Please can anyone help me to understand the concept here? Many thanks.

import re


while True :
    password = input('Enter a password')
    if not len(password) >= 6:
        print('password too short')
    if not len(password) <= 12:
        print('password too long')
    if not re.search(r'[a-z]', password):
        print('password must contain at least a lowercase alphabet')
    if not re.search(r'[0-9]', password):
        print('password must contain at least a number')
    else:
        print('your password is fine')
        break
3 Answers

You want to write something like

import re

while True :
    ok = True
    password = input('Enter a password')
    if not len(password) >= 6:
        print('password too short')
        ok = False
    if not len(password) <= 12:
        print('password too long')
        ok = False
    if not re.search(r'[a-z]', password):
        print('password must contain at least a lowercase alphabet')
        ok = False
    if not re.search(r'[0-9]', password):
        print('password must contain at least a number')
        ok = False
    if ok:
        print('your password is fine')
        break

The else only applies to the last if!

You could, instead, collect all messages in a list and print them, or if the list is empty emit the “ok” message and break the loop. So the ifs would add to list and not print. The last else would be an if that checks if the list is empty. Past that if, iterate the list and print each element. Your program should be exactly 3 lines longer that way. I’ll let you take a stab before I post it in code :)

The ELSE statement is used as a 'catch all' for a chain of IF/ELIF statements.

The reason why your example isn't working as you expect is that your ELSE only applies to the last IF you've written. You are correct that using ELIF would resolve this, but would not act how you are intending.

For this logic to work, I'd recommend creating a new variable 'valid = True' before any of your IF statements. Then under each IF print your error message and set valid = False.

Then you can replace your ELSE with if valid == True:

Hope this helps

Related