Validation of a Password - Python - python

So I have to create code that validate whether a password:
Is at least 8 characters long
Contains at least 1 number
Contains at least 1 capital letter
Here is the code:
def validate():
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif not password.isdigit():
print("Make sure your password has a number in it")
elif not password.isupper():
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
validate()
I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

You can use re module for regular expressions.
With it your code would look like this:
import re
def validate():
while True:
password = raw_input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
validate()

r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')
this code will validate your password with :
min length is 6 and max length is 20
at least include a digit number,
at least a upcase and a lowcase letter
at least a special characters

password.isdigit() does not check if the password contains a digit, it checks all the characters according to:
str.isdigit(): Return true if all characters in the string are digits
and there is at least one character, false otherwise.
password.isupper() does not check if the password has a capital in it, it checks all the characters according to:
str.isupper(): Return true if all cased characters in the string are
uppercase and there is at least one cased character, false otherwise.
For a solution, please check the question and accepted answer at check if a string contains a number.
You can build your own hasNumbers()-function (Copied from linked question):
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
and a hasUpper()-function:
def hasUpper(inputString):
return any(char.isupper() for char in inputString)

Example:
class Password:
def __init__(self, password):
self.password = password
def validate(self):
vals = {
'Password must contain an uppercase letter.': lambda s: any(x.isupper() for x in s),
'Password must contain a lowercase letter.': lambda s: any(x.islower() for x in s),
'Password must contain a digit.': lambda s: any(x.isdigit() for x in s),
'Password must be at least 8 characters.': lambda s: len(s) >= 8,
'Password cannot contain white spaces.': lambda s: not any(x.isspace() for x in s)
}
valid = True
for n, val in vals.items():
if not val(self.password):
valid = False
return n
return valid
def compare(self, password2):
if self.password == password2:
return True
if __name__ == '__main__':
input_password = input('Insert Password: ')
input_password2 = input('Repeat Password: ')
p = Password(input_password)
if p.validate() is True:
if p.compare(input_password2) is True:
print('OK')
else:
print(p.validate())

You are checking isdigit and isupper methods on the entire password string object not on each character of the string. The following is a function which checks if the password meets your specific requirements. It does not use any regex stuff. It also prints all the defects of the entered password.
#!/usr/bin/python3
def passwd_check(passwd):
"""Check if the password is valid.
This function checks the following conditions
if its length is greater than 6 and less than 8
if it has at least one uppercase letter
if it has at least one lowercase letter
if it has at least one numeral
if it has any of the required special symbols
"""
SpecialSym=['$','#','#']
return_val=True
if len(passwd) < 6:
print('the length of password should be at least 6 char long')
return_val=False
if len(passwd) > 8:
print('the length of password should be not be greater than 8')
return_val=False
if not any(char.isdigit() for char in passwd):
print('the password should have at least one numeral')
return_val=False
if not any(char.isupper() for char in passwd):
print('the password should have at least one uppercase letter')
return_val=False
if not any(char.islower() for char in passwd):
print('the password should have at least one lowercase letter')
return_val=False
if not any(char in SpecialSym for char in passwd):
print('the password should have at least one of the symbols $##')
return_val=False
if return_val:
print('Ok')
return return_val
print(passwd_check.__doc__)
passwd = input('enter the password : ')
print(passwd_check(passwd))

''' Minimum length is 5;
- Maximum length is 10;
- Should contain at least one number;
- Should contain at least one special character (such as &, +, #, $, #, %, etc.);
- Should not contain spaces.
'''
import string
def checkPassword(inputStr):
if not len(inputStr):
print("Empty string was entered!")
exit(0)
else:
print("Input:","\"",inputStr,"\"")
if len(inputStr) < 5 or len(inputStr) > 10:
return False
countLetters = 0
countDigits = 0
countSpec = 0
countWS = 0
for i in inputStr:
if i in string.ascii_uppercase or i in string.ascii_lowercase:
countLetters += 1
if i in string.digits:
countDigits += 1
if i in string.punctuation:
countSpec += 1
if i in string.whitespace:
countWS += 1
if not countLetters:
return False
elif not countDigits:
return False
elif not countSpec:
return False
elif countWS:
return False
else:
return True
print("Output: ",checkPassword(input()))
With Regex
s = input("INPUT: ")
print("{}\n{}".format(s, 5 <= len(s) <= 10 and any(l in "0123456789" for l in s) and any(l in "!\"#$%&'()*+,-./:;<=>?#[\]^_`{|}~" for l in s) and not " " in s))
Module import
from string import digits, punctuation
def validate_password(p):
if not 5 <= len(p) <= 10:
return False
if not any(c in digits for c in p):
return False
if not any(c in punctuation for c in p):
return False
if ' ' in p:
return False
return True
for p in ('DJjkdklkl', 'John Doe'
, '$kldfjfd9'):
print(p, ': ', ('invalid', 'valid')[validate_password(p)], sep='')

Sure with regex there are easier answers, but this one of the simplest ways
from string import punctuation as p
s = 'Vishwasrocks#23' #or user input is welcome
lis = [0, 0, 0, 0]
for i in s:
if i.isupper():
lis[0] = 1
elif i.islower():
lis[1] = 1
elif i in p:
lis[2] = 1
elif i.isdigit():
lis[3] = 1
print('Valid') if 0 not in lis and len(s) > 8 else print('Invalid')

The simplest python validation using normal methods
password = '-'
while True:
password = input(' enter the passwword : ')
lenght = len(password)
while lenght < 6:
password = input('invalid , so type again : ')
if len(password)>6:
break
while not any(ele.isnumeric() for ele in password):
password = input('invalid , so type again : ')
while not any(ele.isupper() for ele in password):
password = input('invalid , so type again : ')
while not any(ele not in "[#_!#$%^&*()<>?/|}{~:]" for ele in password):
password = input('invalid , so type again : ')
break

isdigit() checks the whole string is a digit, not if the string contains a digit
Return true if all characters in the string are digits and there is at least one character, false otherwise.
isupper() checks the whole string is in uppercase, not if the string contains at least one uppercase character.
Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
What you need is using the any built-in function:
any([x.isdigit() for x in password]) will return True if at least one digit is present in password
any([x.isupper() for x in password]) will return True if at least one character is considered as uppercase.

Maybe you can use regex expression:
re.search(r"[A-Z]", password)
Check uppercase letters.
re.search(r"[0-9]", password)
Check digits in password.

Python 2.7
The for loop will assign a condition number for each character. i.e. Pa$$w0rd in a list would = 1,2,4,4,2,3,2,2,5. Since sets only contains unique values, the set would = 1,2,3,4,5; therefore since all conditions are met the len of the set would = 5. if it was pa$$w the set would = 2,4 and len would = 2 therefore invalid
name = raw_input("Enter a Password: ")
list_pass=set()
special_char=['#','$','#']
for i in name:
if(i.isupper()):
list_pass.add('1')
elif (i.islower()):
list_pass.add('2')
elif(i.isdigit()) :
list_pass.add('3')
elif(i in special_char):
list_pass.add('4')
if len(name) >=6 and len(name) <=12:
list_pass.add('5')
if len(list_pass) is 5:
print ("Password valid")
else: print("Password invalid")

uppercase_letter = ['A', 'B','C', 'D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z']
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
import re
info ={}
while True:
user_name = input('write your username: ')
if len(user_name) > 15:
print('username is too long(must be less than 16 character)')
elif len(user_name) < 3 :
print('username is short(must be more than 2 character)')
else:
print('your username is', user_name)
break
while True:
password= input('write your password: ')
if len(password) < 8 :
print('password is short(must be more than 7 character)')
elif len(password) > 20:
print('password is too long(must be less than 21 character)')
elif re.search(str(uppercase_letter), password ) is None :
print('Make sure your password has at least one uppercase letter in it')
elif re.search(str(number), password) is None :
print('Make sure your password has at least number in it')
else:
print('your password is', password)
break
info['user name'] = user_name
info['password'] = password
print(info)

Password Complexity conditions:
Must include at least one uppercase character
Must include at least one lowercase character
Must include at least one number
Must include at least one special character
Must have a length of at least 8 and a max of 20
import re
def validate():
while True:
password = raw_input("Enter a password: ")
re_exp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*#?&])[A-Za-z\d#$!#%*?&]{8,20}$"
if re.search(re.compile(regex_exp),password):
print("Your password seems fine")
else:
print("Password doees not matches with password complexity conditions")
break

Or you can use this to check if it got at least one digit:
min(passwd).isdigit()

Related

Where is my mistake? Checking if password is correct in Python

I am new in Python and programming. I am trying to make a program that verifies that the entered password has a certain format. I was pretty sure my code was correct, but obviously...it's not. It won't exit the while loop when the password is in the correct format.
Where is my mistake? Thank you all for your patience!
low = ['abcdefghijklmnopqrstuvwxyz']
up = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
cr = ['#$%&']
digito = ['0123456789']
counter1 = 0
tries = True
while tries:
length = False
May = False
Minus = False
Num = False
Char = False
counter1 += 1
password = input('Password: ')
if len(password) > 7 and len(password) < 16:
length = True
for caracter in password:
if caracter in low:
Minus = True
if caracter in up:
May = True
if caracter in cr:
Char = True
if caracter in digito:
Num = True
if length and May and Minus and Num and Char:
print('Password ok.')
passw = password
tries = False
if counter1 == 5:
print('You had 5 attemps.')
break
The issue is that when you check:
"A" in ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
it returns False. This is because the list ['ABCDEFGHIJKLMNOPQRSTUVWXYZ'] does not contain the element "A". Try to replace the top 4 line with the following code and see if it works:
low = 'abcdefghijklmnopqrstuvwxyz'
up = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cr = '#$%&'
digito = '0123456789'
low, up, cr and digito should all be strings, not a list with only one string in it: low = 'abcdefghijklmnopqrstuvwxyz'. Otherwise only literally "abcdefghijklmnopqrstuvwxyz" is in low, not "a".
Each list should contain separate letters instead of an entire string of the alphabet.
For example, instead of writing
up = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
you should write
up = ['A','B','C','D','E','F','G'...]
A better version of your code might be the following:
tries = True
up = False
low = False
special = False
counter = 0
while tries:
counter += 1
if counter == 5:
print('You had 5 attemps.')
break
password = input("Enter your password: ")
if len(password) > 7 and len(password) < 16:
for char in password:
if char.upper() == char:
up = True
if char.lower() == char:
low = True
if (ord(char) >= 35 and ord(char) <= 38) or ord(char) == 64:
special = True
if up and low and special:
tries = False
print("Password ok")

Python: Random Password Generator

I want o create a Random Password generating program. Passwords shown should have a minimum of 10 digits to a maximum of 20 digits. However, the program didn't capture the length.
My code:
import random
import string
def rpassword():
while True:
length = int(input('\nEnter the length of password: '))
if length < 10:
print("\nWarning: Password length should be more than 10!")
elif length > 20:
print ("\nWarning: Password length should be less than 20!")
else:
print("\nYour password is: ", password)
break
lower = string.ascii_lowercase
upper = string.ascii_uppercase
number = string.digits
symbol = string.punctuation
pswd = lower + upper + number + symbol
passd = random.sample(pswd,length)
password = "".join(passd)
rpassword()
#exampleoutput
#Hello, Welcome to Random Password Generator!
#Enter the length of password: 15
#Your password is: +|VR{c<$k
this will work:
import string
import random
def rpassword():
while True:
length = int(input('\nEnter the length of password: '))
if length < 10:
print("\nWarning: Password length should be more than 10!")
elif length > 20:
print("\nWarning: Password length should be less than 20!")
else:
lower = string.ascii_lowercase
upper = string.ascii_uppercase
number = string.digits
symbol = string.punctuation
pswd = lower + upper + number + symbol
passd = random.sample(pswd, length)
password = "".join(passd)
print("\nYour password is: ", password)
break
rpassword()
output:
Enter the length of password: 15
Your password is: cX7Mg<91G#0-.C"
You need to indent your code to have it happen inside the rpassword function (indent it so it's deeper than the def but not the while), and you also need to print the password after you've generated it, not before:
def rpassword():
while True:
length = int(input('\nEnter the length of password: '))
if length < 10:
print("\nWarning: Password length should be more than 10!")
elif length > 20:
print ("\nWarning: Password length should be less than 20!")
else:
break
# At this point the loop has broken and 10 < length < 20.
lower = string.ascii_lowercase
upper = string.ascii_uppercase
number = string.digits
symbol = string.punctuation
pswd = lower + upper + number + symbol
passd = random.sample(pswd, length)
password = "".join(passd)
# Now we have a valid value for password!
print("\nYour password is: ", password)
rpassword()
I might suggest having this function return the password and printing it outside the function -- that way if you want to do something with the password (like store it somewhere) it's easy to assign it to a value outside of the function instead of (or in addition to) printing it.
def rpassword() -> str:
while True:
length = int(input('\nEnter the length of password: '))
if length < 10:
print("\nWarning: Password length should be more than 10!")
elif length > 20:
print("\nWarning: Password length should be less than 20!")
else:
break
return "".join(random.sample(
string.ascii_lowercase
+ string.ascii_uppercase
+ string.digits
+ string.punctuation,
length
))
print("\nYour password is: ", rpassword())

password generator - letter check

I am trying to build a password generator that would give me passwords that consist of lower case, upper case, numbers and special characters. Below is my code. It generates passwords to the required length but these do not contain characters from each group. Please can someone help to explain what I did wrong?
Many thanks.
import random
lower_case = list("abcdefghijklmnopqrstuvwxyz")
upper_case = list("abcdefghijklmnopqrstuvwxyz".upper())
num = []
for i in range(0, 10):
num.append(i)
s_letters = ["_", "#", "."]
available_char = lower_case + upper_case + num + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
try:
int(user_l) >= 6
except:
print("invalid number")
length()
return int(user_l)
def password_gen(x):
password = []
for i in range(x):
character = random.choice(available_char)
password.append(str(character))
set_a = set(password)
while True:
valid = True
if set_a & set(lower_case) == {}:
password_gen(x)
valid = False
if set_a & set(upper_case) == {}:
password_gen(x)
valid = False
if set_a & set(num) == {}:
password_gen(x)
valid = False
if set_a & set(s_letters) == {}:
password_gen(x)
valid = False
if valid:
print("Your password is " + "".join(password))
print(set_a & set(lower_case))
print(set_a & set(upper_case))
print(set_a & set(num))
print(set_a & set(s_letters))
break
set_password()
Perhaps you could create another list of keys corresponding to each character type (e.g. char_type = [“number”, “special”, “lowercase”, “uppercase”]). Then, prior to choosing a random item from one of those lists, you can randomly choose an item from your “char_type” list. As you approach your desired lengths, you can have checks in place to ensure that if a required type does not yet exist in the string, it will be added prior to hitting the desired character length.
Something like this:
import random
character_types = {}
character_types["lower_case"] = list("abcdefghijklmnopqrstuvwxyz")
character_types["upper_case"] = [char.upper() for char in character_types["lower_case"]]
character_types["num"] = [str(i) for i in range(0, 10)]
character_types["s_letters"] = ["_", "#", "."]
character_types["types"] = [key for key in character_types.keys()]
# available_char = lower_case + upper_case + num + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
if not int(user_l) >= 6:
print("invalid number")
length()
return int(user_l)
def password_gen(x):
password = []
password_types = set()
required_types = 4
for i in range(x):
char_type = random.choice(character_types["types"])
if x - len(password) <= 4:
if "s_letters" not in password_types:
char_type = "s_letters"
elif "lower_case" not in password_types:
char_type = "lower_case"
elif "upper_case" not in password_types:
char_type = "upper_case"
elif "num" not in password_types:
char_type = "num"
character = random.choice(character_types[char_type])
password_types.add(char_type)
password.append(character)
set_a = set(password)
# while True:
# valid = True
# if set_a & set(lower_case) == {}:
# password_gen(x)
# valid = False
# if set_a & set(upper_case) == {}:
# password_gen(x)
# valid = False
# if set_a & set(num) == {}:
# password_gen(x)
# valid = False
# if set_a & set(s_letters) == {}:
# password_gen(x)
# valid = False
# if valid:
print("Your password is " + "".join(password))
print(set_a & set(character_types["lower_case"]))
print(set_a & set(character_types["upper_case"]))
print(set_a & set(character_types["num"])) # This was initially not working because num did not consist of strings, whereas the password did.
print(set_a & set(character_types["s_letters"]))
# break
set_password()
There is no need for the final checks because the rules prevent an invalid password from ever being created. This also prevents us from repeatedly generating passwords such that we may find a valid one.
#azro is also correct in mentioning that your length check does not prevent someone from choosing a length less than 6 (fixed above).
There is an improvement you could make to the above code. Currently, when it checks to make sure all required types exist in the password, it is doing so in a fixed order. As such, it will always append the missing character types in the same order (if none of them exist in the string already). You could instead, determine at each step of the way which character types are missing (maintain a list of "missing_types" or something), and then randomly choose a type from a list, and then randomly select a character based on the chosen type.
Your method length does not give assure the number is >=6 because the statement int(user_l) >= 6 doesn't raise an Exception, you may use assert int(user_l) >= 6, but rather than calling the method again and again, use a while loop
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
while not user_l.isdigit() or int(user_l) < 6:
user_l = input("Please enter length of password. Minimum 6.\n")
return int(user_l)
Use a method to build the password, and another one to validate it
def generate_pwd(length):
password = []
for i in range(length):
character = random.choice(available_char)
password.append(str(character))
return password
The {} is empty dict, not empty set, also you can use the boolean value False of an empty set , and use elif to avoid doing all the if is one is fase don't do the next ones
if not set_a & set(ascii_lowercase)
The more readable way would be the other : if all condition are True, the password is valid
valid = set_a & set(ascii_lowercase) and set_a & set(ascii_uppercase) and \
set_a & set(digits) and set_a & set(s_letters)
Here's the full code that uses built-in alphabet from string
import random
from string import ascii_lowercase, ascii_uppercase, digits
s_letters = ["_", "#", "."]
available_char = list(ascii_lowercase) + list(ascii_uppercase) + list(digits) + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
while not user_l.isdigit() or int(user_l) < 6:
user_l = input("Please enter length of password. Minimum 6.\n")
return int(user_l)
def generate_pwd(length):
return [str(random.choice(available_char)) for i in range(length)]
def password_gen(length):
valid = False
password = []
set_a = set()
while not valid:
password = generate_pwd(length)
set_a = set(password)
valid = set_a & set(ascii_lowercase) and set_a & set(ascii_uppercase) and \
set_a & set(digits) and set_a & set(s_letters)
print("Your password is " + "".join(password))
print(set_a & set(ascii_lowercase))
print(set_a & set(ascii_uppercase))
print(set_a & set(digits))
print(set_a & set(s_letters))

Python how to check if input is a letter or character

How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.

Password validation in Python

My problem is to design a Python script which requires the user to input a password, and let Python validate the password is suitable for the conditions or not.
Here are conditions for the password input by users:
Begin with letters
at least 6 characters
only allowed letters, numbers, - and _ in password
If the conditions match, output Yes. Or else, No.
These are what I have tried:
from sys import exit
def check_alpha(input):
alphas = 0
alpha_list = "A B C D E F G H I J K L M N I O P Q R S T U V W X Y Z".split()
for char in input:
if char in alpha_list:
alphas += 1
if alphas > 0:
return True
else:
return False
def check_number(input):
numbers = 0
number_list = "1 2 3 4 5 6 7 8 9 0".split()
for char in input:
if char in number_list:
numbers += 1
if numbers > 0:
return True
else:
return False
def check_special(input):
specials = 0
special_list = "_-"
for char in input:
if char in special_list:
specials += 1
if specials > 0:
return True
else:
return False
def check_len(input):
if len(input) >= 6:
return True
else:
return False
def validate_password(input):
check_dict ={
'alpha':check_alpha(input),
'number':check_number(input),
'special':check_special(input),
'len':check_len(input)
}
if check_alpha(input) & check_number(input) & check_sprcial(input) & check_len(input)
return True
else:
print"No"
while True:
password = raw_input("Enter password:")
print
if validate_password(password):
print("Yes")
else
print("No")
or alternatively:
import re
while True:
user_input = input("Please enter password:")
is_valid = False
if(len(user_input)<6):
print("No")
continue
elif not re.search("[a-z]",user_input):
print("No")
continue
elif not re.search("[0-9]",user_input):
print("No")
continue
elif re.search("[~!##$%^&*`+=|\;:><,.?/]",user_input):
print("No")
continue
else:
is_valid = True
break
if(is_valid):
print("Yes")
I enjoy this particular solution because I find validation to be such a good use of decorators.
def require(pred):
def wrapper(f):
def wrapped(*args, **kwargs):
while True:
result = f(*args, **kwargs)
ok = pred(result)
if ok:
return result
return wrapped
return wrapper
def begin_with_letters(s):
return s[0].isalpha()
def length_over_six(s):
return len(s) >= 6
def no_letters_outside_of_whitelist(s):
WHITELIST = set(string.ascii_letters + string.digits + '-_')
return all(c in WHITELIST for c in s)
#require(begin_with_letters)
#require(length_over_six)
#require(no_letters_outside_of_whitelist)
def get_password():
user_pass = input("Enter a password: ")
return user_pass
This architecture can be grown by building a Validator class.
class Validator(abc.ABC):
errormsg = NotImplemented
def __init__(self, value):
self.__value = value
#property
def value(self):
return self.__value
#abc.abstractmethod
def validate(self) -> bool:
"""Uses self.value and validates it in some way, returning a bool."""
#staticmethod
def require(validator)
def wrapper(f):
def wrapped(*args, **kwargs):
while True:
result = f(*args, **kwargs)
v = validator(result)
ok = v.validate()
if ok:
return result
print(v.errormsg)
return wrapped
return wrapper
class BeginWithLetters(Validator):
errormsg = "Your password must begin with letters."
def validate(self):
return self.value[0].isalpha()
class LengthOverSix(Validator):
errormsg = "Your password must be six characters or longer."
def validate(self):
return len(self.value) >= 6
class WhiteListCharacters(Validator):
WHITELIST = set(string.ascii_letters + string.digits + "-_")
errormsg = "Your password must only contain letters, digits, - and _"
def validate(self):
return all(c in self.WHITELIST for c in self.value)
#Validator.require(BeginWithLetters)
#Validator.require(LengthOverSix)
#Validator.require(WhiteListCharacters)
def get_password():
return input("Enter a password: ")
I suggest you have a look at getpass module. To help you get started, take a look at the following links:getpass (examples series 1) and examples series 2
You can join the 3 conditions in one line, and avoid the variable is_valid. You also missed the condition of the first character:
import re
user_input = raw_input('Please enter password:')
if len(user_input)>=6 and user_input[0].isalpha() and re.match(r"^[\w-]*$", user_input):
print('Yes')
else:
print('No')
Try this:
import re
pw = raw_input('Type a password: ') # get input from user
if any([not pw[0].isalpha(), # check if first char is a letter
len(pw) < 6, # check if len is greater than or equal to 6
not re.match(r'^[\w-]*$', pw)]): # check if all chars are alphanumeric, underscores, or dashes
print 'No'
else:
print 'Yes'
Sample output for a few test cases:
Type a password: qwer
No
Type a password: qwerty
Yes
Type a password: 1a2b3c
No
Type a password: ASDF1234!!!!
No
Type a password: a.a.a.a
No
import re
def validate(password):
if len(password) < 6 or re.search('^[A-Za-z][A-Za-z0-9-_]*$',password) is None:
print("password not accepted")
else:
print("Your password seems fine")
import re
user_input = raw_input('Please enter password:')
if len(user_input)>=6 and user_input[0].isalpha() and re.match(r"^[\w-]*$", user_input):
print('Yes')
else:
print('No')
Ideal solution for your problem is Regular Expression. Try to validate it in the front-end.
Something like javascript.
For your knowledge, Check the following link in Python Docs.
https://docs.python.org/3/howto/regex.html
Import re
Password = (input("enter password here:"))
flag = 0
while True:
if (len(password)<7):
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
else:
flag = 0
print("strong")
break
if flag == -1:
print("weak")

Categories

Resources