Beginners Python help – keeping things simple – use built in features!
A user in the Programmer’s Discussion / Python channel had issues with code he/she was working. In this case the user needed to check a string to see if it passed certain password requirements:
It was a mess of code, with lots of variables and a counter that would get added onto through a number of for / if loops. I’ve removed most of it, but here’s a small sample of what it looked like:
count_one = 0
count_two = 0
count_three = 0
count_four = 0
password = "ssssL"
length_password = len(password)
lower_alphabet = ["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"]
upper_alphabet = ["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"]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
special_characters = ["$", "#", "@"]
if length_password >= 6 and length_password <= 16:
for letter in password:
for lower_letter in lower_alphabet:
if letter == lower_letter:
count_one = count_one + 1
if count_one == 0:
print("Missing lowercase letter in password")
A huge mess.
While counters work, it’s much simpler to use booleans. Simply iterating through the characters in a password and setting a boolean to true is enough to verify if the password meets a set of given requirements. Also, removing giant lists like lower_alphabet, upper_alphabet – there are built in lists from the string module … or in the following example, some quick python checks:
password = "ss#ss2s"
upperCaseCheck = lowerCaseCheck = numbersCheck = specialCharCheck = False
special_characters = ["$", "#", "@"]
if len(password) >= 6 and len(password) <=16:
for chars in password:
if chars in special_characters: specialCharCheck = True
if chars.isdigit(): numbersCheck = True
if chars.isalpha():
upperCaseCheck = True
if chars.islower(): lowerCaseCheck = True
if specialCharCheck is False: print(" Fail: Did not find special character in password ")
if lowerCaseCheck is False: print("Fail: Did not find lower case letter")
if upperCaseCheck is False: print("Fail: Did not find uppercase letter")
if numbersCheck is False: print("Fail: Did not find number")
else:
print (" Fail: Not within defined length ")