Python for Everybody: Learn Python from Scratch
About Lesson

Modules

  • What are Modules?: Modules are files containing Python code. They help organize our program by separating related functionality.
  • Modules and Libraries: Import external modules and use their functionality.
  • Creating a Module:
    • Let’s create a simple module named math_operations.py:
      Python

      # math_operations.py
      def add(a, b):
          return a + b
      
      def subtract(a, b):
          return a - b
  • Using a Module:
    • In another Python file, we can import and use the functions from our module:
      Python
      # main.py
      import math_operations
      
      result1 = math_operations.add(5, 3)
      result2 = math_operations.subtract(10, 4)
      
      print(f"Addition result: {result1}")
      print(f"Subtraction result: {result2}")
      

Standard Library Modules

  • Python provides a rich set of standard library modules for common tasks.
  • Example: Using the math module to get the value of π (pi):
    Python
    import math
    
    print(f"The value of π is approximately {math.pi}")
    

Best Practices

  • Keep functions small and focused.
  • Use meaningful function names.
  • Organize related functions into modules.
  • Avoid naming conflicts by using unique module names.

By mastering functions and modules, you’ll write cleaner, more maintainable code. Keep practicing and building!

Join the conversation