Login function

EasyFunction Programs · 28 of 39

Write a Python function that accepts a username and password and reports whether login succeeded.

Advertisement
Input
admin / Admin@123
Output
Username: admin
Password: Admin@123
Welcome, admin!

Approach

  1. Read both values with input() and compare them inside a function.

Solution

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

More function programs

← All 39 Function Programs

Leave a Comment