Python Practice › Function Programs › Program 28
Login function
Write a Python function that accepts a username and password and reports whether login succeeded.
Input
admin / Admin@123
Output
Username: admin Password: Admin@123 Welcome, admin!
Approach
- Read both values with
input()and compare them inside a function.
Solution
USERS = {"admin": "Admin@123", "asha": "Test#2026"} def login(): user = input("Username: ") pwd = input("Password: ") if USERS.get(user) == pwd: print(f"Welcome, {user}!") return True print("Invalid username or password") return False login()Outputtyped input: admin, Admin@123
Username: admin Password: Admin@123 Welcome, admin!
Line by line
Line 6
USERS.get(user) is None for unknown users, so the comparison fails safely.
Line 9
One message for both cases avoids telling an attacker which part was wrong.
Tip
Use getpass.getpass() instead of input() for passwords in a real terminal program, so the password is not shown while typing.
Learn the concept
New to this topic? Read the lesson, then come back.