Author: saqibkhan

  • 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 [Book(**data) for data in json.load(file)]
        return []
    def save_books(self):
        """Save books to a JSON file."""
        with open(self.filename, 'w') as file:
            json.dump([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 = [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.
  • Weather Forecast Application

    Get API Key

    1. Sign up at OpenWeatherMap and create an API key.
    2. Note the API key, as you will need it to make requests.

    Step 2: Install Required Packages

    You’ll need the requests library to make API calls. You can install it using pip:

    bashCopy codepip install requests
    

    Step 3: Create the Weather Application

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

    pythonCopy codeimport requests
    
    class WeatherForecast:
    
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "http://api.openweathermap.org/data/2.5/weather"
    def get_weather(self, city):
        """Fetch the weather data for the given city."""
        try:
            params = {
                'q': city,
                'appid': self.api_key,
                'units': 'metric'  # Change to 'imperial' for Fahrenheit
            }
            response = requests.get(self.base_url, params=params)
            response.raise_for_status()  # Raise an error for bad responses
            return response.json()
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error: {e}")
            return None
        except Exception as e:
            print(f"Error fetching weather data: {e}")
            return None
    def display_weather(self, city):
        """Display the weather information."""
        weather_data = self.get_weather(city)
        if weather_data:
            city_name = weather_data&#91;'name']
            temperature = weather_data&#91;'main']&#91;'temp']
            description = weather_data&#91;'weather']&#91;0]&#91;'description']
            humidity = weather_data&#91;'main']&#91;'humidity']
            wind_speed = weather_data&#91;'wind']&#91;'speed']
            print(f"\nWeather in {city_name}:")
            print(f"Temperature: {temperature}°C")
            print(f"Description: {description.capitalize()}")
            print(f"Humidity: {humidity}%")
            print(f"Wind Speed: {wind_speed} m/s")
        else:
            print("Could not retrieve weather data.")
    def main():
    api_key = input("Enter your OpenWeatherMap API key: ")
    weather_app = WeatherForecast(api_key)
    while True:
        city = input("\nEnter city name (or 'quit' to exit): ")
        if city.lower() == 'quit':
            print("Exiting the application.")
            break
        weather_app.display_weather(city)
    if __name__ == "__main__":
    main()

    Step 4: Running the Weather Application

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

    How It Works

    • API Integration: The application fetches weather data from OpenWeatherMap using an API call based on the city name provided by the user.
    • Data Display: It displays the temperature, weather description, humidity, and wind speed.
    • User Input: The user can enter a city name to get the weather or type quit to exit.
  • Custom Shell

    Create the Shell

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

    pythonCopy codeimport os
    import subprocess
    
    class CustomShell:
    
    def __init__(self):
        self.running = True
    def run(self):
        while self.running:
            try:
                command = input(f"{os.getcwd()}$ ").strip()
                self.process_command(command)
            except KeyboardInterrupt:
                print("\nExiting the shell.")
                self.running = False
    def process_command(self, command):
        if command.lower() in &#91;'exit', 'quit']:
            self.running = False
            return
        elif command.startswith('cd '):
            self.change_directory(command&#91;3:])
        else:
            self.execute_command(command)
    def change_directory(self, path):
        try:
            os.chdir(path)
            print(f"Changed directory to {os.getcwd()}")
        except Exception as e:
            print(f"cd: {e}")
    def execute_command(self, command):
        try:
            # Execute the command
            result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error: {e.stderr.strip()}")
    if __name__ == "__main__":
    shell = CustomShell()
    shell.run()

    Step 2: Running the Custom Shell

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

    How It Works

    • Command Input: The shell prompts you to enter a command.
    • Command Processing:
      • Exit Command: You can type exit or quit to exit the shell.
      • Change Directory: Use cd <directory> to change the current working directory.
      • Execute Command: Any other command is executed using the subprocess module.
    • Error Handling: The shell handles errors gracefully, providing feedback if a command fails.

    Example Usage

    1. Change Directory: Type cd path/to/directory to navigate to a different directory.
    2. Execute Commands: Type commands like ls (or dir on Windows) to list files, or echo Hello World to print a message.
    3. Exit: Type exit or quit to close the shell.