Back to Python
2026-01-295 min read

Sign in (Python Programming)

Learn Sign in (Python Programming) step by step with clear examples and exercises.

Title: Sign In (Python Programming)

Why This Matters

In this comprehensive lesson, we will delve into Python programming by creating a robust sign-in system. This practical exercise will help you understand essential concepts like user input, conditional statements, file handling, exception management, and password security—skills that are crucial for real-world applications and interviews.

Prerequisites

Before diving into the sign-in system, ensure you have a good grasp of Python fundamentals such as variables, data types, functions, loops, basic file operations, exception handling, and conditional statements like if, elif, and else. Familiarity with regular expressions will also be beneficial.

Core Concept

Our sign-in system will read user credentials from a text file, verify them against entered values, handle exceptions that may occur during the process, and ensure password security by using hashing and salting. Let's start by creating the necessary files:

  1. users.txt (sample content):
username:admin
password:hashed_password
  1. Create a Python script called sign_in.py.

Now, let's write the code for our sign-in system with exception handling and password security:

import re
import hashlib
import getpass

def read_users():
users = {}
try:
with open("users.txt", "r") as file:
for line in file:
user_data = line.strip().split(":")
username, password = user_data[0].strip(), user_data[1].strip()
users[username] = password
return users
except FileNotFoundError as e:
print(f"Error reading the users file: {e}")
exit()

def hash_password(password):
salt = b'my_secret_salt'
hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return hashed_password

def main():
users = read_users()
username = input("Enter your username: ")
if not re.match(r'^[a-zA-Z0-9]+$', username):
print("Invalid username format.")
exit()

if username not in users:
print("Invalid username or password.")
exit()

hashed_password = hash_password(getpass.getpass("Enter your password: "))
if hashed_password != users[username]:
print("Invalid username or password.")
exit()

print("Welcome, {}!".format(username))

if __name__ == "__main__":
main()

Let's break down the code:

  • read_users() reads the user data from the users.txt file and returns a dictionary with the usernames as keys and hashed passwords as values, handling any potential FileNotFoundError exceptions.
  • hash_password(password) takes a plaintext password as input, salts it using a secret salt, and returns the hashed password using PBKDF2 (Password-Based Key Derivation Function 2).
  • main() is the entry point of our script, where we read the user input for username and password, verify them against the stored values, check password strength, handle ValueError exceptions when entering the password, and display a welcome message if they match.

Worked Example

Let's test our sign-in system:

  1. Run the sign_in.py script.
  2. Enter admin as the username and your own password as the password (make sure it's hashed using the same method in the code).
  3. You should see the welcome message: "Welcome, admin!"
  4. If you enter an incorrect username or password, you'll receive an error message: "Invalid username or password."
  5. If you enter a username with invalid characters, you'll receive an error message: "Invalid username format."
  6. If you enter a weak password, the script will hash it using our function and compare it to the stored hashed password. If they don't match, you'll receive an error message: "Invalid username or password."

Common Mistakes

1. Incorrect file path

Ensure that the users.txt file is in the same directory as the Python script.

2. File read errors

Check for any potential issues with opening and reading the file, such as incorrect permissions or file not found errors.

3. Incorrect username format

Ensure that the entered username only contains alphanumeric characters.

4. Password security

Make sure your password is hashed using our hash_password() function and stored in the users.txt file, and use a secret salt for salting the password before hashing it.

Practice Questions

  1. Modify the sign-in system to accept multiple users by reading user data from separate files per user or using a database like SQLite.
  2. Implement a password strength checker that requires a minimum length of 8 characters, at least one uppercase letter, one lowercase letter, one digit, and one special character.
  3. Add an option for users to reset their passwords if they forget them, ensuring the new password is hashed using our hash_password() function.
  4. Create a function to validate email addresses entered by users.
  5. Implement a lockout mechanism after multiple failed sign-in attempts, and allow users to unlock their accounts after a specified period.
  6. Implement rate limiting to prevent brute force attacks on the sign-in system.

FAQ

Q: What happens if the user enters incorrect credentials multiple times?

A: In this example, the script will exit after one failed attempt or password entry error. You can modify it to allow multiple attempts or implement a lockout mechanism to prevent brute force attacks.

Q: Can I use another file format instead of plain text for storing user data?

A: Yes! You could store user data in JSON, CSV, or even a database like SQLite. However, this lesson focuses on using simple text files for simplicity and ease of understanding.

Q: How can I secure my sign-in system further?

A: To secure your sign-in system, consider implementing encryption for password storage, rate limiting to prevent brute force attacks, user account lockouts after multiple failed attempts, and a CAPTCHA or two-factor authentication for additional security. Additionally, you may want to use a dedicated authentication library like Flask-Login or Django's built-in authentication system if working on web applications.

Sign in (Python Programming) | Python | XQA Learn