Python Code Example: simple login

This code snippet is designed to simulate a simple user login system. It checks whether the provided username and password match predefined values.

Code Example

def checkUserInput(username, password):
    name, pw = "user", "123456"

    if name == username and pw == password:
        return True
    else:
        return False


username = input("Enter username: ")
password = input("Enter password: ")

if checkUserInput(username, password):
    print("Successfully logged in")
else:
    print("Wrong username or password")

Output first run

Enter username: user
Enter password: 123456
Successfully logged in

Output second run

Enter username: adsf
Enter password: 123456
Wrong username or password

Code Explanation

This code snippet is designed to simulate a simple user login system. It checks whether the provided username and password match predefined values. Here is a detailed explanation of each part of the code:

Function checkUserInput(username, password)

def checkUserInput(username, password):
    name, pw = "user", "123456"

    if name == username and pw == password:
        return True
    else:
        return False
  • Purpose: This function checks if the provided username and password match predefined credentials.
  • Parameters: The function takes two parameters:
    • username: The username entered by the user.
    • password: The password entered by the user.
  • Predefined Credentials: Inside the function, name and pw are predefined as “user” and “123456” respectively.
  • Condition Check: The function compares the provided username and password with the predefined name and pw.
    • If both match (name == username and pw == password), the function returns True, indicating successful login.
    • Otherwise, it returns False, indicating a failed login attempt.

Main Program

username = input("Enter username: ")
password = input("Enter password: ")

if checkUserInput(username, password):
    print("Successfully logged in")
else:
    print("Wrong username or password")
  • User Input:
    • The program prompts the user to enter a username using input("Enter username: ") and stores it in the variable username.
    • Similarly, it prompts the user to enter a password using input("Enter password: ") and stores it in the variable password.
  • Function Call and Condition Check:
    • The program calls the checkUserInput function with the entered username and password as arguments.
    • It then checks the returned value:
      • If the function returns True, it prints “Successfully logged in”.
      • If the function returns False, it prints “Wrong username or password”.