Python Practice › If-Else Programs › Program 9
Check username and password
Write a Python program to check login with a given username and password.
Input
("admin", "Admin@123"), ("admin", "wrong"), ("guest", "x")Output
admin -> Login successful admin -> Wrong password guest -> Unknown user
Approach
- Compare both values; give a different message for a wrong user and a wrong password.
Solution
USERNAME = "admin"PASSWORD = "Admin@123" def login(user, pwd): if user == USERNAME and pwd == PASSWORD: return "Login successful" elif user == USERNAME: return "Wrong password" else: return "Unknown user" for u, p in [("admin", "Admin@123"), ("admin", "wrong"), ("guest", "x")]: print(u, "->", login(u, p))Output
admin -> Login successful admin -> Wrong password guest -> Unknown user
Line by line
Lines 1-2
The expected credentials are constants (upper-case names).
Line 5
Both must match, so the checks are joined with and.
Line 7
Reaching this line means the password was wrong for a known user.
Watch out
Real applications never store plain-text passwords; they store a salted hash and compare hashes. This program only practises if-else logic.
Learn the concept
New to this topic? Read the lesson, then come back.