Python 3 — Functions & Reusable Code

🐍 Python 3 🟢 Lesson 10 📅 July 2026

Writing clean code means avoiding repetition (the DRY principle: Don't Repeat Yourself). Functions are reusable blocks of code that you define once and call as many times as you need. They make your programs organized, testable, and maintainable.

1 Defining & Calling Functions

Use the def keyword to define a function. Code inside must be indented. Call it by name followed by parentheses:

Python 3 — Simple Function▶ Run Code
# Define function
def greet():
    print("Welcome back, coder!")
    print("Let's write some Python code.")

# Call the function (can call multiple times)
greet()
greet()

# Function with docstring (documentation)
def show_info():
    """Displays program information to the user."""
    print("=== Python Tutorial v1.0 ===")
    print("Developed with Our Compiler")

show_info()
print(show_info.__doc__)  # Access docstring
2 Parameters & Return Values

Pass data into functions using parameters. Get results back with return:

Python 3 — Parameters & Return▶ Run Code
# Function with parameters
def calculate_area(length, width):
    area = length * width
    return area

result = calculate_area(5, 10)
print(f"Area: {result}")   # Area: 50

# Multiple return values (returns a tuple)
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 7, 1, 9, 4])
print(f"Min: {low}, Max: {high}")   # Min: 1, Max: 9

# Returning early
def divide(a, b):
    if b == 0:
        return None  # Early return
    return a / b

print(divide(10, 2))   # 5.0
print(divide(10, 0))   # None
3 Default Parameters

Give parameters default values — if the caller doesn't provide them, the default is used:

Python 3 — Default Parameters▶ Run Code
def greet_user(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")

greet_user("Balaji")               # Hello, Balaji!
greet_user("Alice", "Hi")          # Hi, Alice!
greet_user("Bob", "Hey", ".")      # Hey, Bob.

# Power function with default exponent
def power(base, exp=2):
    return base ** exp

print(power(5))       # 25 (5 squared by default)
print(power(5, 3))    # 125 (5 cubed)
4 *args and **kwargs

For functions that accept a variable number of arguments:

SyntaxWhat it doesType received
*argsAccepts any number of positional argumentstuple
**kwargsAccepts any number of keyword argumentsdict
Python 3 — *args & **kwargs▶ Run Code
# *args — variable positional arguments
def add_all(*numbers):
    print(f"Numbers received: {numbers}")  # It's a tuple
    return sum(numbers)

print(add_all(1, 2))          # 3
print(add_all(1, 2, 3, 4, 5)) # 15

# **kwargs — variable keyword arguments
def display_profile(**info):
    print(f"Profile info: {info}")   # It's a dict
    for key, value in info.items():
        print(f"  {key}: {value}")

display_profile(name="Balaji", age=25, city="Hyderabad")

# Combining all types
def full_example(required, *args, default="ok", **kwargs):
    print(f"required={required}, args={args}, default={default}, kwargs={kwargs}")
5 Local vs Global Scope
Python 3 — Variable Scope▶ Run Code
app_name = "Our Compiler"   # Global variable

def display():
    local_msg = "Inside function"  # Local variable
    print(app_name)   # Can READ global variables
    print(local_msg)

display()
# print(local_msg)  # ❌ NameError: not accessible outside

# Modifying a global variable inside a function
counter = 0

def increment():
    global counter    # Declare intent to modify global
    counter += 1

increment()
increment()
print(f"Counter: {counter}")  # Counter: 2
6 Lambda Functions (Anonymous Functions)

Lambda functions are compact one-line functions using the lambda keyword:

Python 3 — Lambda Functions▶ Run Code
# Regular function
def square(x):
    return x ** 2

# Equivalent lambda
square = lambda x: x ** 2
print(square(5))   # 25

# Lambda with multiple parameters
add = lambda a, b: a + b
print(add(3, 7))   # 10

# Lambdas shine when used with sorted(), map(), filter()
students = [("Alice", 92), ("Bob", 78), ("Charlie", 85)]

# Sort by score (second element)
students.sort(key=lambda s: s[1])
print(students)  # Sorted by score ascending

# Filter students who scored above 80
top = list(filter(lambda s: s[1] > 80, students))
print(top)

# Double all scores
doubled = list(map(lambda s: (s[0], s[1] * 2), students))
print(doubled)
7 Recursion

A function that calls itself is called recursive. Always have a base case to stop recursion:

Python 3 — Recursion▶ Run Code
# Factorial: 5! = 5 × 4 × 3 × 2 × 1 = 120
def factorial(n):
    if n == 0 or n == 1:   # Base case
        return 1
    return n * factorial(n - 1)  # Recursive case

print(factorial(5))   # 120
print(factorial(10))  # 3628800

# Fibonacci sequence
def fib(n):
    if n <= 1:             # Base case
        return n
    return fib(n-1) + fib(n-2)  # Recursive case

for i in range(10):
    print(fib(i), end=" ")  # 0 1 1 2 3 5 8 13 21 34
⚠️ Return vs Print:

Beginners often confuse print() and return. print() displays text to the terminal but doesn't pass the value back. return sends the value back to the caller, allowing you to store or use it in further calculations.

8 Coding Challenge

Build a mini math library with these functions:

  • is_even(n) — returns True if n is even
  • clamp(value, min_val, max_val) — restricts value to a range
  • celsius_to_fahrenheit(c) — converts temperature
  • sum_of_digits(n) — recursively sums digits of a number (e.g., 123 → 6)
  • flatten(*lists) — combines any number of lists into one using *args
  • Test each function with multiple inputs