Python 3 — Functions & Reusable Code
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.
Use the def keyword to define a function. Code inside must be indented. Call it by name followed by parentheses:
# 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
Pass data into functions using parameters. Get results back with return:
# 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
Give parameters default values — if the caller doesn't provide them, the default is used:
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)
For functions that accept a variable number of arguments:
| Syntax | What it does | Type received |
|---|---|---|
*args | Accepts any number of positional arguments | tuple |
**kwargs | Accepts any number of keyword arguments | dict |
# *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}")
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
Lambda functions are compact one-line functions using the lambda keyword:
# 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)
A function that calls itself is called recursive. Always have a base case to stop recursion:
# 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
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.
Build a mini math library with these functions:
is_even(n)— returns True if n is evenclamp(value, min_val, max_val)— restricts value to a rangecelsius_to_fahrenheit(c)— converts temperaturesum_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