Functions — reusable building blocks
Package a piece of logic under a name so you can call it from anywhere, with different inputs each time.
- Define a function with def, parameters, and a return value
- Distinguish between parameters and arguments
- Explain the difference between returning a value and printing it
Imagine writing the same calculation in four different places in your program. When you discover a bug in it, you have to find and fix it four times — and hope you do not miss one. Functions solve this by giving a name to a piece of logic that you write once and call as many times as you need.
There is a deeper reason too: functions let you give names to concepts, not just
values. A function called calculate_tax tells you what it does before you read a
single line of its body. Good functions make code read like a description of intent,
not a transcript of operations.
Defining a function with def
def greet(name):
print("Hello,", name)
greet("Ada") # Hello, Ada
greet("Grace") # Hello, Gracedefstarts the definition.greetis the function's name.nameinside the parentheses is a parameter — a local variable that will hold whatever value the caller passes in.greet("Ada")is a call;"Ada"is the argument — the actual value.
Returning a value
A function that just prints is limited — you cannot use its result in a larger
calculation. return hands a value back to the caller so it can be stored,
printed, or passed on:
def add(a, b):
return a + b
result = add(3, 4) # result is 7
print(result * 2) # 14A common beginner mistake: using print inside a function when you meant
return. A function that only prints gives back None when you try to use
its result. If you want to store or chain the result, use return.
Parameters and arguments
The terms are related but distinct:
- Parameter — the name in the function definition,
def greet(name): - Argument — the actual value passed when calling,
greet("Ada")
A function can take any number of parameters, separated by commas:
def describe(city, country, population):
return f"{city}, {country} has a population of {population:,}"
print(describe("Tokyo", "Japan", 13_960_000))Variables inside functions: scope
Variables created inside a function exist only while that function is running.
This is called scope — each function has its own private workspace that
disappears when the function returns. This means you can name a variable total
inside ten different functions without any of them interfering with each other.
def double(x):
result = x * 2 # 'result' exists only inside this function
return result
print(double(5)) # 10
print(result) # NameError: result is not defined hereExercise
Write a function celsius_to_fahrenheit(c) that converts a Celsius temperature to Fahrenheit. The formula is f = c * 9/5 + 32.
celsius_to_fahrenheit(0) → 32.0celsius_to_fahrenheit(100) → 212.0celsius_to_fahrenheit(-40) → -40.0Where to go next
Next: lists — storing multiple values together in a single collection.