Python Functions: Write Once, Use Everywhere

INTELEVO EP 06 – Complete Tutorial for AI & Data Science

You’ve already learned variables, conditions, and loops. But here’s the problem — the moment you need the same logic twice, you copy and paste. That’s fragile code. One small change means you hunt down every copy and fix each one manually. Functions fix that entirely.

In Python, a function is a named, reusable block of code. You define it once and call it as many times as you need. It can accept inputs, perform a task, and send a result back — all in a few lines. Think of it as teaching Python a new trick it can perform on command.

More importantly, every ML library you’ll ever use — NumPy, Pandas, scikit-learn — is built on functions. When you call model.fit(X, y), you’re calling someone else’s function. Master this now, and Episode 11 (Machine Learning) won’t intimidate you.

📺 Watch the full tutorial: Intelevo EP06 on YouTube


Why Functions?

Imagine printing the square of ten different numbers. Without functions, you write ten separate lines. Now imagine the formula changes — you rewrite all ten. That’s the repetition trap, and it’s how bugs sneak in.

Consider this without functions:

print(10 * 10)
print(20 * 20)
print(30 * 30)

Now with a function:

def square(n):
    return n * n

square(10)  # 100
square(20)  # 400
square(30)  # 900

Same result. Three times fewer lines. And if the logic ever changes, you fix it in one place — not thirty.

This is the DRY principle: Don’t Repeat Yourself. Functions also make your code easier to test. Instead of testing an entire script, you test one function at a time. In data science and ML workflows, that’s not optional — it’s essential.


Function Syntax

Python function syntax is clean and readable. You need just four things: the def keyword, a name, optional parameters, and a body. Once you write a function, Python stores it in memory — and you can call it from anywhere in your program.

def function_name(parameters):
    # your logic here
    return result

Break it down:

  • def — tells Python a function is starting
  • name — use verb_noun style: calculate_area, load_data
  • parameters — inputs the function needs
  • return — sends the result back to the caller

Here’s a complete example:

def greet(name):
    message = f"Hello, {name}!"
    return message

result = greet("Alice")
print(result)  # Hello, Alice!

Notice the indentation under def — that’s the function body. Python uses indentation (not curly braces) to define where the function starts and ends. Every line inside must be indented consistently, usually by four spaces.


Parameters & Arguments

Parameters make functions flexible. Instead of hardcoding values inside a function, you pass them in at call time. This means the same function handles different inputs without any changes to its logic. Python supports three styles of passing arguments, and knowing all three makes your code significantly more expressive.

Positional — order matters

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

add(5, 10)  # 15

Keyword — order doesn’t matter

add(b=10, a=5)  # still 15

Default — fallback value

def greet(name="Guest"):
    return f"Hi {name}"

greet()         # Hi Guest
greet("Alice")  # Hi Alice

💡 ML Connection: When you write LinearRegression(fit_intercept=True) in scikit-learn, that’s a keyword argument. You’re already using this pattern — just not your own functions yet.


Return Values

A function without a return statement does its work silently — it prints, saves, or modifies something — but gives nothing back. That’s fine for side-effect tasks. However, in data science, you almost always need your function to hand back a result you can store, compare, or pass into another function. That’s exactly what return does.

# No return → None
def show(name):
    print(name)

result = show("Bob")
print(result)  # None

# Single return
def double(x):
    return x * 2

# Multiple returns
def stats(nums):
    return min(nums), max(nums)

lo, hi = stats([3, 1, 9, 5])
# lo = 1, hi = 9

Rule of thumb: if you need the result elsewhere in your code, use return.


Scope: Where Variables Live

Scope is one of the most misunderstood concepts for beginners — and one of the most important. Every variable you create has a scope: the region of your code where it exists and can be accessed. Python has two main scopes: global (outside all functions) and local (inside a function).

Variables inside a function are local — they only exist while the function runs.

x = 100  # global

def my_func():
    y = 50   # local only
    print(x)  # ✅ can read global
    print(y)  # ✅ local works fine

my_func()
print(x)  # ✅ 100
print(y)  # ❌ ERROR — y doesn't exist here

This is a feature, not a limitation. Local variables keep your functions self-contained and safe. They don’t accidentally overwrite or break variables elsewhere in your program — which matters enormously in large ML projects.


Best Practices

Writing a function that works is step one. Writing a function that’s readable, maintainable, and reusable is the real skill. These six rules separate clean code from messy code — and they apply to every Python project, from beginner scripts to ML pipelines.

  1. One job only — if it does two things, split it.
  2. Descriptive namestrain_model() beats tm() every time.
  3. DRY — spotted the same code twice? Make a function.
  4. Write docstrings — future you will thank present you.
  5. Keep it short — over ~20 lines? Break it up.
  6. Handle edge cases — what if the list is empty? What if input is zero?
def calculate_stats(numbers):
    """Return mean, max, and min of a number list."""
    if not numbers:
        return None
    return {
        "mean": sum(numbers) / len(numbers),
        "max":  max(numbers),
        "min":  min(numbers)
    }

data = [10, 20, 30, 40, 50]
print(calculate_stats(data))
# {'mean': 30.0, 'max': 50, 'min': 10}

Clean, documented, edge-case-aware. That’s production-level Python.


Your Python Roadmap to Machine Learning

Functions are your foundation. Now the toolkit expands. Each episode from here adds one essential layer — until Episode 11, where everything comes together and Machine Learning begins.

EpisodeTopic
EP 07Lists & Tuples
EP 08Dictionaries & Sets
EP 09File I/O & Modules
EP 10OOP Basics
EP 11🚀 Machine Learning begins

Every episode builds on the last. Functions are the bridge between beginner Python and professional ML code.


Quick Reference

# Define
def function_name(param1, param2="default"):
    """Docstring: what does this do?"""
    result = param1 + param2
    return result

# Call
output = function_name(10, param2=5)

# Scope reminder
x = "global"
def demo():
    y = "local"   # only lives here
    return x + y  # can access global x

Summary

Functions are the foundation of reusable, readable, professional Python. Define once. Call anywhere. Keep it clean.

Master this, and you’re ready for Episode 7 — where we tackle Lists and Tuples.
📝 All Episodes: Intelevo Tutorial Series

Leave a Comment

Your email address will not be published. Required fields are marked *