Welcome gift! Enjoy free course access today. Discover now!

Building a Simple Employee Login System with Python OOP Principles

In this article, we’ll explore Python’s Object-Oriented Programming (OOP) principles thoroughly and solve a real-world problem: building a simple Employee Login System. We’ll use VS Code as our editor and explain everything in detail, making it perfect for beginners.

This guide will explain every single part of the solution clearly so that you can grasp how OOP and Python work together.

What is Object-Oriented Programming (OOP)?

OOP is a programming style based on the concept of “objects,” which can contain data (attributes) and code (methods). Python supports four major principles of OOP:

1. Encapsulation

Encapsulation is the practice of keeping data safe inside a class and allowing it to be modified only through methods. It protects data from direct access and accidental changes.

Example: We store username and password inside a User class.

2. Abstraction

Abstraction hides complex logic and exposes only what is necessary.

Example: You use the register() method without knowing how it checks the password length internally.

3. Inheritance

Inheritance allows a class to inherit features (attributes and methods) from another class.

Example: A ManagerUser class could inherit from User and add more capabilities.

4. Polymorphism

Polymorphism allows different classes to be treated the same way.

Example: Both AdminUser and EmployeeUser could have a login() method, even if the internals differ.


Problem: Simplified Employee Login System

Requirements

  • Define a User class with username and password attributes.
  • Implement a register method with password validation (minimum 6 characters).
  • Create a login method that verifies user credentials.
  • Allow only three login attempts.
  • Manage users temporarily using a Python data structure (dictionary).
  • Handle invalid inputs and exceptions.

Tools

  • Programming Language: Python
  • Editor: Visual Studio Code (VS Code)

Building the Solution Step-by-Step

1. Defining the User Class

We start by defining a User class.

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

What does this mean?

  • class User: creates a new class called User.
  • def __init__(self, username, password): is a special method called a constructor. It automatically runs when a new User object is created.
  • self refers to the object being created.
  • self.username = username means: assign the value passed to username into the object’s username attribute. The . (dot) is used to access or create attributes inside an object.
  • self.password = password does the same for the password.

2. Registering a New User

Now, we create a method to register users.

@staticmethod
def register(user_db):
    while True:
        username = input("Enter username: ")
        if username in user_db:
            print("Username already exists. Try another one.")
            continue
        password = input("Enter password (at least 6 characters): ")
        if len(password) < 6:
            print("Password too short. Try again.")
        else:
            user_db[username] = User(username, password)
            print("Registration successful!")
            break

Breaking it down:

  • @staticmethod tells Python this method does not need access to the object itself (no self). It belongs to the class.
  • register(user_db) means the method accepts user_db (the user dictionary) as a parameter.
  • while True: means an infinite loop; it will keep asking for input until successful.
  • username = input("Enter username: ") asks the user for a username.
  • if username in user_db: checks if the username already exists in the dictionary.
  • continue skips to the next loop iteration if the username already exists.
  • password = input("Enter password (at least 6 characters): ") asks for a password.
  • if len(password) < 6: checks if the password is shorter than 6 characters.
  • user_db[username] = User(username, password) creates a new user and stores it in the dictionary.
  • break exits the loop when registration is successful.

3. Logging in a User

Next, we build the login method.

@staticmethod
def login(user_db):
    attempts = 0
    while attempts < 3:
        username = input("Enter username: ")
        password = input("Enter password: ")
        user = user_db.get(username)
        if user and user.password == password:
            print(f"Welcome, {username}! You have successfully logged in.")
            return
        else:
            print("Invalid credentials. Please try again.")
            attempts += 1
    print("Too many failed attempts. User locked out.")

Breaking it down:

  • attempts = 0 initializes a counter for login attempts.
  • while attempts < 3: allows up to three login tries.
  • username = input("Enter username: ") and password = input("Enter password: ") prompt the user.
  • user = user_db.get(username) looks up the user in the dictionary.
  • if user and user.password == password: checks if the user exists and if the password matches.
  • return exits the method after successful login.
  • attempts += 1 adds one to the attempt counter after a failed try.
  • After three failed attempts, the user is locked out.

4. Main Program Control

Finally, we set up a menu for the user to interact with.

if __name__ == "__main__":
    user_database = {}
    while True:
        print("\n--- Employee Login System ---")
        print("1. Register")
        print("2. Login")
        print("3. Exit")
        try:
            choice = int(input("Choose an option (1-3): "))
            if choice == 1:
                User.register(user_database)
            elif choice == 2:
                User.login(user_database)
            elif choice == 3:
                print("Exiting system. Goodbye!")
                break
            else:
                print("Invalid choice. Enter 1, 2, or 3.")
        except ValueError:
            print("Invalid input. Please enter a number.")

Explaining this:

  • if __name__ == "__main__": checks if this file is being run directly (not imported as a module).
  • user_database = {} initializes an empty dictionary to store users.
  • while True: creates an endless loop for the menu.
  • print(...) shows the available options.
  • choice = int(input("Choose an option (1-3): ")) gets the user’s choice and converts it to an integer.
  • try-except ValueError: handles the situation where a non-integer is entered, preventing crashes.

Full Solution Code

# Q3SSENDISAMUEL.py

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    @staticmethod
    def register(user_db):
        while True:
            username = input("Enter username: ")
            if username in user_db:
                print("Username already exists. Try another one.")
                continue
            password = input("Enter password (at least 6 characters): ")
            if len(password) < 6:
                print("Password too short. Try again.")
            else:
                user_db[username] = User(username, password)
                print("Registration successful!")
                break

    @staticmethod
    def login(user_db):
        attempts = 0
        while attempts < 3:
            username = input("Enter username: ")
            password = input("Enter password: ")

            user = user_db.get(username)

            if user and user.password == password:
                print(f"Welcome, {username}! You have successfully logged in.")
                return
            else:
                print("Invalid credentials. Please try again.")
                attempts += 1

        print("Too many failed attempts. User locked out.")

# Main program
if __name__ == "__main__":
    user_database = {}

    while True:
        print("\n--- Employee Login System ---")
        print("1. Register")
        print("2. Login")
        print("3. Exit")

        try:
            choice = int(input("Choose an option (1-3): "))

            if choice == 1:
                User.register(user_database)
            elif choice == 2:
                User.login(user_database)
            elif choice == 3:
                print("Exiting system. Goodbye!")
                break
            else:
                print("Invalid choice. Enter 1, 2, or 3.")

        except ValueError:
            print("Invalid input. Please enter a number.")

How This Code Applies OOP Principles

  • Encapsulation:
    • Username and password are hidden inside the User object.
  • Abstraction:
    • Complex details like input validation are hidden behind easy-to-use methods.
  • Inheritance:
    • Future subclasses like AdminUser can inherit from User.
  • Polymorphism:
    • Different user types could redefine login() but still be used similarly.

Running the Program in VS Code

  1. Open Visual Studio Code.
  2. Create a new file and save it as Q3YourFullName.py.
  3. Paste the full code.
  4. Open the terminal (Shortcut: Ctrl + ~).
  5. Run your file:
python Q3YourFullName.py
  1. Follow the menu to register and login users.

Conclusion

This project gives you a complete understanding of Python’s OOP principles in a real-world setting. Mastering these basics is key to writing clean, efficient, and maintainable code.

Next Steps:

  • Add password encryption.
  • Save users permanently (using a database or file).
  • Introduce different user roles (like Admin, Employee, Manager).

Keep practicing and building bigger projects — your coding skills will grow fast!

Leave A Reply

Your email address will not be published. Required fields are marked *


You May Also Like

In this tutorial, we are going to build a Student Grading System for Nkumba University using Python and Object-Oriented Programming...
Control Web Panel (CWP), previously called CentOS Web Panel, is a free and robust hosting control panel built for easy...
Makerere University announces the private sponsorship admission list for the 2024/2025 academic year. Learn about the admission process, cut-off points,...