Learn how to define and use functions inside Python modules. This guide covers creating a module, importing it, and organizing your Python code for better reusability and clarity.
__name__
In Python, a module is a file containing Python code (functions, classes, variables, or runnable code) that can be imported and used in other Python programs. Modules help in organizing code logically, promoting reusability and maintainability.
Reason | Benefit |
---|---|
Code reusability | Write once, use many times |
Better organization | Separate logic into smaller, manageable pieces |
Easier debugging | Errors are easier to isolate in smaller files |
Collaboration | Multiple people can work on different modules |
math
, os
, sys
, random
import math
print(math.sqrt(25)) # Output: 5.0
mymodule.py
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Then import it:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
pip
)numpy
, requests
, pandas
pip install numpy
import numpy as np
arr = np.array([1, 2, 3])
print(arr) # Output: [1 2 3]
import module_name
module_name.function()
import module_name as alias
alias.function()
from module_name import function1, function2
function1()
from module_name import * # Avoid (pollutes namespace)
function1()
math_utils.py
)**
Save functions in a .py
file, e.g., math_utils.py
:
# calc.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
import calc
print(math_utils.add(3, 4)) # Output: 7
print(math_utils.subtract(10, 5)) # Output: 5
Or import specific functions:
from math_utils import add
print(add(2, 2)) # Output: 4
or Import with Alias (‘calc’):
import math_utils as calc
result= calc.add(5, 3)
print(result)
result2 = calc.subtract(10, 4)
print(result2)
Create a module file greetings.py
:
def hello(name):
return f"Hello, {name}!"
def goodbye(name):
return f"Goodbye, {name}!"
Use the module in another script:
import greetings
print(greetings.hello("Alice"))
print(greetings.goodbye("Alice"))
__name__
In Python, the __name__
variable is a special built-in variable that helps determine whether a script is being run directly or being imported as a module into another script.
__name__
Works:__name__
is set to "__main__"
.__name__
is set to the module’s name.def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__":
# Test the functions in this module
print("Testing math_utils.py")
print(f"2 + 3 = {add(2, 3)}")
print(f"5 - 2 = {subtract(5, 2)}")
print("All tests passed!")
This construct allows you to:
__name__
Across Two Filesmodule.py
)# module.py
def greet(name):
return f"Hello, {name}!"
print(f"Module's __name__: {__name__}") # Check __name__
if __name__ == "__main__":
print("This runs only when module.py is executed directly.")
- If you run module.py
directly, it prints:
Module's __name__: __main__
This runs only when module.py is executed directly.
if __name__ == "__main__":
block does not run.module.py
in Another Script (main_script.py
)# main_script.py
import module # Imports module.py
print(f"Main script's __name__: {__name__}") # Check __name__ in main file
print(module.greet("Alice"))
Output when running main_script.py
:
Module's __name__: module # (Because it was imported)
Main script's __name__: __main__ # (Because main_script.py is run directly)
Hello, Alice!
if __name__ == "__main__":
block in module.py
does not execute because it was imported.__name__
if __name__ == "__main__":
to ensure certain code (like tests) runs only when the script is executed directly, not when imported.if __name__ == "__main__":
to test functions without affecting imports.✅ Modules help organize and reuse code.
✅ Python has built-in, user-defined, and third-party modules.
✅ Use import
to include modules in your code.
✅ __name__
helps in writing module test cases.
✅ Task 1: Create a module named calculator.py
with functions multiply
, divide
.
✅ Task 2: Create a main script main.py
and use calculator
functions.
✅ Task 3: Create a module string_utils.py
with a function is_palindrome(text)
that returns True
if a word is a palindrome.
✅ Task 4: Create a module geometry.py
with functions like area_of_circle(r)
and area_of_square(side)
.