Write a function that checks whether a string is valid password.
Rules: Must have at least 8 characters A password must consist of only letters and digits A password must contain at least 2 digits
Heres what I have so far, what am i doing wrong? thank you
def getPassword():
password = input("Enter password: ")
return password
def validPassword(password):
if len(password) >= 8:
valid = True
if password.alnum():
valid = True
if password.isdigit < 2:
valid = True
else:
return False
def main():
password = validPassword()
if validPassword(password):
print(password, "is valid")
else:
print(password, "is invalid")
main()
This seems like a homework assignment so I'll try and stay from directly answering, but more try to push you in the right direction.
Your first bit of code that will run will be
Uh oh,
validPassword(password)
takes an argument and doesn't get a password, maybe you meantgetPassword()
Lets go through the logic of
validPassword(password)
Line by linelets check if the length of the string is more than 8 characters, if it is, we initialize the variable valid and set it to True
Then regardless of what has happened, we call alnum, ( which I don't think is a function in python, probably meant isalnum. ) to check if all the characters in the password are numbers. If it is we initialize the variable valid and set it to True. You may say, but I already initialized it, well not really, in python there is scope.
Then we check if the passwords method
isdigt
is less than 2, maybe you meantpassword.isdigit()
I am really being meticulous as it is unclear your proficiency in programming or python. But if you meantpassword.isdigit() < 2
then you are asking if the password is a digit and if yes, is it less than 2. If it is we initialize the variable valid and set it to True.Then if and only if
password.isdigit() < 2
is false, we return false.Here are some pointers:
Hopefully my line by line explanation has helped you find some of your errors and a better idea of how to continue, if not, feel free to amend your question so that we get a better idea of how to help.
Happy coding.
According to the following reference here for the
isdigit()
method :Which doesn't hold for your case
The method will only let you know if the given string is a digit, not how many digits are in a string. To achieve that you will need to play around a bit.
You may use the following
Furthermore, your code has a small mistake as you will never return back True. Here is a possible fix:
Additioanly, in your main you have a small typo when getting the password from the user
Should be
Therefore here is a complete code