Python Modules: Creation and Usage Guide

UpComing SoftWare Training Demos

🚀 *Gen AI Engineer Telugu (Production Focused)*
🗓️ *Date:* 30th Sept 2026, 07:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
🗓️ *Date:* 30th Sept 2026, 08:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/7r
👥 *Join WA Community:*
https://www.vlrt.in/7w
💡*Course Content:*
https://www.vlrt.in/7c
▶️ *Demo Videos:*
https://www.vlrt.in/7v

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 30th Sept 2026, 09:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

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

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • non-capturing group, Named Groups,groupdict()

    To create a non-capturing group in Python’s re module, you use the syntax (?:…). This groups a part of a regular expression together without creating a backreference for that group. A capturing group (…) saves the matched text. You can then access this captured text using methods like group(1), group(2), etc. A non-capturing group (?:…)…

  • Decorators in Python

    Decorators in Python A decorator is a function that modifies the behavior of another function without permanently modifying it. Decorators are a powerful tool that use closure functions. Basic Concept A decorator: Simple Example python def simple_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is…

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

Leave a Reply

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