Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Are Functions?
  • - Function Parameters
  • - Return Values
  • - Default Parameter Values
  • - *args and **kwargs
  • - Why Use Modular Programming?
  • - Mini Exercise

10. Functions and Modular Programming

Level: IntermediateDuration: 35m

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.

python
def greet():
    print("Hello from a function!")

greet()

Function Parameters

You can pass values into functions using parameters.

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

greet("Sarah")

Return Values

Functions can return a value using the `return` keyword.

python
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # 8
💡 Tip: A function without a return statement automatically returns `None`.

Default Parameter Values

You can assign default values to parameters so they become optional.

python
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.

python
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.

python
# math_utils.py

def multiply(a, b):
    return a * b

# main.py
from math_utils import multiply
print(multiply(4, 6))

Python Modules Documentation

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.