incorrectPassword= True
while incorrectPassword:
password = input("type in your password: ")
if len(password) < 8:
print("your password must be 8 characters long")
if len(password) >24:
print("Your password must be shorter than 24 characters")
elif not any(i.isdigit() for i in password):
print("you need a number in your password")
elif not any(i.isupper() for i in password):
print("you need a capital letter in your password")
elif not any(i.islower() for i in password):
print("you need a lowercase letter in your password")
incorrectPassword = False
How can I only allow certain characters (like !, $, %, ^, &, *, (, ), -, _, = or +) as needed input?
I would use regex, but to do it in a similar fashion to your other tests:
any(i not in '!$%^&*()-_=+' for i in password)
you can simply use
elif " " in password:
#print error
or use Python's re package to define what characters are allowed in your password
Related
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)
I've been trying to figure this out my own, but I couldn't come up with solutions for this. I did come across to SpecialSym["$", "#", "#"] but I wasn't able to work that one into this code.
print("Password is incorrect, please try again...")
passW()
You can do this by adding the condition which would check whether any of the characters is in the list ["$", "#", "#"] or not.
The updated code would be:
import re #regular expression
print("Please enter a password to log in...")
def passW():
while True:
password=input("Enter a password:\n")
if password=="Y0urC0llege":
print("Logging in...")
print("Your login was successful.")
print("Welcome, Professor.")
break
elif len(password) < 10:
print("Please make sure your password is as least 10 characters long.")
elif re.search("[0-9]", password) is None:
print("Please contain as least 1 number in your password.")
elif re.search("[A-Z]", password) is None:
print("Please contain 1 capital letter in your password")
elif re.search("[$##]", password) is None:
print("Please contain as least 1 character symbol in your password.")
else:
print("Password is incorrect, please try again...")
passW()
Hope it helps.
You have to take special characters in a variable after that you can check the condition like below:
SpecialSym = ['!','#','#'] # You can add as many symbols you want.
elif not any(char in SpecialSym for char in password):
print("Please contain as least 1 character symbol in your password.")
I am making a password checker and a generator with a menu, the password checker by it's self works fine but the menu does not work along with the code and I've tried the menu by it's self and that does not work either. These are the errors that I am receiving:
Traceback (most recent call last):
File "C:/Users/Jasiu Czajka/PycharmProjects/untitled/First Code.py", line 41, in <module>
mainmenu()
File "C:/Users/Jasiu Czajka/PycharmProjects/untitled/First Code.py", line 24, in mainmenu
passwordchecker()
NameError: name 'passwordchecker' is not defined
I'm not sure what I've done wrong, so please help if you can.
I use pycharm and python 3.6.3
import re
def mainmenu():
print("*******************************************************************")
print(" Welcome to the Password Checker & Generator ")
print('*******************************************************************')
print("-------------------------------------------------------------------")
print("This program can be used to check a password to see if it is strong")
print("-------------------------------------------------------------------")
print("This Program can be used to generate strong passwords")
print("-------------------------------------------------------------------")
print("1. Password Checker")
print("-------------------------------------------------------------------")
print("2. Password Generator")
print("-------------------------------------------------------------------")
print("3. Exit")
print("-------------------------------------------------------------------")
print("*******************************************************************")
while True:
try:
selection = int(input("Enter choice: ")) # Making selection a variable
if selection == 1:
passwordchecker()
break
elif selection == 2:
passwordgenerator()
break
elif selection == 3:
exit()
break
else:
print("Invalid Choice. Enter 1-3")
mainmenu()
except ValueError:
print("Invalid Choice. Enter 1-3")
exit()
mainmenu()
def passwordchecker():
print("***************************************************************")
print(" PASSWORD CHECKER ")
print("***************************************************************")
print(" ")
print("---------------------------------------------------------------")
print("The password must be at least 8 characters, and a maximum of 24")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 uppercase letter")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 lowercase letter")
print("---------------------------------------------------------------")
print("The password must at least have 1 number in it")
print("---------------------------------------------------------------")
print('The password must have at least 1 symbol')
print("Allowed Symbols: !, $, %, ^, &, *, (, ), _, -, +, =, ")
print("---------------------------------------------------------------")
incorrectpassword = True
while incorrectpassword:
password = input("Type in your password: ")
if len(password) < 8:
print("Your password must be at least 8 characters long")
elif len(password) > 24:
print("Your password must be maximum 24 characters long")
elif not any(i.isdigit() for i in password):
print("You need a number in your password")
elif not any(i.isupper() for i in password):
print("You need a capital letter in your password")
elif not any(i.islower() for i in password):
print("You need a lowercase letter in your password")
elif re.search('[!, $, %, ^, &, *, (, ), _, -, +, =,]', password) is None:
print("You need a symbol in your password")
else:
print("Your password has all the characters needed")
incorrectpassword = False
passwordchecker()
mainmenu()
def passwordgenerator():
print("Work In Progress")
import re
def passwordchecker():
print("***************************************************************")
print(" PASSWORD CHECKER ")
print("***************************************************************")
print(" ")
print("---------------------------------------------------------------")
print("The password must be at least 8 characters, and a maximum of 24")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 uppercase letter")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 lowercase letter")
print("---------------------------------------------------------------")
print("The password must at least have 1 number in it")
print("---------------------------------------------------------------")
print('The password must have at least 1 symbol')
print("Allowed Symbols: !, $, %, ^, &, *, (, ), _, -, +, =, ")
print("---------------------------------------------------------------")
incorrectpassword = True
while incorrectpassword:
password = input("Type in your password: ")
if len(password) < 8:
print("Your password must be at least 8 characters long")
elif len(password) > 24:
print("Your password must be maximum 24 characters long")
elif not any(i.isdigit() for i in password):
print("You need a number in your password")
elif not any(i.isupper() for i in password):
print("You need a capital letter in your password")
elif not any(i.islower() for i in password):
print("You need a lowercase letter in your password")
elif re.search('[!, $, %, ^, &, *, (, ), _, -, +, =,]', password) is None:
print("You need a symbol in your password")
else:
print("Your password has all the characters needed")
incorrectpassword = False
def mainmenu():
print("*******************************************************************")
print(" Welcome to the Password Checker & Generator ")
print('*******************************************************************')
print("-------------------------------------------------------------------")
print("This program can be used to check a password to see if it is strong")
print("-------------------------------------------------------------------")
print("This Program can be used to generate strong passwords")
print("-------------------------------------------------------------------")
print("1. Password Checker")
print("-------------------------------------------------------------------")
print("2. Password Generator")
print("-------------------------------------------------------------------")
print("3. Exit")
print("-------------------------------------------------------------------")
print("*******************************************************************")
while True:
try:
selection = int(input("Enter choice: ")) # Making selection a variable
if selection == 1:
passwordchecker()
break
elif selection == 2:
passwordgenerator()
break
elif selection == 3:
exit()
break
else:
print("Invalid Choice. Enter 1-3")
mainmenu()
except ValueError:
print("Invalid Choice. Enter 1-3")
exit()
mainmenu()
passwordchecker()
mainmenu()
def passwordgenerator():
print("Work In Progress")
It seems you have called some functions before they were defined. Place passwordgenerator() and passwordchecker() before mainmenu() and then call them as you please.
Also, may I suggest putting this program in a loop, and
make that loop dependent on a variable. It would be much more elegant that way. Second, rename your functions like:
mainMenu()
passwordGenerator()
passwordChecker()
It looks more professional. Good luck!
You need to move your call to mainmenu() to below the definitions for passwordchecker() and passwordgenerator(). Otherwise, they won't be defined when mainmenu() tries to call them.
import re
def mainmenu():
print("*******************************************************************")
print(" Welcome to the Password Checker & Generator ")
print('*******************************************************************')
print("-------------------------------------------------------------------")
print("This program can be used to check a password to see if it is strong")
print("-------------------------------------------------------------------")
print("This Program can be used to generate strong passwords")
print("-------------------------------------------------------------------")
print("1. Password Checker")
print("-------------------------------------------------------------------")
print("2. Password Generator")
print("-------------------------------------------------------------------")
print("3. Exit")
print("-------------------------------------------------------------------")
print("*******************************************************************")
while True:
try:
selection = int(input("Enter choice: ")) # Making selection a variable
if selection == 1:
passwordchecker()
break
elif selection == 2:
passwordgenerator()
break
elif selection == 3:
exit()
break
else:
print("Invalid Choice. Enter 1-3")
mainmenu()
except ValueError:
print("Invalid Choice. Enter 1-3")
exit()
def passwordchecker():
print("***************************************************************")
print(" PASSWORD CHECKER ")
print("***************************************************************")
print(" ")
print("---------------------------------------------------------------")
print("The password must be at least 8 characters, and a maximum of 24")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 uppercase letter")
print("---------------------------------------------------------------")
print("The Password must contain at least 1 lowercase letter")
print("---------------------------------------------------------------")
print("The password must at least have 1 number in it")
print("---------------------------------------------------------------")
print('The password must have at least 1 symbol')
print("Allowed Symbols: !, $, %, ^, &, *, (, ), _, -, +, =, ")
print("---------------------------------------------------------------")
incorrectpassword = True
while incorrectpassword:
password = input("Type in your password: ")
if len(password) < 8:
print("Your password must be at least 8 characters long")
elif len(password) > 24:
print("Your password must be maximum 24 characters long")
elif not any(i.isdigit() for i in password):
print("You need a number in your password")
elif not any(i.isupper() for i in password):
print("You need a capital letter in your password")
elif not any(i.islower() for i in password):
print("You need a lowercase letter in your password")
elif re.search('[!, $, %, ^, &, *, (, ), _, -, +, =,]', password) is None:
print("You need a symbol in your password")
else:
print("Your password has all the characters needed")
incorrectpassword = False
passwordchecker()
def passwordgenerator():
print("Work In Progress")
mainmenu()
mainmenu()
I am working on an assignment for password validation where the program keeps asking the user for a valid password until one is given. I am having trouble checking the input string for special characters. Currently the program accepts the password even if their is no special characters. Also I would like to implement a feature that terminates the loop after 3 unsuccessful attempts but am not sure which loop to implement the count in.
Here is my code:
import re
specialCharacters = ['$', '#', '#', '!', '*']
def passwordValidation():
while True:
password = input("Please enter a password: ")
if len(password) < 6:
print("Your password must be at least 6 characters.")
elif re.search('[0-9]',password) is None:
print("Your password must have at least 1 number")
elif re.search('[A-Z]',password) is None:
print("Your password must have at least 1 uppercase letter.")
elif re.search('specialCharacters',password) is None:
print("Your password must have at least 1 special character ($, #, #, !, *)")
else:
print("Congratulations! Your password is valid.")
break
passwordValidation()
There is no need to use regular expression for something so simple. How about:
elif not any(c in specialCharacters for c in password):
or
specialCharacters = set('$##!*')
...
elif not specialCharacters.intersection(password):
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.