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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With