Objective:
Write a Python program that asks the user to enter a password and checks whether it is valid based on the following rules:
!@#$%^&*()_+-=[]{}|;:'",.<>?/
).Your program should:
Code Challenge: Allow the user to keep trying until they enter a valid password.
import re
def is_valid_password(password):
if len(password) < 8:
return False
if not re.search(r"[A-Z]", password): # At least one uppercase letter
return False
if not re.search(r"[a-z]", password): # At least one lowercase letter
return False
if not re.search(r"\d", password): # At least one digit
return False
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password): # Special character
return False
return True
# Example usage
password = input("Enter your password: ")
if is_valid_password(password):
print("Valid password")
else:
print("Invalid password")
Here’s an enhanced version that tells the user exactly which rules their password failed:
import re
def validate_password(password):
errors = []
if len(password) < 8:
errors.append("Password must be at least 8 characters long.")
if not re.search(r"[A-Z]", password):
errors.append("Password must contain at least one uppercase letter.")
if not re.search(r"[a-z]", password):
errors.append("Password must contain at least one lowercase letter.")
if not re.search(r"\d", password):
errors.append("Password must contain at least one number.")
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
errors.append("Password must contain at least one special character.")
return errors
# Example usage
password = input("Enter your password: ")
validation_errors = validate_password(password)
if not validation_errors:
print("Valid password.")
else:
print("Invalid password:")
for error in validation_errors:
print("-", error)
For more python exercises, see Python Exercises