How can I easily iterate over this loop on Python?
Question:
I created a small program to get a password input from the user and then evaluate the password according to some metrics. Them being upper case, lower case, numbers and special characters. I then calculate the strength of the password by calculating how many of these criteria are satisfied. How can I do the iteration of the loop where I find how many upper case, lower case, numbers and special characters are there?
I already have a working code but I think the process could be done more efficiently. What do you think?
import string
password = input("Enter the password: ")
upper_case = any([1 if c in string.ascii_uppercase else 0 for c in password])
lower_case = any([1 if c in string.ascii_lowercase else 0 for c in password])
special = any([1 if c in string.punctuation else 0 for c in password])
digits = any([1 if c in string.digits else 0 for c in password])
characters = [upper_case, lower_case, special, digits]
length = len(password)
score = 0
Answers:
I think you’re complicating things a bit too much:
import string
password = input("Enter the password: ")
upper_case = any(c.isupper() for c in password)
lower_case = any(c.islower() for c in password)
special = any(c in password for c in string.punctuation) # I think there isn't a easier way to do it
digits = any(c.isdigit() for c in password)
characters = [upper_case, lower_case, special, digits]
length = len(password)
score = 0
I created a small program to get a password input from the user and then evaluate the password according to some metrics. Them being upper case, lower case, numbers and special characters. I then calculate the strength of the password by calculating how many of these criteria are satisfied. How can I do the iteration of the loop where I find how many upper case, lower case, numbers and special characters are there?
I already have a working code but I think the process could be done more efficiently. What do you think?
import string
password = input("Enter the password: ")
upper_case = any([1 if c in string.ascii_uppercase else 0 for c in password])
lower_case = any([1 if c in string.ascii_lowercase else 0 for c in password])
special = any([1 if c in string.punctuation else 0 for c in password])
digits = any([1 if c in string.digits else 0 for c in password])
characters = [upper_case, lower_case, special, digits]
length = len(password)
score = 0
I think you’re complicating things a bit too much:
import string
password = input("Enter the password: ")
upper_case = any(c.isupper() for c in password)
lower_case = any(c.islower() for c in password)
special = any(c in password for c in string.punctuation) # I think there isn't a easier way to do it
digits = any(c.isdigit() for c in password)
characters = [upper_case, lower_case, special, digits]
length = len(password)
score = 0