Python Modules: Creation and Usage Guide

Python Modules: Creation and Usage Guide

What are Modules in Python?

Modules are simply Python files (with a .py extension) that contain Python code, including:

  • Functions
  • Classes
  • Variables
  • Executable code

They help you organize your code into logical units and promote code reusability.

Creating a Module

1. Basic Module Creation

Create a file named mymodule.py:

python

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

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

PI = 3.14159

class Calculator:
    def multiply(self, x, y):
        return x * y

Using Modules

2. Importing Entire Modules

python

# main.py
import mymodule

# Use functions with module prefix
print(mymodule.greet("Alice"))  # Output: Hello, Alice!
result = mymodule.add(5, 3)
print(result)  # Output: 8

# Access variables
print(mymodule.PI)  # Output: 3.14159

# Use classes
calc = mymodule.Calculator()
print(calc.multiply(4, 5))  # Output: 20

3. Importing Specific Items

python

# Import specific functions/classes
from mymodule import greet, add, Calculator

# Use without module prefix
print(greet("Bob"))  # Output: Hello, Bob!
print(add(10, 20))   # Output: 30

calc = Calculator()

4. Import with Alias

python

# Import with alias
import mymodule as mm

print(mm.greet("Charlie"))  # Output: Hello, Charlie!

5. Import All Items (Not Recommended)

python

# Import everything (use cautiously)
from mymodule import *

print(greet("David"))  # Output: Hello, David!
print(PI)              # Output: 3.14159

Built-in Python Modules

Python comes with many built-in modules:

python

import math
import random
import datetime
import os

# Using built-in modules
print(math.sqrt(16))  # Output: 4.0
print(random.randint(1, 10))  # Random number between 1-10

current_time = datetime.datetime.now()
print(current_time)

Module Search Path

Python searches for modules in this order:

  1. Current directory
  2. Built-in modules
  3. Directories in PYTHONPATH environment variable
  4. Installation-dependent default path

python

import sys
print(sys.path)  # See where Python looks for modules

The __name__ Variable

Useful for making modules that can run as scripts or be imported:

python

# mymodule.py
def main():
    print("This runs when executed directly")

if __name__ == "__main__":
    # This code runs only when the file is executed directly
    main()
    print("Running as main program")
else:
    print("Module imported")

Creating Package Modules

Packages are directories containing multiple modules:

text

mypackage/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        module3.py

python

# Import from packages
from mypackage import module1
from mypackage.subpackage import module3

Python Modules: All Arithmetic and Logical Operations

1. Arithmetic Operations Module

python

# arithmetic_ops.py
"""
Module containing all basic arithmetic operations
"""

def add(a, b):
    """Return the sum of a and b"""
    return a + b

def subtract(a, b):
    """Return the difference between a and b"""
    return a - b

def multiply(a, b):
    """Return the product of a and b"""
    return a * b

def divide(a, b):
    """Return the quotient of a divided by b"""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def floor_divide(a, b):
    """Return the floor division of a by b"""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a // b

def modulus(a, b):
    """Return the remainder of a divided by b"""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a % b

def exponent(a, b):
    """Return a raised to the power of b"""
    return a ** b

def absolute(a):
    """Return the absolute value of a"""
    return abs(a)

def square(a):
    """Return the square of a"""
    return a ** 2

def cube(a):
    """Return the cube of a"""
    return a ** 3

def square_root(a):
    """Return the square root of a"""
    if a < 0:
        raise ValueError("Cannot calculate square root of negative number")
    return a ** 0.5

def factorial(n):
    """Return the factorial of n"""
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0:
        return 1
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# Constants
PI = 3.141592653589793
E = 2.718281828459045

if __name__ == "__main__":
    # Test the module
    print("Testing Arithmetic Operations:")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"10 - 4 = {subtract(10, 4)}")
    print(f"6 * 7 = {multiply(6, 7)}")
    print(f"15 / 3 = {divide(15, 3)}")
    print(f"17 // 5 = {floor_divide(17, 5)}")
    print(f"17 % 5 = {modulus(17, 5)}")
    print(f"2^8 = {exponent(2, 8)}")
    print(f"|-7| = {absolute(-7)}")
    print(f"5! = {factorial(5)}")

2. Logical Operations Module

python

# logical_ops.py
"""
Module containing all logical operations and boolean algebra
"""

def logical_and(a, b):
    """Return logical AND of a and b"""
    return a and b

def logical_or(a, b):
    """Return logical OR of a and b"""
    return a or b

def logical_not(a):
    """Return logical NOT of a"""
    return not a

def logical_xor(a, b):
    """Return logical XOR of a and b"""
    return (a and not b) or (not a and b)

def logical_nand(a, b):
    """Return logical NAND of a and b"""
    return not (a and b)

def logical_nor(a, b):
    """Return logical NOR of a and b"""
    return not (a or b)

def logical_xnor(a, b):
    """Return logical XNOR of a and b"""
    return (a and b) or (not a and not b)

def implies(a, b):
    """Return logical implication (a → b)"""
    return not a or b

def equivalent(a, b):
    """Return logical equivalence (a ↔ b)"""
    return (a and b) or (not a and not b)

def truth_table(operation, name="Operation"):
    """Generate and print truth table for a binary operation"""
    print(f"\n{name} Truth Table:")
    print("A\tB\tResult")
    print("-" * 20)
    
    for a in [True, False]:
        for b in [True, False]:
            result = operation(a, b)
            print(f"{a}\t{b}\t{result}")

# Bitwise operations
def bitwise_and(a, b):
    """Return bitwise AND of a and b"""
    return a & b

def bitwise_or(a, b):
    """Return bitwise OR of a and b"""
    return a | b

def bitwise_xor(a, b):
    """Return bitwise XOR of a and b"""
    return a ^ b

def bitwise_not(a):
    """Return bitwise NOT of a"""
    return ~a

def left_shift(a, n):
    """Return a left-shifted by n bits"""
    return a << n

def right_shift(a, n):
    """Return a right-shifted by n bits"""
    return a >> n

if __name__ == "__main__":
    # Test the module
    print("Testing Logical Operations:")
    
    a, b = True, False
    print(f"AND({a}, {b}) = {logical_and(a, b)}")
    print(f"OR({a}, {b}) = {logical_or(a, b)}")
    print(f"NOT({a}) = {logical_not(a)}")
    print(f"XOR({a}, {b}) = {logical_xor(a, b)}")
    
    # Generate truth tables
    truth_table(logical_and, "AND")
    truth_table(logical_or, "OR")
    truth_table(logical_xor, "XOR")
    
    # Test bitwise operations
    print(f"\nBitwise AND(5, 3) = {bitwise_and(5, 3)}")  # 1
    print(f"Bitwise OR(5, 3) = {bitwise_or(5, 3)}")     # 7
    print(f"Bitwise XOR(5, 3) = {bitwise_xor(5, 3)}")   # 6

3. Advanced Math Module

python

# advanced_math.py
"""
Module containing advanced mathematical operations
"""

import math

def is_prime(n):
    """Check if a number is prime"""
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def gcd(a, b):
    """Return greatest common divisor of a and b"""
    while b:
        a, b = b, a % b
    return abs(a)

def lcm(a, b):
    """Return least common multiple of a and b"""
    if a == 0 or b == 0:
        return 0
    return abs(a * b) // gcd(a, b)

def fibonacci(n):
    """Return the nth Fibonacci number"""
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

def quadratic_roots(a, b, c):
    """Solve quadratic equation ax² + bx + c = 0"""
    discriminant = b**2 - 4*a*c
    
    if discriminant > 0:
        root1 = (-b + math.sqrt(discriminant)) / (2*a)
        root2 = (-b - math.sqrt(discriminant)) / (2*a)
        return (root1, root2)
    elif discriminant == 0:
        root = -b / (2*a)
        return (root,)
    else:
        real = -b / (2*a)
        imaginary = math.sqrt(-discriminant) / (2*a)
        return (complex(real, imaginary), complex(real, -imaginary))

if __name__ == "__main__":
    # Test the module
    print("Testing Advanced Math Operations:")
    print(f"Is 17 prime? {is_prime(17)}")
    print(f"GCD(48, 18) = {gcd(48, 18)}")
    print(f"LCM(12, 15) = {lcm(12, 15)}")
    print(f"Fibonacci(10) = {fibonacci(10)}")
    print(f"Quadratic roots of x² - 5x + 6: {quadratic_roots(1, -5, 6)}")

4. Main Program Using All Modules

python

# main_program.py
"""
Main program demonstrating usage of all mathematical and logical modules
"""

from arithmetic_ops import *
from logical_ops import *
from advanced_math import *

def demonstrate_arithmetic():
    print("=== ARITHMETIC OPERATIONS ===")
    print(f"Addition: 7 + 3 = {add(7, 3)}")
    print(f"Subtraction: 10 - 4 = {subtract(10, 4)}")
    print(f"Multiplication: 6 × 7 = {multiply(6, 7)}")
    print(f"Division: 15 ÷ 4 = {divide(15, 4)}")
    print(f"Exponent: 2^10 = {exponent(2, 10)}")
    print(f"Square root of 25: {square_root(25)}")
    print(f"Factorial of 5: {factorial(5)}")
    print(f"PI constant: {PI}")

def demonstrate_logical():
    print("\n=== LOGICAL OPERATIONS ===")
    a, b = True, False
    print(f"AND({a}, {b}) = {logical_and(a, b)}")
    print(f"OR({a}, {b}) = {logical_or(a, b)}")
    print(f"XOR({a}, {b}) = {logical_xor(a, b)}")
    print(f"NOT({a}) = {logical_not(a)}")
    
    # Bitwise operations
    print(f"\nBitwise AND(12, 25) = {bitwise_and(12, 25)}")
    print(f"Bitwise OR(12, 25) = {bitwise_or(12, 25)}")
    print(f"Bitwise XOR(12, 25) = {bitwise_xor(12, 25)}")

def demonstrate_advanced_math():
    print("\n=== ADVANCED MATH OPERATIONS ===")
    print(f"Is 29 prime? {is_prime(29)}")
    print(f"GCD(56, 98) = {gcd(56, 98)}")
    print(f"LCM(8, 12) = {lcm(8, 12)}")
    print(f"Fibonacci sequence up to 10: {[fibonacci(i) for i in range(11)]}")
    print(f"Quadratic equation 2x² + 4x - 6 = 0: {quadratic_roots(2, 4, -6)}")

def calculator_demo():
    print("\n=== CALCULATOR DEMO ===")
    while True:
        print("\nChoose operation:")
        print("1. Add     2. Subtract  3. Multiply  4. Divide")
        print("5. Exit")
        
        choice = input("Enter choice (1-5): ")
        
        if choice == '5':
            break
            
        if choice in ['1', '2', '3', '4']:
            try:
                num1 = float(input("Enter first number: "))
                num2 = float(input("Enter second number: "))
                
                if choice == '1':
                    result = add(num1, num2)
                    print(f"Result: {num1} + {num2} = {result}")
                elif choice == '2':
                    result = subtract(num1, num2)
                    print(f"Result: {num1} - {num2} = {result}")
                elif choice == '3':
                    result = multiply(num1, num2)
                    print(f"Result: {num1} × {num2} = {result}")
                elif choice == '4':
                    result = divide(num1, num2)
                    print(f"Result: {num1} ÷ {num2} = {result}")
                    
            except ValueError as e:
                print(f"Error: {e}")
            except ZeroDivisionError:
                print("Error: Cannot divide by zero")
        else:
            print("Invalid choice!")

if __name__ == "__main__":
    demonstrate_arithmetic()
    demonstrate_logical()
    demonstrate_advanced_math()
    calculator_demo()

5. Installation and Usage

  1. Save all files in the same directory:
    • arithmetic_ops.py
    • logical_ops.py
    • advanced_math.py
    • main_program.py
  2. Run the main program:

bash

python main_program.py
  1. Run individual modules:

bash

python arithmetic_ops.py
python logical_ops.py
python advanced_math.py

Key Features:

  • Complete arithmetic operations (+, -, ×, ÷, exponents, roots, etc.)
  • All logical operations (AND, OR, NOT, XOR, NAND, NOR, XNOR)
  • Bitwise operations for low-level programming
  • Advanced mathematical functions (prime checking, GCD, LCM, Fibonacci)
  • Error handling for invalid operations
  • Interactive calculator demo
  • Comprehensive testing for each module

This comprehensive set of modules covers all basic and advanced mathematical and logical operations you might need in Python programming!

Similar Posts

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • Finally Block in Exception Handling in Python

    Finally Block in Exception Handling in Python The finally block in Python exception handling executes regardless of whether an exception occurred or not. It’s always executed, making it perfect for cleanup operations like closing files, database connections, or releasing resources. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else:…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

Leave a Reply

Your email address will not be published. Required fields are marked *