PythonForAI Day 6: Libraries and Modules

Welcome to Day 6 of PythonForAI! Today, we will learn about using standard libraries and creating your own modules. Libraries and modules allow you to organize and reuse code efficiently. We’ll cover how to import and use standard libraries like math and datetime, and how to create and use your own modules. Let’s dive in!

Topics to Cover

1. Importing and Using Standard Libraries

Python comes with a rich set of built-in libraries that provide a wide range of functionalities. You can import these libraries and use their functions to perform various tasks.

Example: Using the math Library

The math library provides mathematical functions and constants.

import math

# Using mathematical constants
print(math.pi)  # Output: 3.141592653589793
print(math.e)  # Output: 2.718281828459045

# Using mathematical functions
print(math.sqrt(16))  # Output: 4.0
print(math.factorial(5))  # Output: 120
print(math.sin(math.radians(30)))  # Output: 0.5

Example: Using the datetime Library

The datetime library provides classes for manipulating dates and times.

from datetime import datetime, timedelta

# Get the current date and time
now = datetime.now()
print("Current date and time:", now)

# Format the date and time
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date and time:", formatted_now)

# Calculate the date and time for tomorrow
tomorrow = now + timedelta(days=1)
print("Tomorrow's date and time:", tomorrow)

# Parse a string into a datetime object
date_str = "2023-06-13 15:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Parsed date and time:", parsed_date)

2. Creating Your Own Modules

A module is a file containing Python definitions and statements. You can create your own modules to organize your code into reusable components. To create a module, simply write Python code in a .py file and import it into another script.

Example: Creating a Custom Module

  1. Create a file named mymodule.py with the following content:
# mymodule.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero"
    return a / b
  1. Create another file named main.py in the same directory to import and use the custom module:
# main.py

import mymodule

# Using functions from the custom module
print("Addition:", mymodule.add(5, 3))  # Output: Addition: 8
print("Subtraction:", mymodule.subtract(5, 3))  # Output: Subtraction: 2
print("Multiplication:", mymodule.multiply(5, 3))  # Output: Multiplication: 15
print("Division:", mymodule.divide(5, 3))  # Output: Division: 1.6666666666666667
print("Division by zero:", mymodule.divide(5, 0))  # Output: Division by zero: Error: Division by zero

Potential Problems to Solve

1. Write a Program that Uses the datetime Library to Display the Current Date and Time

We will write a simple program that imports the datetime library and displays the current date and time.

Solution

from datetime import datetime

def display_current_datetime():
    now = datetime.now()
    print("Current date and time:", now)
    formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
    print("Formatted date and time:", formatted_now)

# Run the function
display_current_datetime()

2. Create a Custom Module with a Few Utility Functions and Import it into Another Script

We will create a custom module named utilities.py with utility functions and import it into another script to use the functions.

Step 1: Create utilities.py

# utilities.py

def is_even(number):
    return number % 2 == 0

def is_odd(number):
    return number % 2 != 0

def factorial(n):
    if n == 0:
        return 1
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

Step 2: Create main.py to Import and Use utilities.py

# main.py

import utilities

# Using functions from the custom module
print("Is 4 even?", utilities.is_even(4))  # Output: Is 4 even? True
print("Is 7 odd?", utilities.is_odd(7))  # Output: Is 7 odd? True
print("Factorial of 5:", utilities.factorial(5))  # Output: Factorial of 5: 120

Summary

Today, we learned how to import and use standard libraries such as math and datetime, and how to create and use custom modules. Libraries and modules are essential for organizing and reusing code efficiently. We also applied these concepts by solving practical problems related to date and time manipulation and creating utility functions.

Mastering the use of libraries and modules will greatly enhance your ability to write modular, maintainable, and reusable code. Tomorrow, we will delve into more advanced topics such as object-oriented programming (OOP) in Python.

Keep practicing and experimenting with libraries and modules to strengthen your understanding. Feel free to leave any questions or comments below, and happy coding! 🐍🚀


Additional Resources

Frequently Asked Questions (FAQs)

Q1: How do I install third-party libraries in Python?
You can install third-party libraries using pip, the Python package installer. For example, to install the requests library, you would run pip install requests in your terminal.

Q2: What is the difference between a module and a package?

  • A module is a single file containing Python code.
  • A package is a collection of modules organized in a directory hierarchy. A package contains a special file called __init__.py.

Q3: Can I import specific functions from a module?
Yes, you can import specific functions from a module using the from keyword. For example, from math import pi, sqrt.

Q4: How can I reload a module after making changes to it?
If you make changes to a module and want to reload it without restarting your Python interpreter, you can use the reload() function from the importlib module: from importlib import reload.

Q5: Can I have multiple functions with the same name in different modules?
Yes, functions in different modules can have the same name. When you import the modules, you can call the functions using the module name as a prefix, e.g., module1.function_name() and module2.function_name().

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 482