create a function to set a password, check the string if it is has one upper case, if it has at least one number and of it has maximum 8 characters, display successful password, else display try again.
this is the code that i tried to solve with
password = str(input("Please enter your password: "))
len_pass = len(password)
upper_pass = password.upper()
number = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
def pass_check(word, upper_word, integer, x):
for letter in word:
for num in integer:
for element in upper_word:
if element in letter:
if num == letter:
if x < 8:
return 1
return 2
result = pass_check(password, upper_pass, number, len_pass)
if result == 1:
print("Successful Password")
elif result == 2:
print("Fail")
CodePudding user response:
you can do it in much simpler way: This should check if the password meets the criteria and print the appropriate message.
def check_password(password):
# Check if password has at least one uppercase letter
has_uppercase = any(c.isupper() for c in password)
# Check if password has at least one number
has_number = any(c.isdigit() for c in password)
# Check if password is no more than 8 characters long
is_short_enough = len(password) <= 8
# Return True if password meets all criteria, False otherwise
return has_uppercase and has_number and is_short_enough
password = str(input("Please enter your password: "))
if check_password(password):
print("Successful password")
else:
print("Try again")
CodePudding user response:
Using regular expressions:
import re
def pass_check(passwd):
if len(passwd) <= 8 and re.search(r"\d", passwd) and re.search(r"[A-Z]", passwd):
return True
return False
if pass_check(password):
print("Successful password")
else:
print("Try again")
The function pass_check()
checks for:
len(passwd) <= 8
password length is at most 8re.search(r"\d", passwd)
searches for a digit character, returns None (evaluates to False) if doesn't find anyre.search(r"[A-Z]", passwd)
searches for an uppercase character, returns None if doesn't find any.
If you wish to check for exactly ONE uppercase character, put len(re.findall(r"[A-Z]", passwd))==1
instead of the last expression. The
re.findall(r"[A-Z]", passwd)
part simply returns a list with all the uppercase characters in the string.