How to count how many numbers in a variable - python

I'm trying to create a password reset program, which includes counting how many lowercase and uppercase are in said password. If the password is less than 8 letters or contains no uppercase or lowercase, it rejects the password, however the program crashes when there are numbers as it can not calculate how many numbers there are:
import time
print("Please create a new password")
password = input()
print("Re-enter your password")
password2 = input()
if password != password2:
print("Your Passwords Do Not Match")
time.sleep(2)
print("Please create a new password")
password = input()
print("Re-enter your password")
password2 = input()
valid = 0
lower = 0
upper = 0
for c in password:
if c.islower():
lower += 1
elif c.isupper():
upper += 1
else:
pass
char_count = upper + lower
if char_count >= 8:
valid += 1
if lower >= 1:
valid += 1
else:
print("Your Password Has No Lowercase Letters")
if upper >= 1:
valid += 1
else:
print("Your Password Has No Uppercase Letters")
else:
print("Your Password Doesn't Have 8 Characters")
if valid == 3:
print("Your Password Is Valid. Welcome")
else:
print("Your Password Is Invalid. Sorry")
time.sleep(2)
print("Please create a new password")
password = input()
print("Re-enter your password")
password2 = input()
EDIT: Thanks For Your Help But My Program Works! Thanks Guys!

You can get the count of all digits in the password by summing a list of 1s/0s, a 1 meaning the character is a digit, 0 otherwise:
>>> password= "134jhie92"
>>> sum([1 if c.isdigit() else 0 for c in password])
5
or:
>>> sum(map(str.isdigit, password))
5
This can also be done with your other parameters:
lower = sum(map(str.islower, password))
upper = sum(map(str.isupper, password))
nums = sum(map(str.isdigit, password))
Although it would make more sense to extend your if statement (as suggested by panatale1):
lower = 0
upper = 0
nums = 0
for c in password:
if c.islower():
lower += 1
elif c.isupper():
upper += 1
elif c.isdigit():
nums += 1

Create a variable called num and change your for loop:
for c in password:
if c.isdigit():
num += 1
elif c.islower():
lower += 1
elif c.isupper():
upper += 1
else:
pass

Related

Username and Password Variable Incorrect

Helo guys
i'm trying to create a login system, it's run normally when i input username and password directlt after i signed up on my own code, but when i try to login using false username or password bruteforcely variable "p" or "u" is changed by itself. I dunno why it's happened here's my code
sorry for my bad english and my bad code(it's weird"), i'm new in programming language and python "i've tried my best" so if anyone wants to fix my code or something else please help me, 1 more question is there any code to loop when the input is false? i used a function that call the lastest function if the input is false
import os
import sys
import re
def apus():
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE)
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
def main():
os.system("cls")
print(""""
Welcome To X Bank
Enter Any Key To Continue
""")
x = input()
menu()
def menu():
os.system('cls')
print("------------------------------------------------------------------------")
print('''
Don't Have An Account Yet? Please Sign Up
1. Login
2. Sign Up
''')
print("------------------------------------------------------------------------")
opsimenu()
def opsimenu():
#os.system("cls")
a = int(input())
os.system("cls")
if a == 1:
login()
elif a == 2:
signu()
else:
menu()
def ulog():
login()
def login():
os.system('cls')
print("Enter Your Username And Password \n \n")
C = input("Username = ")
D = input("Password = ")
while True:
if C == u and D == p:
login2()
break
else:
print("Your Username Or Password Is Incorrect")
ulog()
def login2():
os.system("cls")
print("Login Succesful")
def signu():
global Address
global Name
#print("\n ")
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Name = str(input("Full Name:"))
Address = str(input("Address: "))
enteruser()
def signup():
enteruser()
def enteruser():
global u
Username = (input("Username:"))
flag = 0
while True:
if (len(Username) < 8):
flag = -1
break
elif not re.search("[a-z]", Username):
flag = -1
break
elif not re.search("[A-Z]", Username):
flag = -1
break
elif not re.search("[0-9]", Username):
flag = -1
break
elif not re.search("[!##$%^&*]", Username):
flag = -1
break
elif re.search("\s", Username):
flag = -1
break
else:
flag = 0
break
if flag == -1:
apus()
#print("Invalid Username")
signup()
u = Username
pw()
def ulangpw():
pw()
def pw():
global p
Password = str(input("Password:"))
while True:
if (len(Password) < 8):
flag = -1
break
elif not re.search("[a-z]", Password):
flag = -1
break
elif not re.search("[A-Z]", Password):
flag = -1
break
elif not re.search("[0-9]", Password):
flag = -1
break
elif not re.search("[!##$%^&*]", Password):
flag = -1
break
elif re.search("\s", Password):
flag = -1
break
else:
flag = 0
break
if flag == -1:
print("Invalid Password")
apus()
apus()
ulangpw()
p = Password
os.system("cls")
validating()
def validating():
print(" ---------------------------------------------------")
print(" You have successfully created your account.\n Press Any Key To Login. \n \n Validating Your Data")
print("\n • Full Name ="+ Name)
print(" • Address ="+ Address)
print(" • Username ="+ u)
print(" • Password ="+ p)
print(" ---------------------------------------------------")
#p = Password
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N "))
while True:
if confirm == "Y" or confirm =="y":
login()
break
elif confirm == "N" or confirm == 'n':
os.system("cls")
signu()
break
else:
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N ="))
break
>main()
python wont print this:
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Because it is syntax for uncommenting text
""" multiline comment line 1
multiline comment line 2 """
You have to use quotes like
print("Hi Dad")

The simplest way to check for UPPERCASES

Here, I am trying to validate a password and check to see if there are capitals and numbers in the password before saving it as a different variable. Using functions, is it possible for me to do so. The indents have changed on the format, so please help me with other aspects.
def length(long):
while len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
if password.isupper() = True:
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
This is what I have now done:
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
errors = []
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
bool Capcheck = False
bool DigCheck = False
while CapCheck = False or CapCheck = False:
length(password)
if not any(x.isupper() for x in password):
errors.append("Your password needs at least 1 capital.")
else:
CapCheck = True
break
if not any(x.islower() for x in password):
errors.append("......... Why?")
if not any(x.isdigit() for x in password):
errors.append("You need to have at least 1 digit")
else:
DigCheck = True
break
if errors:
print(" ".join(errors))
password = input("Please enter a stronger password")
Apparently there is an error with my boolean here, please help
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
Try using islower():
password.islower()
This returns True if there are no Uppercases in the password.
Now if you want to check if it has number i it, you have to follow #jubnvz:
any(i.isdigit() for i in password)
or a more specific way:
any(map(str.isdigit, password))
And for your password entries, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
break
If you want to and a confirm password too, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
passwordcon = input(""Please confirm your password:")
if passwordcon == password:
break
else:
print("Your passwords do not match, try again'")
any([p.isupper() for p in password])

Python: Problems with final result of password strength program

Lately, I was presented with a challenge exercise, aiming to create a program which checks the length of a password and then assesses it strength based on it being mixed case and containing numbers.
The part which determines whether the length of the password is suitable works absolutely fine, however the rest of the program seems to not work. I am unsure whether this is a logical or syntax error of some sort. I hope you can help me in some way.
import re
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
Password = ""
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers in password
def hasNumbers(s):
return any(i.isdigit() for i in s)
#checks if password is all upper case
Is_upper = Password.isupper()
if Is_upper == "True":
Score = Score - 1
else:
Score = Score + 1
#checks if passwords is all lower case
Is_lower = Password.islower()
if Is_lower == "False":
Score = Score - 1
else:
Score = Score + 1
#checks if password contains a number
Number_presence = hasNumbers(Password)
if Number_presence == "True":
Score = Score + 1
else:
Score = Score - 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if Only_numbers == "True":
Score = Score - 1
#outputs weak, medium or strong to user based on score value
if Score <= 0:
print("Your password is absolutely rubbish!")
if Score == 1:
print("Your password is weak, you should try again.")
elif Score == 2:
print("Your password is medium, it should be OK.")
elif Score == 3:
print("Your password is strong, it is absolutely fine.")
else:
print("The program has experienced a problem. Please try again!")
exit()
Python has some pre-defined statements that are part of it. One of these is Boolean : True and False
When you call the built in isupper() function in python, it doesn't return a string, it returns a Boolean, and so does most other similar functions.
True and "True" are very different things. True is a Boolean type value, while "True" is just a string. This is a common mistake all new python programmers make, due to the fact that in python, you don't have to specify different value types like you do in c++ or Java. It is still important to know about data types as to avoid such fatal errors and to further advance your knowledge in Python :)
To read more about Data Types: http://developer.rhino3d.com/guides/rhinopython/python-datatypes/
I have looked at your code and fixed some mistakes ( not tested ):
import re
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
Password = ""
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers in password
def hasNumbers(s):
return any(i.isdigit() for i in s)
#checks if password is all upper case
Is_upper = Password.isupper()
if Is_upper == True:
Score = Score - 1
else:
Score = Score + 1
#checks if passwords is all lower case
Is_lower = Password.islower()
if Is_lower == False:
Score = Score - 1
else:
Score = Score + 1
#checks if password contains a number
Number_presence = hasNumbers(Password)
if Number_presence == True:
Score = Score + 1
else:
Score = Score - 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if Only_numbers == True:
Score = Score - 1
#outputs weak, medium or strong to user based on score value
if Score <= 0:
print("Your password is absolutely rubbish!")
if Score == 1:
print("Your password is weak, you should try again.")
elif Score == 2:
print("Your password is medium, it should be OK.")
elif Score == 3:
print("Your password is strong, it is absolutely fine.")
else:
print("The program has experienced a problem. Please try again!")
exit()
*As a sidenote, you can make your program less verbose by just completley removing the == True and == False from your code. By default, if and while statements will check if a value is True or False, and run the code indented under them if it is True

How to replace a double while loop?

The program, which assesses password strength, initially checks whether the length of the password is correct (6-12) and whether the password contains extented ASCII characters, i.e. 127-255.
The problem I have is that if the user first inputs a password which is too short or too long, the program then doesn't check for extended characters in the next password, inputted by the user and vice-versa, with checking for extended characters first.
I implemented a double while loop, if that's the correct way of calling it, however it still didn't bring the desired effect.
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers
def hasNumbers(s):
return any(i.isdigit() for i in s)
#defines function for checking for presence of letters
def hasLetters(s):
return any(i.isalpha() for i in s)
#defines function for checking for presence of special characters
def hasSpecial(s):
return any(ord(i) < 48 for i in s)
#checks if password contains letters
Letter_presence = hasLetters(Password)
if not Letter_presence:
Score = Score - 1
Improvements.append("letters")
else:
Score = Score + 1
#checks if password is all upper case
Is_upper = Password.isupper()
if not Is_upper:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if passwords is all lower case
Is_lower = Password.islower()
if not Is_lower:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if password contains a number
Number_presence = hasNumbers(Password)
if not Number_presence:
Score = Score + 0
Improvements.append("numbers")
else:
Score = Score + 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if not Only_numbers:
Score = Score + 0
else:
Score = Score - 1
Improvements.append("other characters")
#checks if password contains special characters
Special_presence = hasSpecial(Password)
if not Special_presence:
Score = Score + 0
Improvements.append("special characters, such as '$'")
else:
Score = Score + 1
#outputs weak, medium or strong password to user and suggest improvements
if Score <= 2:
print("The program is processing your password...")
time.sleep(2)
print("Your password isn't acceptable! Please try again.")
print("Next time, remember to include", Improvements)
if Score == 3:
print("The program is processing your password...")
time.sleep(2)
print("Your password is weak, you should try again.")
print("Next time, remember to include", Improvements)
elif Score == 4:
print("The program is processing your password...")
time.sleep(2)
print("Your password is medium, it should be OK.")
print("Next time, remember to include", Improvements)
elif Score == 5:
print("The program is processing your password...")
time.sleep(2)
print("Your password is strong, it is absolutely fine.")
I would suggest you to write validator, a function that looks like this:
def validate_password(password):
... # check score, symbols and other, print whatever you want
return score
And then call it in a way like that one:
pass = input('Enter your password')
score = validate_password(pass)
while score <= 3:
pass = input('Enter another password')
score = validate_password(pass)
You can implement such scenario like below:
check_pass function will check for length of function
def hasExtended(s):
return any(ord(i) > 127 for i in s)
check_pass = lambda x: x>=6 and x<=12 # check for range of input value
password=input("Password: ")
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
else:
print("Do not use extended ascii characters, use password with minimum length of 6 and maximum length of 12")
to be more precise about error you can use nesting in below way:
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
elif check_pass(len(password)) and hasExtended(password):
print("do not use extended ascii character")
elif not check_pass(len(password)) and hasExtended(password):
print("password length should be between 6 to 12")
similarly if you want to check for invalid length of minimum lenght and maximum length separately.
If you wish to check all condition separately and then show success or failure you can do like below:
def verify_password(password):
if len(password) < 6:
print("require minimum 6 characters")
if len(password) > 12:
print("can not use more then 12 characters")
if hasExtended(password):
print("use only valid ascii characters")
else:
print("valid password")
return True
while not verify_password(password): # loop will never stops unless valid password or used break statement within
password = input("Password: ")
The function will check for three different condition if condition satisfied message will be printed else it will continue executing, at the end if it is valid password instead of printing anything it will print valid password and return True instead of None.
Try this code , and instead of while just use if in first checking codition of Extended_presence , You don't need while there because its already in the scope of previous while loop :
import re
print([chr(i) for i in range(127,200)])
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
if Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
output:
Please enter a password:hel¢
Your password is too short . It has to be no shorter than 6 characters .
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hellllo#
Why don't you delegate your password check to a function and separate the user input from checking the password? That way you can ask the user as many times as you want without complex jumps. Something like:
def validate_password(password):
if len(password) < 6:
return 0, "Your password is too short, it has to be no shorter than 6 characters."
elif len(password) > 12: # why, tho?
return 0, "Your password is too long, it has to be no longer than 12 characters."
# these can be optimized but I'll leave that as an exercise for you
if any(ord(i) > 127 for i in password): # again, why?!
return 0, ("Your password contains characters from the extended ASCII list. "
"Please don't use these.")
score = 0
improvements = []
if any(i.isalpha() for i in password):
score += 1
if password.isupper() or password.islower():
score -= 1
improvements.append("upper and lower case letters")
else:
score += 1
else:
score -= 1
improvements.append("letters")
if any(i.isdigit() for i in password):
score += 1
if password.isdigit():
score -= 1
improvements.append("other characters")
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("numbers")
if any(ord(i) < 48 for i in password):
score += 1
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("special characters such as '$'")
return score, "Next time remember to include: {}".format(", ".join(improvements))
And now you can call it from wherever you want, as many times as you need:
while True:
candidate = input("Please enter a password: ")
print("The program is processing your password...") # why? this happens in an instant
score, message = validate_password(candidate)
time.sleep(2) # why are we making people wait for no reason?
if score <= 1:
print(message)
print("Please try again.")
elif score == 2:
print("Your password is weak, you should try again.")
print(message)
elif score == 3:
print("Your password is medium, it should be OK.")
print(message)
break
elif score == 4:
print("Your password is strong, it is absolutely fine.")
break
print("Accepted password: " + candidate)
And you can get an output as:
Please enter a password: dfld
The program is processing your password...
Your password is too short, it has to be no shorter than 6 characters.
Please try again.
Please enter a password: dfldsadlslads
The program is processing your password...
Your password is too long, it has to be no longer than 12 characters.
Please try again.
Please enter a password: dflds°
The program is processing your password...
Your password contains characters from the extended ASCII list. Please don't use these.
Please try again.
Please enter a password: ddlllsd
The program is processing your password...
Next time remember to include: upper and lower case letters, numbers, special characters
such as '$'
Please try again.
Please enter a password: ddlllsd12
The program is processing your password...
Next time remember to include: upper and lower case letters, special characters such as '$'
Please try again.
Please enter a password: Ddlllsd12
The program is processing your password...
Your password is medium, it should be OK.
Next time remember to include: special characters such as '$'
Accepted password: Ddlllsd12

How to check the "password" for numbers in python

I have set up a program to change a "password". I have it checking to see if it is at least 8 characters, contains a capital letter and has a number, and if it does not meet this criteria, it asks for the password again. I have everything working except the checking for a number and I was wondering if someone could help.
npwv = 1
while npwv == 1:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if npwc.isupper()== False:
if npwc.islower()== False:
if len(npwc) >= 8:
if str.isdigit(npwc) == True:
npw=npwc
print("Your password has been changed")
else:
print("Your password must contain a number")
npwv = 1
else:
print("Your password must contain at least 8 characters.")
npwv = 1
else:
print("Your password must contain at least 1 upper case character.")
npwv = 1
else:
print ("Passwords don't match")
npwv = 1
You are checking if the password itself is fully uppercase or composed of numbers. What you need to check if if the characters in the password match this criteria.
has_upper = any([c.isupper() for c in npwc])
has_digit = any([c.isdigit() for c in npwc])
You can also use regular expressions.
By the way, you should prefer getpass to get the password from the user.
Have you considered using .isalnum()?
>>> foo = "123asd"
>>> foo
'123asd'
>>> foo.isalnum()
True
>>>
Edit: Judging by the other answers, I am not sure what are you looking for, could explain it with examples?
I would suggest using sets, and the string package from stdlib for your list of acceptable characters.
I would also suggest refactoring a bit to remove a lot of the nesting with if / else branches.
import string
upper = set(list(string.uppercase))
lower = set(list(string.lowercase))
numbers = set(list(string.digits))
while True:
npw = input("Please enter new password: ")
npwc = input("Please confirm new password: ")
if npwc != npw:
print("Passwords don't match")
continue
if len(npcw) < 8:
print("Your password must contain at least 8 characters.")
continue
chars = set(list(npwc))
if not upper.intersection(chars):
print("Your password must contain at least 1 upper case character.")
continue
if not lower.intersection(chars):
print("Your password must contain at least 1 lower case character.")
continue
if not numbers.intersection(chars):
print("Your password must contain a number")
continue
npw = npwc
print("Your password has been changed")
break
This can be made more compact but yeah..
while True:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if any(x.isupper() for x in npwc):
if any(x.islower() for x in npwc):
if len(npwc) >= 8:
if any (x.isdigit() for x in npwc):
npw=npwc
print("Your password has been changed")
#break # you probably want to exit the loop at this point
else:
print("Your password must contain a number")
else:
print("Your password must contain at least 8 characters.")
else:
print("Your password must contain at least 1 upper case character.")
else:
print("Your password must contain at least 1 lower case character.")
else:
print("Passwords don't match")
This looks like a job for regular expressions. Solution below:
import re
def password_validator(password):
if len(password) < 8:
return False, "Your password must contain at least 8 characters"
if not re.match('.*[0-9]', password):
return False, "Your password must contain a number"
if not re.match('.*[A-Z]', password):
return False, "Your password must contain at least 1 upper case character."
if not re.match('.*[a-z]', password):
return False, "Your password must contain at least 1 lower case character."
return True, "Your password has been changed"
while True:
npw = input("Please enter new password.")
npwc = input("Please confirm new password")
if npw != npwc:
print("Passwords don't match")
continue
is_valid, message = password_validator(npw)
print(message)
if is_valid:
break
You could also validate the whole thing in one go as:
pattern = """
(?=.*[a-z]) # use positive lookahead to see if at least one lower case letter exists
(?=.*[A-Z]) # use positive lookahead to see if at least one upper case letter exists
(?=.*\d) # use positive lookahead to see if at least one digit exists
[A-Za-z0-9##$%^&+=]{8,} # match any character in [] at least 8 times
"""
pwd_validator = re.compile(pattern, re.VERBOSE)
if pwd_validator.match(password):
# legit password
else:
# no match ask again
Hope this helps. The re.VERBOSE just makes this regular expression self-documenting so a lot easier to understand in future.

Categories