Reputation: 29
I have to build a program where you enter a password. The password must contain at least 8 characters, start with a letter, have both upper and lower case letters, have no spaces and at least 2 digits.
I have everything else down except for the last 2.
I tried using a for loop to see if there are spaces or digits, but it will only work if the whole password consists of spaces or digits. If there is a number or a space, if prints off the error message for as many characters there are in the password, not just for how many digits or spaces there are. I know this is happening because of the for loop, but I'm stuck on how to fix it.
Here is what I have so far:
again = 'y'
while again == 'y':
minimum_characters = 8
error = 0
print('Password must contain 8 characters, start with a letter,')
print(' have no blanks, at least one uppercase and lowercase letter,')
print(' and must contain at least 2 digits.')
password = input('Enter a password: ')
passlength = len(password)
#validity checks for errors
if passlength < minimum_characters:
error += 1
print (error, '- Not a valid password. Must contain AT LEAST 8 characters. PW entered has', passlength, '.')
if not password[0].isalpha():
error += 1
print(error, '- The password must begin with a letter.')
if password.isalpha():
error += 1
print(error, '- The password must contain at least 2 digits.')
if password.isupper():
error += 1
print(error, '- You need at least one lower case letter.')
if password.islower():
error += 1
print(error,'- You need at least one upper case letter.')
again = input('Test another password? (Y or N): ')
again = again.lower()
Upvotes: 2
Views: 12064
Reputation: 499
User regular expression
import re
sequence = "1Sentence1e"
if re.match("(?:\d.*?){2,}", sequence):
print("Match!")
else:
print("Not match!")
Fiddle: http://tpcg.io/73SyIc
Regular expression match javascript syntax
Upvotes: 1
Reputation: 22690
To report an error when the string contains less than 2 digits you can use:
if sum(map(str.isdigit, password)) < 2:
Also, your checks for uppercase and lowercase letters are incorrect:
if password.isupper():
checks if all characters are uppercase. To check if any character is uppercase you can use:
any(map(str.isupper, password))
Upvotes: 0
Reputation: 4010
"(...) have no spaces and at least 2 digits."
A few options that will work for counting the number of occurrences of any character/digit. Simply replace with what you need (digits and spaces in the examples):
if any([x for x in password if x == " "]):
# 1 or more spaces in password
if password.count(" ") > 0:
# 1 or more spaces in password
if len([x for x in password if x.isdigit()]) < 2:
# less than 2 digits
Upvotes: 0
Reputation: 4021
if " " in password:
error += 1
print(error, '- Not a valid password. It contains spaces.')
if len([x for x in pwd if x.isdigit()]) < 2:
error += 1
print(error, '- The password must contain at least 2 digits.')
Upvotes: 3