HTML

    Select a Subtopic

    Day 9: Working with Packages

    Let's dive into how to work with packages in Python. This day focuses on creating, installing, and managing packages using `pip` and virtual environments.

    Topics Covered:

    • Creating Packages
    • Installing Packages using pip
    • Virtual Environments

    1. Creating Packages

    A package in Python is a directory that contains multiple Python files (modules) and a special __init__.py file to indicate it is a package.

    Example:

    my_package/ __init__.py module1.py module2.py

    Now, you can use your package by importing it:

    import my_package print(my_package.greet("Alice")) print(my_package.farewell("Bob"))

    2. Installing Packages Using pip

    Use pip to install external libraries from PyPI.

    Steps to Install a Package:

    • Open your terminal/command prompt.
    • Run the command: pip install packagename

    Example:

    pip install requests

    Using the Installed Package:

    import requests response = requests.get('https://api.github.com') print(response.status_code)

    3. Virtual Environments

    A virtual environment helps isolate project dependencies.

    Steps to Create a Virtual Environment:

    1. Run the following command: python -m venv myenv
    2. Activate the virtual environment:
      • On Windows: myenv\Scripts\activate
      • On Mac/Linux: source myenv/bin/activate
    3. Install packages using pip.
    4. Deactivate the environment using: deactivate

    Example:

    python -m venv myenv

    Exercises for Day 9

    • Create your own package with two modules: math_utils and string_utils.
    • Install the requests package and fetch the HTML of a webpage.
    • Create and use a virtual environment, then install a package inside it.

    Summary

    By the end of **Day 9**, you should be comfortable with:

    • Creating and using Python packages.
    • Installing external packages with pip.
    • Setting up and using virtual environments.