Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 492
LCY Avatar asked Sep 03 '25 03:09

LCY


1 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
like image 123
FFF Avatar answered Sep 07 '25 18:09

FFF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!