Home > Net >  Why does my if statement return the wrong prompt?
Why does my if statement return the wrong prompt?

Time:12-19

I am sure the answer is right in front of my face but I can't seem to figure out how to fix the return on my first if statement when I input the right conditions.

create_password = input("Enter password here: ")

if len(create_password) > 6 and create_password.isdigit() > 0:
    print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
    print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
    print("Password must include a number")
else:
    print("Your password sucks")

Let's say I enter elephant100, I am trying to get the prompt to be "Your account is ready!". But to my dismay, it prints "Password must include a number" and I cannot figure out why. My other conditions match the right input but that is the only one that does not work.

CodePudding user response:

.isdigit() method returns True if all the characters are digits, otherwise False. Hence it returns False in this case since your string contains letters like e, l, p etc. So the statement print("Your account is ready!") will never be executed.

CodePudding user response:

Turns out I needed to use isalnum(), isnumeric(), and isalpha() to fix my problem. Thank you Muhammed Jaseem for helping me figure it out! Here is my revised code.

if create_password.isnumeric() == True:
    print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
    print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
    print("Your account is ready!")
else:
    print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")
  • Related