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

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • difference between positional and keyword arguments

    1. Positional Arguments How they work: The arguments you pass are matched to the function’s parameters based solely on their order (i.e., their position). The first argument is assigned to the first parameter, the second to the second, and so on. Example: python def describe_pet(animal_type, pet_name): “””Display information about a pet.””” print(f”\nI have a {animal_type}.”) print(f”My {animal_type}’s name…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

Leave a Reply

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