Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Modules

In this Python Modules tutorial, we'll cover the basics of using modules in Python, including importing and organizing code into modules.

  1. What is a Module?
  2. Importing Modules
  3. Organizing Code in Modules
  4. The __name__ attribute

1. What is a Module?

A module in Python is simply a file containing Python code. Modules are used to organize code into separate, reusable components, which can then be imported and used in other programs. By splitting code into modules, you can reuse functionality across multiple projects and keep your codebase organized and maintainable.

2. Importing Modules

To use a module in your Python code, you need to import it using the import statement. When you import a module, Python will search for the module in its module search path, which includes the current directory and the directories listed in the sys.path variable.

Here's an example of importing a built-in module, the math module:

import math

# Now you can access the functions and variables in the math module
result = math.sqrt(25)
print(result)  # Output: 5.0

You can also import specific functions or variables from a module using the from ... import ... statement:

from math import sqrt

result = sqrt(25)
print(result)  # Output: 5.0

To import multiple items from a module, separate them with commas:

from math import sqrt, pi

result = sqrt(pi)
print(result)  # Output: 1.77245385091

To avoid naming conflicts or make your code more readable, you can use the as keyword to create an alias for the imported module, function, or variable:

import math as m

result = m.sqrt(25)
print(result)  # Output: 5.0

3. Organizing Code in Modules

To create your own module, simply create a new .py file and define your functions, classes, and variables within it. Let's create a simple module called mymodule.py:

# mymodule.py

def greet(name):
    return f"Hello, {name}!"

Now you can import and use your custom module in other Python programs:

import mymodule

greeting = mymodule.greet("Alice")
print(greeting)  # Output: Hello, Alice!

4. The __name__ attribute

Every Python module has a built-in attribute called __name__. When a module is run as the main program, its __name__ attribute is set to "__main__". When a module is imported, its __name__ attribute is set to the module's name.

You can use the __name__ attribute to conditionally execute code in your module. For example, you might have some code that you want to run only when the module is executed as the main program, but not when it's imported:

# mymodule.py

def greet(name):
    return f"Hello, {name}!"

def main():
    print(greet("Alice"))

if __name__ == "__main__":
    main()

Now, when you run mymodule.py as the main program, it will execute the main() function. But when you import mymodule in another Python program, the main() function will not be executed.

  1. How to create a module in Python:

    • Description: A module in Python is a file containing Python definitions and statements. You can create a module by writing Python code in a file with a .py extension.
    • Example Code:
      # mymodule.py
      def greeting(name):
          return f"Hello, {name}!"
      
  2. Importing modules in Python:

    • Description: Modules are imported using the import keyword, allowing access to the functions and variables defined in the module.
    • Example Code:
      import mymodule
      
      message = mymodule.greeting("Alice")
      print(message)
      
  3. Built-in modules in Python:

    • Description: Python comes with a set of built-in modules that provide additional functionality. Examples include math, random, and datetime.
    • Example Code:
      import math
      
      square_root = math.sqrt(25)
      print(square_root)
      
  4. Creating and using custom modules in Python:

    • Description: Custom modules are created by defining functions and variables in a separate Python file and then importing them into other scripts.
    • Example Code:
      # mycustommodule.py
      def multiply(x, y):
          return x * y
      
      # main script
      import mycustommodule
      
      result = mycustommodule.multiply(3, 4)
      print(result)
      
  5. Exploring standard library modules in Python:

    • Description: Python's standard library includes a rich set of modules for various purposes. Explore modules like os, sys, and collections for different functionalities.
    • Example Code:
      import os
      
      current_directory = os.getcwd()
      print(current_directory)
      
  6. Module attributes and functions in Python:

    • Description: Modules can have attributes (variables) and functions. These attributes and functions are accessed using dot notation after importing the module.
    • Example Code:
      # mymodule.py
      pi = 3.14
      
      def area(radius):
          return pi * radius**2
      
      # main script
      import mymodule
      
      circle_area = mymodule.area(5)
      print(circle_area)
      
  7. Module namespaces in Python:

    • Description: Modules provide namespaces, isolating their attributes and functions. Access module items using the module's name.
    • Example Code:
      # mymodule.py
      variable_in_module = "I am in the module!"
      
      # main script
      import mymodule
      
      print(mymodule.variable_in_module)