micheledpierri.com

  • HOME
    • Python
    • Statistics
    • Data Analysis
    • Machine Learning
  • WRITINGS
  • VISIONS
  • ABOUT
Home / Python / Functions and Code Reusability
Children dressed in lab coats are studying a python

Functions and Code Reusability

Lesson Objectives

By the end of this lesson, you will be able to:

  • Define and call functions in Python
  • Use parameters and return values correctly
  • Understand variable scope (local vs global)
  • Write reusable, testable code

This lesson is a major turning point:

functions are the foundation of real analytical and machine learning code.


1️⃣ Why Functions Matter

Without functions, code becomes:

  • repetitive
  • hard to read
  • difficult to debug
  • impossible to scale

Functions allow you to:

  • encapsulate logic
  • reuse code
  • express intent clearly

In data science, every pipeline is a composition of functions.


2️⃣ Defining a Function

Functions are defined using the def keyword.

def greet():
    print("Hello!")

This code:

  • defines a function called greet
  • does not execute it

To run it:

greet()


3️⃣ Functions with Parameters

Parameters allow functions to receive input.

def greet(name):
    print("Hello", name)

Calling the function:

greet("Michele")

Output:

Hello Michele

Parameters make functions flexible and reusable.


4️⃣ Return Values

Functions can return values using return.

def square(x):
    return x * x

Using the returned value:

result = square(4)
print(result)

Output:

16

Key rule:

return sends data back to the caller and stops the function.


5️⃣ print vs return (Critical Distinction)

def f1(x):
    print(x * 2)

def f2(x):
    return x * 2

  • f1 shows a value
  • f2 produces a value

In analytical code:

  • almost always prefer return
  • print is for debugging only

6️⃣ Multiple Parameters

Functions can accept multiple parameters.

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

add(3, 5)

Parameter order matters unless specified explicitly.


7️⃣ Variable Scope (Local vs Global)

Variables defined inside a function are local.

def test():
    x = 10
    print(x)

test()
print(x)   # ERROR

Why this matters:

  • avoids accidental overwrites
  • improves code safety

Rule:

Analytical functions should avoid global variables.


8️⃣ Functions in Data Analysis

Functions are used to:

  • preprocess data
  • compute statistics
  • transform variables
  • evaluate models

Example:

def mean(a, b):
    return (a + b) / 2

This pattern scales naturally to vectors and datasets.


9️⃣ Writing Good Functions (Best Practices)

A good function:

  • does one thing
  • has a clear name
  • returns a value
  • avoids side effects

Bad function:

def process(x):
    print(x + 1)

Better:

def increment(x):
    return x + 1


FAQ — Frequently Asked Questions

Q: Can a function return multiple values?

A: Yes, using tuples (we’ll cover this later).

Q: Can functions call other functions?

A: Yes. This is how pipelines are built.

Q: Should functions be short?

A: Yes. Long functions usually hide multiple responsibilities.

Q: Why avoid global variables?

A: They make code unpredictable and hard to debug.


Exercises

Exercise 1

Write a function that prints "Hello World".

Exercise 2

Write a function that takes a name and prints a greeting.

Exercise 3

Write a function that returns the square of a number.

Exercise 4

Write a function that adds two numbers.

Exercise 5

Store the result of a function call in a variable.

Exercise 6

Predict the output:

def f(x):
    return x + 1

print(f(2))

Exercise 7

Explain the difference between print and return.

Exercise 8

Write a function that computes the mean of two numbers.

Exercise 9

Why is this bad practice?

total = 0
def add_to_total(x):
    global total
    total += x

Exercise 10

Rewrite Exercise 9 using a proper function.


Solutions

Exercise 1

def hello():
    print("Hello World")

Exercise 2

def greet(name):
    print("Hello", name)

Exercise 3

def square(x):
    return x * x

Exercise 4

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

Exercise 5

result = square(5)

Exercise 6

# Output: 3

Exercise 7

# print shows output, return provides a value to use

Exercise 8

def mean(a, b):
    return (a + b) / 2

Exercise 9

# Uses global state, unpredictable behavior

Exercise 10

def add(x, y):
    return x + y


Next Lesson Preview

In Lesson 7, we will cover:

  • lists
  • tuples
  • sets
  • dictionaries

These data structures are the bridge between basic Python and real-world data manipulation.

Cite this article

Pierri, M. D. (2026). Functions and Code Reusability. micheledpierri.com. Permalink

Share:Email·LinkedIn
Previous← Control Flow: Conditions and LoopsNextCollections: Lists, Tuples, Sets, and Dictionaries →
Python
  1. Why Python
  2. Python & VS Code Setup (From Zero to a Professional Environment)
  3. Variables, Naming Rules, and Basic Syntax
  4. Core Data Types in Python
  5. Control Flow: Conditions and Loops
  6. Functions and Code Reusability
  7. Collections: Lists, Tuples, Sets, and Dictionaries
  8. Modules, Packages, and File Handling
  9. Errors, Exceptions, and Robust Code
  10. Object-Oriented Programming (OOP) in Python
  11. Intermediate Python: Writing Clean, Pythonic Code
  12. Python Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step)
© 2024–2026 micheledpierri.com · Privacy Policy · Impressum