Reputation: 97
Hey guys I am new to Python and I wrote this password program in Python but the first 'elif' statement doesn't execute for some reason. If i input a password that has less than 5 characters AND has a special character in it, it just says that it's too short whereas it's supposed to say it's too short AND you can't use special characters. Any help would be appreciated.
password = 'Chubz'
count = 3
listA = list("'#$%&\()@*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c'")
while count >= 0:
x = input('What is the pass? ')
if x in listA:
print(f" {count} You can't use special characters ")
count -= 1
elif x in listA and len(x) < 5:
print(f"{count} You can't use special characters and the pass is too short")
count -= 1
elif len(x) < 5:
print(f'{count} Pass is too short')
count -= 1
elif x != password:
print(f'{count} Try again')
count -= 1
else:
print('Access Granted')
break
Upvotes: 2
Views: 488
Reputation:
The if statement is true and after that it will exit... it will never reach to first elif. you need to add the seconds condition as well in elif.
if x in listA and len(x) > 5::
print(f" {count} You can't use special characters ")
count -= 1
Basically if statements work best if they are mutually exclusive.
Upvotes: 1
Reputation: 8508
Instead of checking it in the order you have, why don't you check it in the below order. It will ensure the elif gets executed only if the previous condition is not satisfied.
Also, you need to check for each character of x instead of the whole string of x.
To do that you can use any()
any([True for i in x if i in listA])
This will be set to True if any of the characters in x
is a special character.
password = 'Chubz'
count = 3
listA = list("'#$%&\()@*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c'")
while count >= 0:
x = input('What is the pass? ')
if len(x) < 5:
print(f'{count} Pass is too short')
count -= 1
elif any([True for i in x if i in listA]):
print(f" {count} You can't use special characters ")
count -= 1
elif x != password:
print(f'{count} Try again')
count -= 1
else:
print('Access Granted')
break
Upvotes: 1
Reputation: 195
To fix this, just put
elif x in listA and len(x) < 5: print(f"{count} You can't use special characters and the pass is too short") count -= 1
Before the first if statement so this would become the if statement instead of elif.
The interpreter reads from up to down so it saw that a special character was used to directly printed it.
SO the code would be:
if x in listA and len(x) > 5:
print(f" {count} You can't use special characters ")
count -= 1
Upvotes: 1
Reputation: 77827
if x in listA:
print(f" {count} You can't use special characters ")
count -= 1
elif x in listA and len(x) < 5:
There is no way to reach this latter clause: it is a subset of the first one. Anything that qualifies for the elif
has already been handled by the if
. You need to switch the order of checks.
Upvotes: 3