Defining functions
Overview
You’ve been calling functions since your first line: print(), len(), input(). Now you’ll write your own. A function is a named block of code that you define once and run whenever you need it. Functions are how programmers stay sane: they turn a long script into small, named, testable steps.
Why functions?
- Reuse — write the logic once, use it many times.
- Naming —
is_valid_email(text)explains itself; twenty lines of string checks don’t. - Fixing in one place — a bug in a function is fixed everywhere it’s used.
- Testing — small functions are easy to check (Testing with pytest).
Defining and calling
def greet(name):
print(f"Hello, {name}!")
greet("Asha") # Hello, Asha!
greet("Ben") # Hello, Ben!defstarts the definition, followed by the function’s name, parameters in brackets, and a colon.- The indented body is the code that runs.
- Defining a function doesn’t run it. The body runs each time the function is called:
greet("Asha"). - A function must be defined (its
defmust have run) before it’s called.
Parameters and arguments
The names in the definition are parameters; the values you pass in a call are arguments. Each call fills the parameters with that call’s arguments:
def rectangle_area(width, height):
return width * height
rectangle_area(3, 4) # width=3, height=4 → 12
rectangle_area(10, 2) # width=10, height=2 → 20Pass the wrong number and Python tells you:
TypeError: rectangle_area() missing 1 required positional argument: 'height'Parameters and arguments covers defaults, keyword arguments and more.
return: sending a result back
return ends the function and hands a value back to wherever it was called. The call expression becomes that value:
def rectangle_area(width, height):
return width * height
area = rectangle_area(3, 4) # area is 12
print(rectangle_area(3, 4) * 2) # 24 — use it in an expressionA function without a return (or with a bare return) returns None:
result = greet("Asha") # prints Hello, Asha!
print(result) # NoneReturn, don’t print
Beginners often write functions that print their result:
def rectangle_area(width, height):
print(width * height) # shows it... and then it's goneThat function can’t be used in a calculation, saved to a file, or tested. Return the value and let the caller decide whether to print it. Reserve printing for functions whose whole job is output, like greet.
Functions returning booleans
Functions that answer a yes/no question read nicely in if statements. Name them like questions:
def is_even(n):
return n % 2 == 0
if is_even(len(players)):
print("Teams are equal")Note return n % 2 == 0 — not if n % 2 == 0: return True else: return False. The comparison already is True or False.
Functions calling functions
Functions can use other functions — that’s how you build up bigger programs from small pieces:
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
def describe_temperature(c):
f = celsius_to_fahrenheit(c)
return f"{c}°C is {f}°F"
print(describe_temperature(20)) # 20°C is 68.0°FStructuring a program
A common layout for a script: definitions at the top, then the code that uses them — often in a main() function:
def get_total(prices):
return sum(prices)
def main():
prices = [3.5, 12.0, 7.25]
print("Total:", get_total(prices))
main()Modules and imports explains the if __name__ == "__main__": line you’ll often see around that final call.
Naming and size
- Use snake_case verbs:
calculate_total,send_email,is_valid,get_user. - Keep functions short — if it doesn’t fit on your screen, it’s probably doing several jobs.
- One job each. If you describe a function with “and” (“loads the file and calculates totals and prints a report”), split it.
Remember:
defdefines, brackets call,returngives back. Prefer returning values over printing them.
A small toolbox of functions
Write four functions and call each one to show it works. (1) greet(name) prints Hello, <name>!. (2) rectangle_area(width, height) returns the area. (3) is_even(n) returns True or False. (4) celsius_to_fahrenheit(c) returns c × 9/5 + 32. Then use them together: print the area of a 3 × 4 rectangle, whether that area is even, and convert 0, 37 and 100 °C in a loop, printing e.g. 37°C = 98.6°F.
# 1. greet(name)
# 2. rectangle_area(width, height)
# 3. is_even(n)
# 4. celsius_to_fahrenheit(c)
# Use them# 1. greet(name)
def greet(name):
print(f"Hello, {name}!")
# 2. rectangle_area(width, height)
def rectangle_area(width, height):
return width * height
# 3. is_even(n)
def is_even(n):
return n % 2 == 0
# 4. celsius_to_fahrenheit(c)
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
# Use them
greet("Asha")
area = rectangle_area(3, 4)
print("Area:", area) # 12
print("Even?", is_even(area)) # True
for c in [0, 37, 100]:
print(f"{c}°C = {celsius_to_fahrenheit(c)}°F")Summary
def name(parameters):defines a function; the indented body runs only when the function is called.- Call a function with brackets:
name(arguments); arguments fill the parameters in order. return valuesends a result back to the caller and ends the function; without it, the function returns None.- Return values rather than printing them, so the caller can decide what to do with the result.
- Good functions do one job, have a verb-like name, and are short enough to read at a glance.