使用Python编写一个程序来验证用户名和密码
发布时间:2023-12-16 11:29:30
以下是一个使用Python编写的用于验证用户名和密码的程序,包括了一个使用例子。
import getpass
def validate_username(username):
if len(username) < 5 or len(username) > 15:
return False
return True
def validate_password(password):
if len(password) < 8 or len(password) > 20:
return False
if not any(char.isdigit() for char in password):
return False
if not any(char.isalpha() for char in password):
return False
return True
def signup():
print("Sign up:")
username = input("Enter username: ")
while not validate_username(username):
print("Invalid username! Username should be 5-15 characters long.")
username = input("Enter username: ")
password = getpass.getpass("Enter password: ")
while not validate_password(password):
print("Invalid password! Password should be 8-20 characters long and contain at least one letter and one digit.")
password = getpass.getpass("Enter password: ")
print("Successfully signed up!")
def login():
print("Login:")
username = input("Enter username: ")
password = getpass.getpass("Enter password: ")
if username == "admin" and password == "admin123":
print("Welcome, admin!")
else:
print("Invalid username or password!")
def main():
print("Welcome to User Login System!")
choice = input("Select an option (1 - Sign up, 2 - Login): ")
if choice == "1":
signup()
elif choice == "2":
login()
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()
使用例子:
Welcome to User Login System! Select an option (1 - Sign up, 2 - Login): 1 Sign up: Enter username: john123 Enter password: Invalid password! Password should be 8-20 characters long and contain at least one letter and one digit. Enter password: password123 Successfully signed up! Welcome to User Login System! Select an option (1 - Sign up, 2 - Login): 2 Login: Enter username: john123 Enter password: password123 Invalid username or password! Welcome to User Login System! Select an option (1 - Sign up, 2 - Login): 2 Login: Enter username: admin Enter password: admin123 Welcome, admin!
