Python 3 — Functions & Reusable Code

🐍 Python 3 🟢 Lesson 10 📅 July 2026

Writing clean code means avoiding repetitions (the DRY principle: Don't Repeat Yourself). If you write the same calculation code multiple times, wrapping it inside a reusable code machine called a Function is the professional solution.

1 Defining a Function

We declare functions using the def keyword, followed by the function name, parentheses, and a colon. Code inside the function must be indented:

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

# Calling the function to execute it
say_hello()
say_hello()
2 Parameters & Return Values

To pass data into a function, put parameter variables inside the parentheses. To send results back from the function, use the return keyword:

Python 3 — Functions with return ▶ Run Code
# Parameters: num1, num2
def calculate_area(length, width):
    area = length * width
    return area # Send value back to caller

# Calling function and capturing output
result = calculate_area(5, 10)
print(f"Area: {result}") # Area: 50
3 Local vs Global Scope

Variables created inside a function belong to that function's **local scope** and cannot be read from the outside. Variables declared outside functions exist in the **global scope**:

Python 3 — Scopes ▶ Run Code
global_name = "Guido"

def scope_demo():
    local_val = 100
    print(global_name) # Can read global variables

scope_demo()
# This would crash: print(local_val)
⚠️ Return vs Print:

Beginners often confuse print() and return. Printing displays text in the output terminal panel, but doesn't pass the value back to the program. Returning passes the value back to the code, allowing you to store it or do math on it.

4 Coding Challenge

Define a function called 'celsius_to_fahrenheit' that accepts a temperature value, converts it using formula (celsius * 9/5) + 32, and returns the result. Call the function with '25' degrees and print the result.