Python Modules

Python modules are files containing Python definitions and statements. They are used to organize code and avoid code duplication.

Example 1: Importing and Using the `math` Module


    import math
    
    result = math.sqrt(25)
    print(result)  # Output: 5.0
    
    print(math.pi) # Output: 3.141592653589793
        

Example 2: Importing Specific Functions


    from math import sqrt
    
    result = sqrt(16)
    print(result)  # Output: 4.0
        

Import only the needed function, reducing code clutter.

Example 3: Importing a Module with an Alias


    import math as m
    
    result = m.cos(math.pi)
    print(result) # Output: -1.0
        

Example 4: Importing from a Specific Submodule


    from math import pi, cos, floor
    
    print(pi)
    print(cos(pi))
    print(floor(3.14))  # Output: 3
        

Example 5: Creating Your Own Module

Save the following code as `my_module.py`:


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

Then, in your main script:


    import my_module
    
    my_module.greet("Anam")  # Output: Hello, Anam!
        

Example 6: Working with `random`


    import random
    
    random_number = random.randint(1, 10)
    print(random_number)
    
    random_choice = random.choice(["apple", "banana", "cherry"])
    print(random_choice)
        

Example 7: Using `datetime`


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

Important Considerations

  • `import` statement: Use `import` to bring modules into your script.
  • `from ... import` statement: Use this to import specific functions or classes from a module to reduce clutter.
  • Aliasing modules: Use `import module as alias` for more concise references.
  • Modules in Packages: Python's module system allows you to organize code in logical units (packages).
  • Standard Library: Python's rich standard library provides many pre-built modules (e.g., `math`, `random`, `datetime`, `os`).