मुख्य कंटेंट तक स्किप करें

Modules in Python

Ayesha
EditReport

Hey there! In this guide, we'll explore modules in Python. Modules are files containing Python code that can define functions, classes, and variables. They allow you to organize your code logically and reuse code across different programs. Let's dive in!


Python Modules

  • Code Organization: Modules help organize code into manageable sections, making it easier to maintain.
  • Reusability: You can reuse code in multiple programs without rewriting it.
  • Standard Library: Python comes with a standard library of modules that provide useful functions and tools.

Video Explanation

1. Creating a Module

You can create a module by simply creating a new Python file (with a .py extension) and defining functions or variables in it.

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

PI = 3.14159

2. Importing a Module

You can import a module using the import statement. You can import the entire module or specific functions or variables.

import my_module # Import the entire module
from my_module import greet # Import specific function

print(my_module.PI) # Output: 3.14159
print(greet("Alice")) # Output: Hello, Alice!

3. Importing with Aliases

You can give a module or function an alias using the as keyword to simplify its usage.

import my_module as mm

print(mm.PI) # Output: 3.14159
print(mm.greet("Bob")) # Output: Hello, Bob!

4. The __name__ Variable

The __name__ variable allows you to check if a module is being run as the main program or if it is being imported.

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

if __name__ == "__main__":
print(greet("Main")) # This code runs only if the module is executed directly

5. Using Standard Library Modules

Python's standard library provides many built-in modules you can use in your programs.

import math

print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Modules in Python"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.