password checker - str.isdigit() doesn't seem to be working in python -


i'm working on password checker checks if string valid password. have check if there @ least 8 characters, must consist of letters , digits , last 2 characters must digits.

it seems work far other password.isdigit(). password comes out valid , doesn't. suggestions?

# gets users password password = input('enter string password: ') # splices last 2 characters of password lasttwo = password[-2:]  # checks password if less 8 characters while len(password) < 8:     print('the password entered short.')     print()     password = input('enter string password: ')      # checks password if composed of letters , numbers     while password.isalnum() == false:         print('your password has special characters not allowed.')         print()         password = input('enter string password: ')      # checks spice verify digits     while lasttwo.isdigit() == false:         print('your last 2 characters of password must digits.')         print()         password = input('enter string password: ')  print('your password valid.') 

there handful of issues provided code. particularly, check subsequent rules while len(password) < 8. if give password of length 10, rules never checked. additionally, don't update lasttwo each new password attempted

one way fix replace several while statements if...elif..elif...else... wrapped in overall while statement, follows:

# gets users password password = input('enter string password: ')  while true:     # checks password if less 8 characters     if len(password) < 8:         print('the password entered short.')     # checks password if composed of letters , numbers     elif not password.isalnum():         print('your password has special characters not allowed.')     # checks spice verify digits     elif not password[:-2].isdigit():         print('your last 2 characters of password must digits.')     else:         # here when rules true         break      print()     password = input('enter string password: ')  print('your password valid.') 

this should work intended it. while we're @ it, why not tell user every rule password has broken? ui point of view, helps keep user informed.

if store information message alongside whether relevant rule has been met, can work out of rules have been broken, so:

valid_password = false  while not valid_password:     # password     password = input('\nenter string password: ')     # applies checks     checks = {         '- end in 2 digits': password[-2].isdigit(),         '- not contain special characters': password.isalnum(),         '- on 8 characters long': len(password) > 8     }     # if values in dictionary true, password valid.     if all(checks.values()):         valid_password = true     # otherwise, return rules violated     else:         print('this password not valid. passwords must:\n{}'.format(             '\n'.join([k k, v in checks.items() if not v])))  print('your password valid.') 

Comments