Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Validate user login credentials (hardcoded username/password) - Python Program

Example 1 :

username = input("Username: ") password = input("Password: ") if username == "admin" and password == "1234": print("Login successful") else: print("Invalid credentials")

Output

 
OUTPUT  :
Username: admin
Password: 1234
Login successful
 

Example 2 :

def validate_login(username, password): """ Validates user login credentials against hardcoded username and password. Args: username (str): The username entered by the user. password (str): The password entered by the user. Returns: bool: True if credentials are valid, False otherwise. """ # Hardcoded username and password correct_username = "admin" correct_password = "password123" if username == correct_username and password == correct_password: return True else: return False # Get user input user_input_username = input("Enter username: ") user_input_password = input("Enter password: ") # Validate credentials and display result if validate_login(user_input_username, user_input_password): print("Login successful! Welcome.") else: print("Invalid username or password. Please try again.")

Output

 

Successful Login:
OUTPUT 1 :
Enter username: admin
Enter password: password123
Login successful! Welcome.


Failed Login (Incorrect Password):
OUTPUT 2 :
Enter username: admin
Enter password: wrongpassword
Invalid username or password. Please try again.


Failed Login (Incorrect Username):
OUTPUT 3 :
Enter username: user
Enter password: password123
Invalid username or password. Please try again.

Explanation

This program defines a function validate_login that takes a username and password as input. Inside this function, correct_username and correct_password are hardcoded with the expected login credentials. The function then compares the user-provided input with these hardcoded values. If both the username and password match, it returns True, indicating a successful login; otherwise, it returns False.

The main part of the program prompts the user to enter their username and password using the input() function. These inputs are then passed to the validate_login function. Based on the boolean value returned by validate_login, a message is printed to the console indicating whether the login was successful or if the credentials were invalid.