Technology

Functions: How to Write Reusable Code

Functions are reusable blocks of code that make programming manageable. Learn how functions work and why they're essential for every programmer.

Superlore TeamJanuary 19, 20264 min read

Functions: How to Write Reusable Code

Imagine writing the same 20 lines of code every time you need to perform a calculation. That's tedious and error-prone. Functions solve this—they're reusable blocks of code you write once and use anywhere.

Functions are fundamental to programming. They make code organized, readable, and maintainable.

What Is a Function?

A function is a named block of code that:
1. Optionally takes input (parameters)
2. Does something
3. Optionally returns output

Simple function:
\\\`python
def greet():
print("Hello, World!")

Calling the function

greet() # Output: Hello, World! greet() # Output: Hello, World! \\\`

Write once, use many times.

Functions with Parameters

Parameters let you pass information into functions:
\\\`python
def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
\\\`

The same function produces different results based on input.

Multiple parameters:
\\\`python
def add(a, b):
print(a + b)

add(3, 5) # Output: 8
add(10, 20) # Output: 30
\\\`

Return Values

Functions can send results back:
\\\`python
def add(a, b):
return a + b

result = add(3, 5)
print(result) # Output: 8

Use directly in expressions

total = add(10, 20) + add(1, 2) # 33 \\\`

The return statement sends a value back to wherever the function was called.

Why Use Functions?

1. Avoid repetition (DRY - Don't Repeat Yourself)

Bad:
\\\`python
print("=" * 50)
print("Welcome to the Program")
print("=" * 50)

... later in code ...

print("=" * 50)
print("Goodbye!")
print("=" * 50)
\\\`

Good:
\\\`python
def print_banner(message):
print("=" * 50)
print(message)
print("=" * 50)

print_banner("Welcome to the Program")
print_banner("Goodbye!")
\\\`

2. Organization

Functions break complex programs into manageable pieces:
\\\`python
def get_user_input():
# Handle input logic

def validate_data(data):
# Handle validation logic

def save_to_database(data):
# Handle database logic

def main():
data = get_user_input()
if validate_data(data):
save_to_database(data)
\\\`

3. Testing

Small functions are easier to test than long scripts.

4. Readability

calculate_tax(price) is clearer than seeing the tax formula everywhere.

Default Parameters

Parameters can have default values:
\\\`python
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
\\\`

Practical Examples

Temperature converter:
\\\`python
def celsius_to_fahrenheit(celsius):
return celsius * 9/5 + 32

def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9

print(celsius_to_fahrenheit(0)) # 32.0
print(fahrenheit_to_celsius(98.6)) # 37.0
\\\`

Password strength checker:
\\\`python
def check_password_strength(password):
if len(password) < 8:
return "Weak: Too short"
if password.isalpha():
return "Medium: Add numbers"
if password.isalnum():
return "Medium: Add special characters"
return "Strong"

print(check_password_strength("abc")) # Weak: Too short
print(check_password_strength("password")) # Medium: Add numbers
print(check_password_strength("pass123!")) # Strong
\\\`

List operations:
\\\`python
def find_max(numbers):
if not numbers:
return None
max_value = numbers[0]
for num in numbers:
if num > max_value:
max_value = num
return max_value

def find_average(numbers):
if not numbers:
return None
return sum(numbers) / len(numbers)

data = [4, 8, 2, 9, 1, 5]
print(find_max(data)) # 9
print(find_average(data)) # 4.833...
\\\`

Function Scope

Variables inside functions are "local"—they don't exist outside:
\\\`python
def my_function():
local_var = "I'm local"
print(local_var) # Works

my_function()
print(local_var) # Error! Not defined here
\\\`

This prevents functions from accidentally affecting other parts of your code.

Built-in Functions

  • print() - Display output
  • len() - Get length
  • range() - Generate sequences
  • sum() - Add numbers
  • max(), min() - Find extremes
  • type() - Check data type

Function Design Tips

1. Single responsibility: Each function should do one thing well.

2. Clear naming: calculate_total() not do_stuff()

3. Reasonable size: If a function is too long, split it.

4. Document complex functions:
\\\`python
def calculate_compound_interest(principal, rate, time, n=12):
"""
Calculate compound interest.

Args:
principal: Initial amount
rate: Annual interest rate (as decimal)
time: Time in years
n: Compounds per year (default 12)

Returns:
Final amount after interest
"""
return principal (1 + rate/n) (n time)
\\\`

From Beginner to Professional

Functions are how professional code is organized. As programs grow from hundreds to thousands to millions of lines, functions (and their relatives—classes and modules) keep complexity manageable.

Every program you use—from simple scripts to complex applications—is built from functions calling other functions.

Related Reading

Listen to the Full Course

Master programming fundamentals in Learn to Code: Programming Fundamentals.

Prefer Audio Learning?

Learn to Code: Programming Fundamentals for Beginners

Master the building blocks of programming — variables, loops, functions, and computational thinking

Listen Now
Functions: How to Write Reusable Code | Superlore - Superlore