Login Authentication in Python
Require both demo credentials to match in a Python login decision. Beginners practice and and string equality without mistaking hardcoded text for real security.
1# Simple login authentication23USERNAME = "admin"4PASSWORD = "secret123"56username = input("Enter username: ")7password = input("Enter password: ")89if username == USERNAME and password == PASSWORD:10 print("Login successful")11else:12 print("Invalid username or password")
Output
Login successful
Both entered strings exactly match the two demonstration constants.
In this one
- Require two matching fields with and
- Understand case-sensitive text equality
- Separate demo logic from secure authentication
How it works
- 1
Define the two demonstration credentials.
- 2
Read username and password as strings.
- 3
Compare both pairs and print one success or failure message.
Edge cases
Wrong user, right password
Enter a different username with secret123.
and fails because both fields must match.
Extra space
Enter admin followed by a space.
The response differs from admin and is rejected.
What's going on
Both fields have to match. A correct password with the wrong username still fails because the condition uses and. Using or would turn either matching field into a successful login.
USERNAME and PASSWORD are hardcoded strings. Capital names signal constants by convention, but Python does not make them unchangeable. input returns exactly the typed text apart from the final newline, so comparison is case-sensitive and spaces remain significant.
This is a Boolean-logic demo, not authentication for a real application. input shows the password while it is typed, and the password is visible in the source. Real systems need secure password storage, careful verification, and protection against repeated attempts. Do not enter a real password into this exercise.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use and for the two checks?
Pick an answer to check it.
Question 2
Does input hide password characters?
Pick an answer to check it.
Questions people ask
Why use and for the two checks?
Both the username and password must match for the condition to be True.
Does input hide password characters?
No. input uses ordinary visible terminal entry in this example.
Are capital names enforced constants?
No. Uppercase naming is a convention, not a language restriction on reassignment.