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])
Related
def isValidPassword(password):
if (len(password)<=8):
print("Password must be at least 8 characters or more.")
return False
if any(digit.isdigit() for digit in password):
print("Password must have at least single digit or more.")
return False
if any(digit.isupper() for digit in password):
print("Password must have at least one uppercase letter or more.")
return False
if any(digit.islower() for digit in password):
print("Password must have at least one lowercase letter or more.")
return False
return True
def confirmedPassword():
isSecure = False ; isMatch = False
password = "" ; reenterPassword = ""
while(isSecure == False):
password = input("Enter your password: ")
isSecure = isValidPassword(password)
while(isMatch == False):
reenterPassword = input("\nPlease re-enter your password: ")
if (password == reenterPassword):
isMatch = True ; print("Password is confirmed. Thank you.")
print("The password you entered is approved and safe.")
else:
(password == reenterPassword)
isMatch = False ; print("Password is not confirmed. Please try again.")
confirmedPassword()
If anyone can please help. It is appreciated. I had a hard time figuring out how to condense a failed list of criteria printed out when I input "ABC" to run the program.
I changed your code to print out all the issues with the password before returning whether or not it is a valid password. I also fixed all of the if statements you had to correctly capture the password issue.
def isValidPassword(password):
valid = True
if (len(password) < 8):
print("Password must be at least 8 characters or more.")
valid = False
if not any(digit.isdigit() for digit in password):
print("Password must have at least single digit or more.")
valid = False
if not any(digit.isupper() for digit in password):
print("Password must have at least one uppercase letter or more.")
valid = False
if not any(digit.islower() for digit in password):
print("Password must have at least one lowercase letter or more.")
valid = False
return valid
def confirmedPassword():
isSecure = False ; isMatch = False
password = "" ; reenterPassword = ""
while(not isSecure):
password = input("Enter your password: ")
isSecure = isValidPassword(password)
while(not isMatch):
reenterPassword = input("\nPlease re-enter your password: ")
if (password == reenterPassword):
isMatch = True
print("Password is confirmed. Thank you.")
print("The password you entered is approved and safe.")
else:
isMatch = False
print("Password is not confirmed. Please try again.")
confirmedPassword()
I am trying to create a login and register program in simple console python, however when trying to make a loop that will check if the username contains a digit I keep getting the error, ("UnboundLocalError: local variable 'includesDigit' referenced before assignment") the code is:
def register():
incluesDigit = False
print("")
print("Create Account")
print("~~~~~~~~~~~~~~")
print("Username: ")
registerUsername = input("")
for char in registerUsername:
if char.isdigit():
includesDigit = True
if includesDigit == True:
print("Please enter a username that does not contain a number")
register()
print("Password: ")
registerPassword = input("")
if len(registerPassword) < 5:
print("Please enter a password that is atleast 5 characters")
register()
if len(registerPassword) > 15:
print("Please enter a password that is less than or fifteen character")
logCreate = open("C:\\Desktop\\Login Program\\Accounts\\" + registerUsername + ".txt", "w")
logCreate.write(registerPassword)
logCreate.close()
login()
There is a typo in line 2.
incluesDigit = False
Should be
includesDigit = False
I'm checking my password for this criteria
be at least 10 characters long
contain at least 1 capital letter
contain at least 1 number
contain at least one of the characters $, #, %, &, or *
not contain any spaces
my code:
password = input("enter a password ")
def passwordIsOk (password):
symbols = "$#%&*"
if len (password) > 10:
if any(i.isupper() for i in password):
if any(i.isdigit() for i in password):
if " " not in password:
for i in range(0,5):
if symbols[i] in password:
passwordValid = True
if passwordValid == True:
print("ok buddy")
else:
print("Password must contain $#%&*")
else:
print("Password must not contain spaces")
else:
print("Password must have at least 1 number")
else:
print("Password must have at least 1 capital letter")
else:
print("Password must be greater than 10 characters")
passwordIsOk(password)
It works, but It just don't feel right :(
You can avoid this kind of nested if structure by inverting the conditions. This makes the code much more readable, and puts the error messages next to the conditions which check for those errors.
def passwordIsOk(password):
symbols = "$#%&*"
if len (password) <= 10:
print("Password must be greater than 10 characters")
elif not any(i.isupper() for i in password):
print("Password must have at least 1 capital letter")
elif not any(i.isdigit() for i in password):
print("Password must have at least 1 number")
elif " " in password:
print("Password must not contain spaces")
elif not any(s in password for s in symbols):
print("Password must contain at least one of " + symbols)
else:
print("ok buddy")
password = input("enter a password ")
passwordIsOk(password)
Putting aside the nested if structure, you could use any to check if it contains any special symbol:
password = input("enter a password ")
def passwordIsOk (password):
symbols = "$#%&*"
if len (password) > 10:
if any(i.isupper() for i in password):
if any(i.isdigit() for i in password):
if " " not in password:
if any(s in password for s in symbols):
passwordValid = True
print("ok buddy")
else:
print("Password must contain $#%&*")
else:
print("Password must not contain spaces")
else:
print("Password must have at least 1 number")
else:
print("Password must have at least 1 capital letter")
else:
print("Password must be greater than 10 characters")
passwordIsOk(password)
It is arguably easier to read and it will print all the problems with the password if you invert and flatten out the if statements using the passwordValid flag like so:
password = input("enter a password ")
def passwordIsOk (password):
passwordValid = True
symbols = "$#%&*"
if len (password) <= 10:
passwordValid = False
print("Password must be greater than 10 characters")
if not any(i.isupper() for i in password):
passwordValid = False
print("Password must have at least 1 capital letter")
if not any(i.isdigit() for i in password):
passwordValid = False
print("Password must have at least 1 number")
if " " in password:
passwordValid = False
print("Password must not contain spaces")
if not any(s in password for s in symbols):
passwordValid = False
print("Password must contain at least one of $#%&*")
if passwordValid:
print("ok buddy")
passwordIsOk(password)
A common method in password validation are regular expressions.
# coding: utf-8
import re
from getpass import getpass
def passwordIsOk(password):
if len(password) < 10:
print("Password must be greater than 10 characters")
elif not re.search('[A-Z]',password):
print("Password must have at least 1 capital letter")
elif not re.search('[0-9]',password):
print("Password must have at least 1 number")
elif not re.search('[$#%&*]',password ):
print("Password must contain at least one of $#%&*")
elif " " in password:
print("Password must not contain spaces")
else:
print("ok buddy")
pswd = getpass("Enter password: ")
passwordIsOk(pswd)
My program works perfectly fine but instead of returning EVERYTHING wrong with a password it will only return one problem back.
Example:
The password is ASD123 (the problems being less than 10 characters, and no symbols). The program only returns "The password is less than 10 characters"
passwordisokk = True
def passwordisOK():
while True:
passwordisokk = input("Please enter a password so we can validate:")
if len(passwordisokk) < 10:
print(" Your password should be 10 characters,please enter more characters")
passwordisokk = False
print(passwordisokk)
elif re.search("[0-9]",passwordisokk) is None:
print("Your password needs a number,please enter one")
passwordisokk = False
print(passwordisokk)
elif re.search("[A-Z]",passwordisokk) is None:
print(" Your password needs a capital letter,please enter one")
passwordisokk = False
print(passwordisokk)
elif re.search("[$,#,%,&,*]",passwordisokk) is None:
print(" You password needs one of these symbols:$,#,%,&,*. Please enter one")
passwordisokk = False
print(passwordisokk)
elif re.search("[ ]",passwordisokk):
passwordisokk = False
print("No spaces when entering your password please")
print(passwordisokk)
else:
passwordisokk = True
print(passwordisokk)
break
passwordisOK()
Just change the elif and else to if statements.
import re
passwordisokk = True
def checkPasswordisOK():
while True:
password = input("Please enter a password so we can validate:")
if len(password) < 10:
print(" Your password should be 10 characters,please enter more characters")
passwordisokk = False
print(passwordisokk)
if re.search("[0-9]",password) is None:
print("Your password needs a number,please enter one")
passwordisokk = False
print(passwordisokk)
if re.search("[A-Z]",password) is None:
print(" Your password needs a capital letter,please enter one")
passwordisokk = False
print(passwordisokk)
if re.search("[$,#,%,&,*]",password) is None:
print(" You password needs one of these symbols:$,#,%,&,*. Please enter one")
passwordisokk = False
print(passwordisokk)
if re.search("[ ]",password):
passwordisokk = False
print("No spaces when entering your password please")
print(passwordisokk)
if not passwordisokk:
passwordisokk = True
print(passwordisokk)
break
checkPasswordisOK()
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