Category: Projects

https://cdn3d.iconscout.com/3d/premium/thumb/project-task-management-3d-illustration-download-in-png-blend-fbx-gltf-file-formats–development-checklist-list-design-pack-business-illustrations-4496029.png

  • URL Shortener Application

    Step 1: Set Up the Project Structure

    Create a new directory for your project and create the following files and folders:

    arduinoCopy codeurl_shortener/
    │
    ├── app.py
    ├── database.py
    ├── templates/
    │   └── index.html
    └── static/
    
    └── styles.css

    Step 2: Create the Database Module

    Create a file named database.py to handle the SQLite database:

    pythonCopy codeimport sqlite3
    
    def init_db():
    
    """Initialize the database."""
    conn = sqlite3.connect('urls.db')
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS urls (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            original_url TEXT NOT NULL,
            short_url TEXT NOT NULL UNIQUE
        )
    ''')
    conn.commit()
    conn.close()
    def add_url(original_url, short_url):
    """Add a URL to the database."""
    conn = sqlite3.connect('urls.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO urls (original_url, short_url) VALUES (?, ?)', (original_url, short_url))
    conn.commit()
    conn.close()
    def get_original_url(short_url):
    """Retrieve the original URL from the database."""
    conn = sqlite3.connect('urls.db')
    cursor = conn.cursor()
    cursor.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
    result = cursor.fetchone()
    conn.close()
    return result[0] if result else None

    Step 3: Create the Flask Application

    Create a file named app.py and add the following code:

    pythonCopy codefrom flask import Flask, request, redirect, render_template
    import string
    import random
    import database
    
    app = Flask(__name__)
    
    # Initialize the database
    database.init_db()
    
    def generate_short_url(length=6):
    
    """Generate a random short URL."""
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))
    @app.route('/', methods=['GET', 'POST']) def index():
    if request.method == 'POST':
        original_url = request.form['url']
        short_url = generate_short_url()
        database.add_url(original_url, short_url)
        return render_template('index.html', short_url=short_url)
    return render_template('index.html', short_url=None)
    @app.route('/<short_url>') def redirect_to_url(short_url):
    original_url = database.get_original_url(short_url)
    if original_url:
        return redirect(original_url)
    return "URL not found", 404
    if __name__ == "__main__":
    app.run(debug=True)

    Step 4: Create the HTML Template

    Create a file named index.html inside the templates folder and add the following code:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;URL Shortener&lt;/title&gt;
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;URL Shortener&lt;/h1&gt;
        &lt;form method="POST"&gt;
            &lt;input type="text" name="url" placeholder="Enter your URL here" required&gt;
            &lt;button type="submit"&gt;Shorten&lt;/button&gt;
        &lt;/form&gt;
        {% if short_url %}
            &lt;h2&gt;Short URL: &lt;a href="{{ short_url }}"&gt;{{ request.host_url }}{{ short_url }}&lt;/a&gt;&lt;/h2&gt;
        {% endif %}
    &lt;/div&gt;
    </body> </html>

    Step 5: Create the CSS Styles

    Create a file named styles.css inside the static folder and add the following code:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } form {
    display: flex;
    flex-direction: column;
    } input[type="text"] {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    } button {
    padding: 10px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    } button:hover {
    background-color: #218838;
    }

    Step 6: Run the Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved the project.
    3. Run the application using the command:bashCopy codepython app.py
    4. Open your web browser and go to http://127.0.0.1:5000/.
  • Simple URL Shortener in C++

    cppCopy code#include <iostream>
    #include <unordered_map>
    #include <string>
    #include <ctime>
    
    class URLShortener {
    private:
    
    std::unordered_map&lt;std::string, std::string&gt; url_map; // Maps short URL to original URL
    std::unordered_map&lt;std::string, std::string&gt; reverse_map; // Maps original URL to short URL
    const std::string base_url = "http://short.url/";
    
    std::string generateShortURL() {
        static const char alphanum&#91;] =
            "0123456789"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";
        std::string short_url;
        
        for (int i = 0; i &lt; 6; ++i) {
            short_url += alphanum&#91;rand() % (sizeof(alphanum) - 1)];
        }
        
        return short_url;
    }
    public:
    URLShortener() {
        std::srand(static_cast&lt;unsigned&gt;(std::time(nullptr))); // Seed for randomness
    }
    std::string shortenURL(const std::string&amp; original_url) {
        if (reverse_map.find(original_url) != reverse_map.end()) {
            return base_url + reverse_map&#91;original_url]; // Return existing short URL
        }
        
        std::string short_url = generateShortURL();
        while (url_map.find(short_url) != url_map.end()) {
            short_url = generateShortURL(); // Ensure unique short URL
        }
        
        url_map&#91;short_url] = original_url;
        reverse_map&#91;original_url] = short_url;
        return base_url + short_url;
    }
    std::string getOriginalURL(const std::string&amp; short_url) {
        std::string short_code = short_url.substr(base_url.length());
        if (url_map.find(short_code) != url_map.end()) {
            return url_map&#91;short_code];
        }
        return "URL not found!";
    }
    }; int main() {
    URLShortener url_shortener;
    std::string original_url;
    std::cout &lt;&lt; "Enter a URL to shorten: ";
    std::cin &gt;&gt; original_url;
    std::string short_url = url_shortener.shortenURL(original_url);
    std::cout &lt;&lt; "Shortened URL: " &lt;&lt; short_url &lt;&lt; std::endl;
    std::cout &lt;&lt; "Enter the short URL to retrieve the original: ";
    std::string input_short_url;
    std::cin &gt;&gt; input_short_url;
    std::string retrieved_url = url_shortener.getOriginalURL(input_short_url);
    std::cout &lt;&lt; "Original URL: " &lt;&lt; retrieved_url &lt;&lt; std::endl;
    return 0;
    }

    How It Works

    1. URL Mapping: It uses two hash maps to store mappings between short URLs and original URLs.
    2. Short URL Generation: A random string of characters is generated for the short URL.
    3. Collision Handling: The program checks for existing short URLs to ensure uniqueness.
    4. User Input: The user can input a URL to shorten and retrieve the original URL using the shortened link.
  • Virtual Library Application in Python

    Create a file named virtual_library.py and add the following code:

    pythonCopy codeimport json
    import os
    
    class Book:
    
    def __init__(self, title, author, year, isbn):
        self.title = title
        self.author = author
        self.year = year
        self.isbn = isbn
    def to_dict(self):
        return {
            'title': self.title,
            'author': self.author,
            'year': self.year,
            'isbn': self.isbn,
        }
    class VirtualLibrary:
    def __init__(self, filename='library.json'):
        self.filename = filename
        self.books = self.load_books()
    def load_books(self):
        """Load books from a JSON file."""
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                return &#91;Book(**data) for data in json.load(file)]
        return &#91;]
    def save_books(self):
        """Save books to a JSON file."""
        with open(self.filename, 'w') as file:
            json.dump(&#91;book.to_dict() for book in self.books], file)
    def add_book(self, title, author, year, isbn):
        """Add a new book to the library."""
        new_book = Book(title, author, year, isbn)
        self.books.append(new_book)
        self.save_books()
        print("Book added!")
    def view_books(self):
        """View all books in the library."""
        if not self.books:
            print("No books available.")
            return
        print("\nBooks in the Library:")
        for index, book in enumerate(self.books, start=1):
            print(f"{index}. {book.title} by {book.author} ({book.year}) - ISBN: {book.isbn}")
        print()
    def search_books(self, search_term):
        """Search for books by title or author."""
        results = &#91;book for book in self.books if search_term.lower() in book.title.lower() or search_term.lower() in book.author.lower()]
        if results:
            print("\nSearch Results:")
            for index, book in enumerate(results, start=1):
                print(f"{index}. {book.title} by {book.author} ({book.year}) - ISBN: {book.isbn}")
        else:
            print("No books found matching that search term.")
        print()
    def run(self):
        """Run the virtual library application."""
        while True:
            print("Virtual Library")
            print("1. Add Book")
            print("2. View Books")
            print("3. Search Books")
            print("4. Exit")
            choice = input("Choose an option (1-4): ")
            if choice == '1':
                title = input("Enter the book title: ")
                author = input("Enter the author: ")
                year = input("Enter the publication year: ")
                isbn = input("Enter the ISBN: ")
                self.add_book(title, author, year, isbn)
            elif choice == '2':
                self.view_books()
            elif choice == '3':
                search_term = input("Enter title or author to search: ")
                self.search_books(search_term)
            elif choice == '4':
                print("Exiting the application.")
                break
            else:
                print("Invalid choice. Please try again.")
    def main():
    library = VirtualLibrary()
    library.run()
    if __name__ == "__main__":
    main()

    Step 2: Running the Virtual Library Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved virtual_library.py.
    3. Run the script using the command:bashCopy codepython virtual_library.py

    How It Works

    • Book Class: Represents a book with attributes like title, author, year, and ISBN.
    • VirtualLibrary Class: Manages the collection of books, including loading from and saving to a JSON file.
    • Functions:
      • load_books: Loads existing books from the JSON file.
      • save_books: Saves the current books back to the JSON file.
      • add_book: Adds a new book to the library.
      • view_books: Displays all stored books.
      • search_books: Searches for books by title or author.
    • User Interface: A simple command-line interface that allows users to interact with the library.
  • Social Media Dashboard

    This application will simulate fetching and displaying user data from a social media platform. We’ll use Flask to serve the web pages.

    Step 1: Set Up the Project Structure

    Create a new directory for your project and create the following files and folders:

    arduinoCopy codesocial_media_dashboard/
    │
    ├── app.py
    ├── templates/
    │   └── dashboard.html
    └── static/
    
    └── styles.css

    Step 2: Create the Flask Application

    Create a file named app.py and add the following code:

    pythonCopy codefrom flask import Flask, render_template
    
    app = Flask(__name__)
    
    # Sample data representing social media stats
    user_data = {
    
    "username": "john_doe",
    "followers": 1200,
    "following": 300,
    "posts": 50,
    "likes": 2500,
    } @app.route('/') def dashboard():
    return render_template('dashboard.html', user=user_data)
    if __name__ == "__main__":
    app.run(debug=True)

    Step 3: Create the HTML Template

    Create a file named dashboard.html inside the templates folder and add the following code:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Social Media Dashboard&lt;/title&gt;
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;Social Media Dashboard&lt;/h1&gt;
        &lt;h2&gt;User: {{ user.username }}&lt;/h2&gt;
        &lt;div class="stats"&gt;
            &lt;div class="stat"&gt;
                &lt;h3&gt;Followers&lt;/h3&gt;
                &lt;p&gt;{{ user.followers }}&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class="stat"&gt;
                &lt;h3&gt;Following&lt;/h3&gt;
                &lt;p&gt;{{ user.following }}&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class="stat"&gt;
                &lt;h3&gt;Posts&lt;/h3&gt;
                &lt;p&gt;{{ user.posts }}&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class="stat"&gt;
                &lt;h3&gt;Likes&lt;/h3&gt;
                &lt;p&gt;{{ user.likes }}&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    </body> </html>

    Step 4: Create the CSS Styles

    Create a file named styles.css inside the static folder and add the following code:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } .stats {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    } .stat {
    background: #e2e2e2;
    border-radius: 5px;
    padding: 10px;
    text-align: center;
    flex: 1;
    margin: 5px;
    }

    Step 5: Run the Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved the project.
    3. Run the application using the command:bashCopy codepython app.py
    4. Open your web browser and go to http://127.0.0.1:5000/.
  • Note-Taking Application in Python

    Create a file named note_taking_app.py and add the following code:

    pythonCopy codeimport json
    import os
    
    class NoteTakingApp:
    
    def __init__(self, filename='notes.json'):
        self.filename = filename
        self.notes = self.load_notes()
    def load_notes(self):
        """Load notes from a JSON file."""
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                return json.load(file)
        return &#91;]
    def save_notes(self):
        """Save notes to a JSON file."""
        with open(self.filename, 'w') as file:
            json.dump(self.notes, file)
    def add_note(self, note):
        """Add a new note."""
        self.notes.append(note)
        self.save_notes()
        print("Note added!")
    def view_notes(self):
        """View all notes."""
        if not self.notes:
            print("No notes available.")
            return
        print("\nYour Notes:")
        for index, note in enumerate(self.notes, start=1):
            print(f"{index}. {note}")
        print()
    def delete_note(self, index):
        """Delete a note by index."""
        if 0 &lt;= index &lt; len(self.notes):
            deleted_note = self.notes.pop(index)
            self.save_notes()
            print(f"Deleted note: {deleted_note}")
        else:
            print("Invalid note index.")
    def run(self):
        """Run the note-taking application."""
        while True:
            print("Note-Taking Application")
            print("1. Add Note")
            print("2. View Notes")
            print("3. Delete Note")
            print("4. Exit")
            choice = input("Choose an option (1-4): ")
            if choice == '1':
                note = input("Enter your note: ")
                self.add_note(note)
            elif choice == '2':
                self.view_notes()
            elif choice == '3':
                self.view_notes()
                index = int(input("Enter the note number to delete: ")) - 1
                self.delete_note(index)
            elif choice == '4':
                print("Exiting the application.")
                break
            else:
                print("Invalid choice. Please try again.")
    def main():
    app = NoteTakingApp()
    app.run()
    if __name__ == "__main__":
    main()

    Step 2: Running the Note-Taking Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved note_taking_app.py.
    3. Run the script using the command:bashCopy codepython note_taking_app.py

    How It Works

    • Data Storage: Notes are stored in a JSON file (notes.json). This allows for persistent storage of notes between sessions.
    • Functions:
      • load_notes: Loads existing notes from the JSON file.
      • save_notes: Saves the current notes back to the JSON file.
      • add_note: Adds a new note to the list.
      • view_notes: Displays all stored notes.
      • delete_note: Deletes a note by its index.
    • User Interface: The command-line interface allows users to choose actions like adding, viewing, or deleting notes.
  • Quiz Application

    Create a file named quiz_app.py and add the following code:

    pythonCopy codeclass Question:
    
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer
    class Quiz:
    def __init__(self, questions):
        self.questions = questions
        self.score = 0
    def run(self):
        for question in self.questions:
            print(question.prompt)
            user_answer = input("Your answer: ")
            if user_answer.lower() == question.answer.lower():
                self.score += 1
                print("Correct!\n")
            else:
                print(f"Wrong! The correct answer was: {question.answer}\n")
        self.show_score()
    def show_score(self):
        print(f"You scored {self.score} out of {len(self.questions)}.")
    def main():
    questions = &#91;
        Question("What is the capital of France?\n(a) London\n(b) Paris\n(c) Rome\n", "b"),
        Question("Which planet is known as the Red Planet?\n(a) Earth\n(b) Mars\n(c) Jupiter\n", "b"),
        Question("What is 2 + 2?\n(a) 3\n(b) 4\n(c) 5\n", "b"),
        Question("What is the largest ocean on Earth?\n(a) Atlantic\n(b) Indian\n(c) Pacific\n", "c"),
        Question("What is the chemical symbol for gold?\n(a) Au\n(b) Ag\n(c) Fe\n", "a"),
    ]
    quiz = Quiz(questions)
    quiz.run()
    if __name__ == "__main__":
    main()

    Step 2: Running the Quiz Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved quiz_app.py.
    3. Run the script using the command:bashCopy codepython quiz_app.py

    How It Works

    • Question Class: Represents a quiz question with a prompt and the correct answer.
    • Quiz Class: Manages the list of questions and keeps track of the user’s score. It has methods to run the quiz and display the score.
    • Main Function: Initializes a list of questions and starts the quiz.

    Example Quiz Questions

    The quiz consists of the following questions:

    1. What is the capital of France? (a) London (b) Paris (c) Rome
    2. Which planet is known as the Red Planet? (a) Earth (b) Mars (c) Jupiter
    3. What is 2 + 2? (a) 3 (b) 4 (c) 5
    4. What is the largest ocean on Earth? (a) Atlantic (b) Indian (c) Pacific
    5. What is the chemical symbol for gold? (a) Au (b) Ag (c) Fe
  • Maze Solver in Python

    Create a file named maze_solver.py and add the following code:

    pythonCopy codeclass Maze:
    
    def __init__(self, grid):
        self.grid = grid
        self.rows = len(grid)
        self.cols = len(grid&#91;0]) if self.rows &gt; 0 else 0
        self.path = &#91;]
    def is_valid_move(self, x, y):
        """Check if the move is within the maze boundaries and not a wall."""
        return 0 &lt;= x &lt; self.rows and 0 &lt;= y &lt; self.cols and self.grid&#91;x]&#91;y] == 0
    def solve_maze(self, x, y):
        """Solve the maze using DFS."""
        # Check if we reached the exit
        if (x, y) == (self.rows - 1, self.cols - 1):
            self.path.append((x, y))
            return True
        # Check if the current position is valid
        if not self.is_valid_move(x, y):
            return False
        # Mark the cell as part of the path
        self.path.append((x, y))
        self.grid&#91;x]&#91;y] = 2  # Mark as visited
        # Explore neighbors (right, down, left, up)
        if (self.solve_maze(x + 1, y) or
                self.solve_maze(x, y + 1) or
                self.solve_maze(x - 1, y) or
                self.solve_maze(x, y - 1)):
            return True
        # Unmark the cell if not part of the solution
        self.path.pop()
        self.grid&#91;x]&#91;y] = 0  # Unmark as visited
        return False
    def print_solution(self):
        """Print the path found."""
        if self.path:
            print("Path to the exit:")
            for step in self.path:
                print(step)
        else:
            print("No path found.")
    def main():
    # Define the maze (0 = path, 1 = wall)
    maze_grid = &#91;
        &#91;0, 1, 0, 0, 0],
        &#91;0, 1, 0, 1, 0],
        &#91;0, 0, 0, 1, 0],
        &#91;1, 1, 0, 0, 0],
        &#91;0, 1, 1, 1, 0]
    ]
    maze = Maze(maze_grid)
    # Solve the maze starting from the top-left corner (0, 0)
    if maze.solve_maze(0, 0):
        maze.print_solution()
    else:
        print("No path from the start to the exit.")
    if __name__ == "__main__":
    main()

    Step 2: Running the Maze Solver

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved maze_solver.py.
    3. Run the script using the command:bashCopy codepython maze_solver.py

    How It Works

    • Maze Representation: The maze is represented as a 2D list (grid), where 0 represents open paths and 1 represents walls.
    • DFS Algorithm: The solve_maze method uses Depth-First Search to explore the maze:
      • It checks if the current position is valid.
      • If it reaches the exit (bottom-right corner), it returns True.
      • It marks the cell as visited by changing it to 2.
      • It recursively explores neighboring cells.
      • If a cell doesn’t lead to a solution, it backtracks by unmarking the cell.
    • Path Tracking: The path to the exit is tracked and printed if found.

    Example Maze

    The maze defined in the code looks like this:

    Copy code0 1 0 0 0
    0 1 0 1 0
    0 0 0 1 0
    1 1 0 0 0
    0 1 1 1 0
  • Create the Basic Compiler

    Create a file named basic_compiler.py and add the following code:

    pythonCopy codeclass Lexer:
    
    def __init__(self, text):
        self.text = text
        self.position = 0
        self.current_char = self.text&#91;self.position]
    def error(self):
        raise Exception("Invalid character")
    def advance(self):
        """Advance the 'position' pointer and set the 'current_char'."""
        self.position += 1
        if self.position &gt; len(self.text) - 1:
            self.current_char = None  # Indicates the end of the input
        else:
            self.current_char = self.text&#91;self.position]
    def skip_whitespace(self):
        """Skip whitespace characters."""
        while self.current_char is not None and self.current_char.isspace():
            self.advance()
    def variable(self):
        """Return a variable identifier."""
        result = ''
        while self.current_char is not None and self.current_char.isalnum():
            result += self.current_char
            self.advance()
        return result
    def number(self):
        """Return a multi-digit integer."""
        result = ''
        while self.current_char is not None and self.current_char.isdigit():
            result += self.current_char
            self.advance()
        return int(result)
    def get_next_token(self):
        """Tokenize the input string."""
        while self.current_char is not None:
            if self.current_char.isspace():
                self.skip_whitespace()
                continue
            if self.current_char.isalpha():
                return ('VARIABLE', self.variable())
            if self.current_char.isdigit():
                return ('NUMBER', self.number())
            if self.current_char == '+':
                self.advance()
                return ('PLUS', '+')
            if self.current_char == '-':
                self.advance()
                return ('MINUS', '-')
            if self.current_char == '=':
                self.advance()
                return ('EQUALS', '=')
            self.error()
        return ('EOF', None)
    class Interpreter:
    def __init__(self, lexer):
        self.lexer = lexer
        self.current_token = self.lexer.get_next_token()
        self.variables = {}
    def error(self):
        raise Exception("Invalid syntax")
    def eat(self, token_type):
        """Consume the current token if it matches the expected type."""
        if self.current_token&#91;0] == token_type:
            self.current_token = self.lexer.get_next_token()
        else:
            self.error()
    def factor(self):
        """Parse a factor."""
        token = self.current_token
        if token&#91;0] == 'NUMBER':
            self.eat('NUMBER')
            return token&#91;1]
        elif token&#91;0] == 'VARIABLE':
            var_name = token&#91;1]
            self.eat('VARIABLE')
            return self.variables.get(var_name, 0)
    def term(self):
        """Parse a term (factor)."""
        result = self.factor()
        return result
    def expression(self):
        """Parse an expression."""
        result = self.term()
        while self.current_token&#91;0] in ('PLUS', 'MINUS'):
            token = self.current_token
            if token&#91;0] == 'PLUS':
                self.eat('PLUS')
                result += self.term()
            elif token&#91;0] == 'MINUS':
                self.eat('MINUS')
                result -= self.term()
        return result
    def assignment(self):
        """Parse an assignment statement."""
        var_name = self.current_token&#91;1]
        self.eat('VARIABLE')
        self.eat('EQUALS')
        value = self.expression()
        self.variables&#91;var_name] = value
        return value
    def main():
    while True:
        try:
            text = input("Enter a statement (or 'exit' to quit): ")
            if text.lower() == 'exit':
                break
            lexer = Lexer(text)
            interpreter = Interpreter(lexer)
            result = interpreter.assignment()
            print(f"Result: {result}")
        except Exception as e:
            print(f"Error: {e}")
    if __name__ == "__main__":
    main()

    Step 2: Running the Basic Compiler

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved basic_compiler.py.
    3. Run the script using the command:bashCopy codepython basic_compiler.py

    How It Works

    • Lexer: The Lexer class tokenizes the input string into meaningful components like numbers, variables, and operators.
    • Interpreter: The Interpreter class parses the tokens and evaluates expressions and assignments. It maintains a dictionary to store variable values.
    • Input Handling: The user can enter statements to assign values to variables or evaluate expressions.
  • Multiplayer Tic-Tac-Toe

    pythonCopy codeclass TicTacToe:
    
    def __init__(self):
        self.board = &#91;' ' for _ in range(9)]  # 3x3 board
        self.current_player = 'X'
    def print_board(self):
        print("\n")
        for i in range(3):
            print(f" {self.board&#91;i*3]} | {self.board&#91;i*3+1]} | {self.board&#91;i*3+2]} ")
            if i &lt; 2:
                print("---|---|---")
        print("\n")
    def is_winner(self):
        # Check rows, columns, and diagonals for a win
        winning_combinations = &#91;
            (0, 1, 2), (3, 4, 5), (6, 7, 8),  # rows
            (0, 3, 6), (1, 4, 7), (2, 5, 8),  # columns
            (0, 4, 8), (2, 4, 6)               # diagonals
        ]
        for a, b, c in winning_combinations:
            if self.board&#91;a] == self.board&#91;b] == self.board&#91;c] != ' ':
                return True
        return False
    def is_draw(self):
        return ' ' not in self.board
    def make_move(self, position):
        if self.board&#91;position] == ' ':
            self.board&#91;position] = self.current_player
            if self.is_winner():
                self.print_board()
                print(f"Player {self.current_player} wins!")
                return True
            elif self.is_draw():
                self.print_board()
                print("It's a draw!")
                return True
            else:
                self.current_player = 'O' if self.current_player == 'X' else 'X'
            return False
        else:
            print("Invalid move! Try again.")
            return False
    def main():
    game = TicTacToe()
    
    while True:
        game.print_board()
        try:
            move = int(input(f"Player {game.current_player}, enter your move (1-9): ")) - 1
            if move &lt; 0 or move &gt; 8:
                print("Invalid input! Enter a number between 1 and 9.")
                continue
            if game.make_move(move):
                break
        except ValueError:
            print("Invalid input! Please enter a number.")
    if __name__ == "__main__":
    main()

    Step 2: Running the Tic-Tac-Toe Game

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved tic_tac_toe.py.
    3. Run the script using the command:bashCopy codepython tic_tac_toe.py

    How It Works

    • Game Board: The board is represented as a list of strings, with ‘ ‘ indicating empty spaces.
    • Player Turns: Players alternate turns, with ‘X’ and ‘O’ representing the two players.
    • Move Validation: The game checks if the chosen position is valid and not already taken.
    • Winning Conditions: The game checks for winning combinations after each move.
    • Draw Condition: If the board is full without a winner, it announces a draw.

    Example Gameplay

    1. The board is displayed in a 3×3 grid.
    2. Players take turns entering their moves by specifying a number from 1 to 9 corresponding to the board positions.
    3. The game announces the winner or if it’s a draw.
  • Library Management System

    pythonCopy codeclass Book:
    
    def __init__(self, title, author, isbn):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.is_borrowed = False
    def __str__(self):
        return f"{self.title} by {self.author} (ISBN: {self.isbn}) - {'Borrowed' if self.is_borrowed else 'Available'}"
    class Library:
    def __init__(self):
        self.books = &#91;]
    def add_book(self, title, author, isbn):
        book = Book(title, author, isbn)
        self.books.append(book)
        print(f"Added book: {book}")
    def view_books(self):
        if not self.books:
            print("No books available in the library.")
            return
        print("\nAvailable Books:")
        for book in self.books:
            print(book)
    def borrow_book(self, isbn):
        for book in self.books:
            if book.isbn == isbn:
                if book.is_borrowed:
                    print("Sorry, this book is already borrowed.")
                else:
                    book.is_borrowed = True
                    print(f"You have borrowed: {book}")
                return
        print("Book not found.")
    def return_book(self, isbn):
        for book in self.books:
            if book.isbn == isbn:
                if not book.is_borrowed:
                    print("This book wasn't borrowed.")
                else:
                    book.is_borrowed = False
                    print(f"You have returned: {book}")
                return
        print("Book not found.")
    def main():
    library = Library()
    
    while True:
        print("\nLibrary Management System")
        print("1. Add Book")
        print("2. View Books")
        print("3. Borrow Book")
        print("4. Return Book")
        print("5. Exit")
        choice = input("Choose an option (1-5): ")
        if choice == '1':
            title = input("Enter the book title: ")
            author = input("Enter the author's name: ")
            isbn = input("Enter the ISBN number: ")
            library.add_book(title, author, isbn)
        elif choice == '2':
            library.view_books()
        elif choice == '3':
            isbn = input("Enter the ISBN of the book to borrow: ")
            library.borrow_book(isbn)
        elif choice == '4':
            isbn = input("Enter the ISBN of the book to return: ")
            library.return_book(isbn)
        elif choice == '5':
            print("Exiting the Library Management System.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 2: Running the Library Management System

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved library_management.py.
    3. Run the script using the command:bashCopy codepython library_management.py

    How It Works

    • Book Class: Represents a book with attributes for title, author, ISBN, and whether it is borrowed.
    • Library Class: Manages a list of books, including adding books, viewing available books, borrowing, and returning books.
    • User Interaction: The command-line interface allows users to choose actions like adding a book, viewing the library, borrowing a book, or returning a book.

    Example Usage

    1. Add Book: Choose option 1 and enter the book title, author, and ISBN to add a new book.
    2. View Books: Choose option 2 to see all available books in the library.
    3. Borrow Book: Choose option 3 and enter the ISBN of the book you want to borrow.
    4. Return Book: Choose option 4 and enter the ISBN of the book you want to return.
    5. Exit: Choose option 5 to exit the system.