Python Modules

Python Modules

In Python, modules are files containing Python code that can define functions, classes, and variables. They help in organizing the code logically and enable code reuse. Instead of writing everything in one file, you can write your code in separate modules and then import them where needed.

Why Use Modules?
    ● Reusability: You can write a module once and reuse it in multiple programs.
    ● Organization: Large codebases can be divided into smaller, more manageable pieces.

Importing a Module
You can import a module into your Python script using the import keyword. Here’s an example of using a built-in module:

Syntax:
import package_name

Example:

import math

Here, the package can be imported by writing import math statement
 
Types of Python Modules:
1. Built-in Modules: These are the modules that come with Python installation.
    a. math Module
      The math module provides a set of mathematical functions, such as trigonometric, logarithmic, and exponential
       functions.
 
    Common Use Cases:
      ● Advanced mathematical calculations.
      ● Working with constants like pi and e.
 
Example:

import math
# Square root of a number
print(math.sqrt(16))        #Output: 4
# Value of pi
print(math.pi)                #Output: 3.141592653589793

Some commonly used functions from math module:

Function Description Example Output
math.sqrt(x) Returns the square root of x. math.sqrt(16) 4
math.pow(x, y) Returns x raised to the power of y. math.pow(2, 3) 8
math.floor(x) Returns the largest integer less than or equal to x. math.floor(4.7) 4
math.factorial(x) Returns the factorial of x. math.factorial(5) 120
math.gcd(x, y) Returns the greatest common divisor of x and y. math.gcd(12, 15) 3
math.sin(x) Returns the sine of x (in radians). math.sin(math.pi / 2) 1
math.cos(x) Returns the cosine of x (in radians). math.cos(0) 1
math.pi Returns the value of Pi (constant). math.pi 3.141592654
b. random Module
The random module is used for generating random numbers and working with randomization in Python.
 
Common Use Cases:
    ● Generating random numbers.
    ● Shuffling sequences.
    ● Selecting random elements from a list.
 
Example:

import random

# Random number between 1 and 10
print(random.randint(1, 10))
#Output: 5 (or can be any number between 1-10 )
# Shuffle a list
items = [1, 2, 3, 4, 5]
random.shuffle(items)
#Output: [2, 3, 5, 1, 4]
print(items)

c. datetime Module
The datetime module provides classes for manipulating dates and times. It’s commonly used for working with date and time objects.
Common Use Cases:
    ● Getting the current date and time.
    ● Formatting dates.
    ● Calculating time differences.
Example:

import datetime

# Get current date and time
now = datetime.datetime.now()
print(“Current Date and Time:”, now)
#Output: Current Date and Time: 2024-09-14 13:40:56.770829

# Format date as string
formatted_date = now.strftime(“%d-%m-%Y”)
print(“Formatted Date:”, formatted_date)
#Output: Formatted Date: 14-09-2024

#Time difference
date1 = datetime.datetime(2024, 9, 1) #creating datetime obj
print(date1) # September 1, 2024

difference = now – date1
print(difference) #Output: 13 days, 13:46:52.940377

2. User-Defined Modules: These are modules created by the user (by us).
Module is nothing but a file with some python code and .py extension. So, let’s create our own module named as my_module.py

Step 1: Create a file named my_module.py

Step 2: Write some code in my_module.py file

# my_module.py

def greet(name):
      return f”Hello, {name}!”

pi = 3.14159

Step 3: Create another file with name module_test.py

Step 4: Now in this file, we will import out previously created module i.e. my_module.py

import my_module

# Call the greet function from my_module
message = my_module.greet(“Jannat”)
print(message) # Output: Hello, Jannat!

# Access the pi variable from my_module
print(my_module.pi) # Output: 3.14159

In this way, we can create and use our own module, i.e. user-defined module

Example: Let’s create a basic calculator application using python modules
First, we’ll create a module (file) named calculator.py that contains the functions for the
basic operations.

# calculator.py
def add(x, y):
“””Return the sum of x and y.”””
      return x + y

def subtract(x, y):
“””Return the difference of x and y.”””
      return x – y

def multiply(x, y):
“””Return the product of x and y.”””
      return x * y

def divide(x, y):
“””Return the quotient of x and y. Raise ValueError if y is zero.”””
      if y == 0:
              raise ValueError(“Cannot divide by zero!”)
      return x / y

Here, we have defined arithmetic functions like addition, subtraction, multiplication,
division for our calculator in this file

Now, we’ll create a main program that uses this calculator module. Let’s call this file
test.py.

# test.py
from calculator import add, subtract, multiply, divide

print(“Welcome to the Calculator!”)
print(“Select an operation:”)
print(“1. Add”)
print(“2. Subtract”)
print(“3. Multiply”)
print(“4. Divide”)

while True:
        choice = input(“Enter choice (1/2/3/4): “)

        if choice in [‘1’, ‘2’, ‘3’, ‘4’]:
            num1 = float(input(“Enter first number: “))
            num2 = float(input(“Enter second number: “))

               if choice == ‘1’:
                    print(f”{num1} + {num2} = {add(num1, num2)}”)
               elif choice == ‘2’:
                    print(f”{num1} – {num2} = {subtract(num1, num2)}”)
               elif choice == ‘3’:
                    print(f”{num1} * {num2} = {multiply(num1, num2)}”)
               elif choice == ‘4’:
                      try:
                             print(f”{num1} / {num2} = {divide(num1, num2)}”)
                      except ValueError as e:
                             print(e)
               else:
                      print(“Invalid Input”)

               next_calculation = input(“Do you want to perform another calculation? (yes/no): “)
       if next_calculation.lower() != ‘yes’:
                      break

Output:

Course Video

Course Video English:

Task:
1. Use a random module to create a guessing game to guess a number between 1-10. If the number guessed by the module and the number guessed by the user is the same print “You won” else print “Better Luck, next time!”
Expected Output:

2. Create a user-defined module, in that, create a function to perform addition of two numbers. Use that function in another file by calling the created module.

Task Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

 Python has a large standard library with many built-in modules.

How many classes in a Python module? Modules can have multiple classes depending on the design.

What is Python types module? It’s a module that provides functions for Python types.

Main module of Python? The main module is the script that is executed directly. packages.

 Files containing Python definitions and statements.

To use code from external sources and avoid redundancy.

Import command in Python? import module_name.

Is Numpy a standard Python library? No, it’s an external library.

Standard library modules? Built-in modules like math, os, sys.

 Modules are imported from the standard library or external packages.