P5.30 Having a secure password is a very important practice, when much of our information is stored online. Write a program that validates a new password, following these rules: •The password must be at least 8 characters long. •The password must have at least one uppercase and one lowercase letter. •The password must have at least one digit. Write a program that asks for a password, then asks again to confirm it. If the passwords don’t match or the rules are not fulfilled, prompt again. Your program should include a function that checks whether a password is valid.

Respuesta :

Answer:

def check_password(password):

   is_short = False

   has_uppercase = False

   has_lowercase = False

   has_digit = False

   

   if len(password) < 8:

       is_short = True

   

   for p in password:

       if p.isupper():

           has_uppercase = True

       if p.islower():

           has_lowercase = True

       if p.isdigit():

           has_digit = True

   

   if is_short == False and has_uppercase and has_uppercase and has_digit:

       return True

   else:

       return False

while True:

   password = input("Enter your password: ")

   password2 = input("Enter your password again: ")

   

   if password == password2 and check_password(password):

       break

Explanation:

Create a function named check_password that takes one parameter, password

Inside the function:

Initialize the is_short, has_uppercase, has_lowercase, and has_digit as False. These variables will be used to check each situation

Check the length of the password using len() method. If it is smaller than 8, set is_short as True

Create a for loop that iterates through password. Check each character. If a character is uppercase, set the has_uppercase as True (use isupper() function). If a character is lowercase, set the has_lowercase as True (use islower() function). If a character is a digit, set the has_digit as True (use isdigit() function).

When the loop is done, check the value of is_short, has_uppercase, has_lowercase, and has_digit. If is_short is False and other values are True, return True. Otherwise, return False

Create an indefinite while loop, that asks the user to enter password twice. Check the entered passwords. If they are equal and the check_password function returns True, stop the loop. This implies that both passwords are same and password is valid.

Q&A Education