Check username and password

EasyIf-Else Programs · 9 of 64

Write a Python program to check login with a given username and password.

Advertisement
Input
("admin", "Admin@123"), ("admin", "wrong"), ("guest", "x")
Output
admin -> Login successful
admin -> Wrong password
guest -> Unknown user

Approach

  1. Compare both values; give a different message for a wrong user and a wrong password.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs