10. Functions and Modular Programming
What Are Functions?
Functions let you group related code into reusable blocks. Instead of repeating yourself, you write a function once and use it anytime you need it — clean and efficient.
def greet():
print("Hello from a function!")
greet()Function Parameters
You can pass values into functions using parameters.
def greet(name):
print(f"Hello, {name}!")
greet("Sarah")Return Values
Functions can return a value using the `return` keyword.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8Default Parameter Values
You can assign default values to parameters so they become optional.
def greet(name="friend"):
print(f"Hello, {name}!")
greet()
greet("David")*args and **kwargs
`*args` allows variable number of positional arguments, while `**kwargs` allows named arguments.
def show_scores(*scores):
for score in scores:
print(score)
show_scores(88, 92, 76)
def show_user(**details):
print(details)
show_user(name="Sarah", age=22)Why Use Modular Programming?
As projects grow, writing everything in one file becomes messy. Modular programming lets you split code across multiple files (called modules) for clarity and reuse.
# math_utils.py
def multiply(a, b):
return a * b
# main.py
from math_utils import multiply
print(multiply(4, 6))Mini Exercise
Create a function called `calculate_discount(price, discount)` that returns the final price after applying a percentage discount. Then move the function to a separate module and import it into another file.