Functions and modules help you organize and reuse code in Python. They make your programs cleaner, more efficient, and easier to manage.
A function is a block of reusable code that performs a specific task. You define it using the def
keyword.
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
A module is a Python file (.py) that contains functions, variables, or classes you can use in other programs.
math_utils.py
):def square(x):
return x * x
def cube(x):
return x * x * x
import math_utils
print(math_utils.square(4)) # Output: 16
print(math_utils.cube(3)) # Output: 27
from math_utils import square
print(square(5)) # Output: 25
Python comes with many useful built-in modules like:
math
– for mathematical functionsrandom
– for random number generationdatetime
– for working with dates and timesimport math
print(math.sqrt(16)) # Output: 4.0
Use functions to keep your code organized and avoid repetition. Use modules to break large programs into smaller, manageable pieces.
Functions are reusable blocks of code.
def greet():
print("Hello, welcome to Python!")
greet()
def power(base, exponent=2):
return base ** exponent
print(power(3))
print(power(3, 3))
def square(n):
return n * n
result = square(4)
print(result)
def local_example():
x = 10
print(x)
local_example()
y = 50
def global_example():
global y
y += 10
print(y)
global_example()
square = lambda x: x * x
print(square(5))
# mymodule.py
def greet(name):
return f"Hello, {name}!"
try:
x = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
def check_age(age):
if age < 18:
raise ValueError("Must be 18 or older")
return "Allowed"
print(check_age(20))
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception")
except CustomError as e:
print(e)