Skip to content

Module 9 · Functions — topic 2 of 19

Function definition

Writing a function with def: the header, parameters, colon, indented body, docstring and return statement, and the rule that a function must be defined before it is called.

Beginner 10 min read·Lesson 127 of 306 in Python Programming

Learning objectives

  • Write a syntactically correct function definition
  • Explain when the body of a function runs
  • Order definitions and calls correctly in a script

Definition

A function definition is a def statement that binds a name to a new function object. It consists of a header (def name(parameters):) and an indented body that runs each time the function is called.

Introduction

Defining a function is like writing a recipe card: you describe the steps once and give the recipe a name. Nothing is cooked until someone follows the recipe — in Python, until the function is called.

Why it matters

Understanding exactly what def does explains common confusions: why a function that is never called does nothing, why calling it before the def fails, and why errors inside a function only appear when it runs.

Detailed explanation

The header is def, the function name, a parameter list in parentheses (possibly empty) and a colon. The body is the indented block below it; it ends where the indentation ends.

Executing def creates a function object and stores it under the name, just like an assignment. The statements in the body are not executed at that moment.

Because def is executed top to bottom like any statement, a script must run the def before the call. Inside other functions, though, you may call functions defined later in the file, because the call happens only when the outer function runs.

An empty function body is a syntax error; use pass as a placeholder while sketching a program.

A docstring — a string literal as the first statement — documents the function and is shown by help().

Names follow the same rules as variables: snake_case, letters, digits and underscores, not starting with a digit.

Syntax

Python
def area_of_rectangle(width, height):
"""Return the area of a rectangle."""
return width * height
def todo():
pass # placeholder body
  • The colon after the header is required.
  • Use 4 spaces for the body.
  • pass does nothing but keeps the syntax valid.

Code examples

Defining and calling

Python
def area_of_rectangle(width, height):
"""Return the area of a rectangle."""
return width * height
print(area_of_rectangle(4, 2.5))
print(area_of_rectangle.__doc__)
Output
10.0
Return the area of a rectangle.

The body runs only when called

Python
def announce():
print("inside the function")
print("before the call")
announce()
print("after the call")
Output
before the call
inside the function
after the call

More examples

Order of definitions

Python
def main():
print(total_price(3, 120)) # defined below, but main() runs after both defs
def total_price(quantity, unit_price):
subtotal = quantity * unit_price
return subtotal + tax(subtotal)
def tax(amount):
return round(amount * 0.18, 2)
main()
Output
424.8

Step-by-step explanation

  • Three def statements create three function objects; nothing is printed yet.
  • main() is called on the last line, after every def has run.
  • main calls total_price, which calls tax: each call finishes and returns before the caller continues.
  • 3 × 120 = 360 plus 18% tax (64.8) gives 424.8.

Expected output

Running “Order of definitions” prints exactly:

TextOutput
424.8

Practical applications

  • Scripts usually define all functions first and then call main() at the bottom.
  • Placeholders with pass are used while designing a program's structure.

Best practices

  • Define functions before top-level code that calls them.
  • Start each function with a one-line docstring.
  • Use a main() function for the program's top-level steps.

Common mistakes

Calling before defining

Avoid

print(square(3))
def square(x):
return x * x

Prefer

def square(x):
return x * x
print(square(3))

The top-level call runs before the def statement, so the name doesn't exist yet: NameError.

Forgetting the colon or indentation

Avoid

def square(x)
return x * x

Prefer

def square(x):
return x * x

The header needs a colon and the body must be indented.

Important notes

  • A common pattern is if __name__ == "__main__": main(), which runs main only when the file is executed directly (see Modules).

Key takeaways

  • def creates a function object; the body runs only when called.
  • The header ends with a colon and the body is indented.
  • Top-level calls must come after the def they call.

Try it yourself

  1. 1
    Define perimeter(width, height) with a docstring and print help(perimeter).
  2. 2
    Sketch a program with four empty functions using pass, then fill them in one by one.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

15 questions cover the “Functions” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module