Table of Contents
Understanding Function Definitions
In this chapter, you’ll focus on how to define functions in Python: the exact syntax, where to put things, and what happens when Python reads a function definition.
You already know what functions are and why they matter from the parent chapter. Here, you’ll learn how to write your own.
The Basic Function Definition Syntax
A function definition in Python has this general form:
def function_name(parameters):
# function body
# do somethingLet’s break that down:
def— a keyword that tells Python you’re defining a function.function_name— the name you choose for your function.parameters— zero or more names inside parentheses, separated by commas (can be empty).:— a colon that ends the function header.- Indented block — the function body: all the code that runs when you call the function.
A very simple function with no parameters and no return yet:
def say_hello():
print("Hello!")
This code defines the function. It does not run print("Hello!") until you call:
say_hello()Function Names
Function names follow the same rules as variable names:
- Can include letters, numbers, and underscores.
- Cannot start with a number.
- No spaces.
- Case-sensitive (
greetandGreetare different).
Common style (PEP 8):
- Use all lowercase letters.
- Use underscores to separate words (snake_case).
Examples of good names:
greet_usercalculate_areashow_menu
Examples of invalid names:
2nd_function(starts with a number)my-function(contains-)print(this is actually the name of a built-in function; avoid using built-in names)
Indentation Inside Functions
The function body must be indented consistently. Everything that is part of the function goes one level in (usually 4 spaces):
def greet():
print("Hello")
print("Welcome to the program")
print("This is outside the function.")Here:
- The two
printlines inside the function are indented: they belong togreet. - The last
printis not indented: it runs immediately when the script runs, not whengreet()is called.
If you forget indentation, you’ll get an IndentationError:
def greet():
print("Hello") # ❌ wrong: not indentedWhen the Function Body Runs
Defining a function sets it up in memory. The body runs only when you call the function.
def show_message():
print("I am inside the function")
# At this point, nothing has been printed yet
show_message() # Now the function body runs
show_message() # It runs againOutput:
I am inside the function
I am inside the functionRemember:
def show_message():tells Python what to do later.show_message()actually does it.
Functions with and without Parameters (Overview Only)
The detailed meaning of parameters and arguments is in the next chapter. For now, just see how they appear in definitions.
No parameters:
def say_hi():
print("Hi!")One parameter:
def greet(name):
print("Hello,", name)Multiple parameters:
def add(a, b):
print(a + b)We’ll explore what these parameters really are and how arguments work in the next section of the course. Here, focus on recognizing them as part of the function definition syntax.
Functions That Do Nothing (Yet): `pass`
Sometimes you want to declare a function now and fill it in later. Python does not allow an empty function body, but you can use pass as a placeholder:
def todo_feature():
pass # I will implement this later
pass tells Python: “There’s no code here yet, but this is valid.”
Docstrings: Adding Basic Documentation
You can add a short description inside your function using a docstring. This is a string placed immediately after the function header:
def greet():
"""Prints a friendly greeting."""
print("Hello there!")Key points:
- The docstring goes as the very first line inside the function body.
- It’s usually written with triple quotes
""" ... """. - Tools and IDEs can show this docstring when you hover over the function or ask for help.
Another example with parameters:
def add(a, b):
"""Print the sum of a and b."""
print(a + b)Calling a Function vs Defining It
It’s important to see the difference between defining and calling.
- Definition: uses the
defkeyword and a colon.
def say_hello():
print("Hello")- Call: uses the function name followed by parentheses.
say_hello()If you only define a function and never call it, it will never run.
Example:
def example():
print("This is the example function")
# No call here, so no outputIf you add a call:
def example():
print("This is the example function")
example()Now it prints the message.
Order of Code: Define Before You Call
Python reads your file from top to bottom. A function must be defined before the first time it is called.
This is wrong:
say_hello() # ❌ NameError: function not defined yet
def say_hello():
print("Hello")This is correct:
def say_hello():
print("Hello")
say_hello() # ✅ worksSo in a script:
- Put your function definitions near the top (or in a separate file).
- Call them after they are defined.
Common Beginner Mistakes When Defining Functions
Here are some typical syntax mistakes specific to function definitions:
1. Forgetting the Colon
def greet() # ❌ missing colon
print("Hi")Correct:
def greet():
print("Hi")2. Missing Parentheses (Even with No Parameters)
def greet: # ❌ missing parentheses
print("Hi")Correct:
def greet():
print("Hi")3. Inconsistent Indentation
def greet():
print("Hi")
print("Welcome") # ❌ mixed indentationStick to one indentation style (commonly 4 spaces):
def greet():
print("Hi")
print("Welcome")4. Putting Code Before the Function Body Starts
Anything that is part of the function must be indented:
def greet():
print("Hi") # ❌ not indented, not part of the functionCorrect:
def greet():
print("Hi")Simple Practice Ideas
Here are a few ideas to practice just defining and calling functions (without worrying yet about return values or complex parameters):
- Define a function
say_name()that prints your name, then call it. - Define a function
print_line()that prints a line of dashes like----------, then call it several times. - Define a function
intro()that prints two or three lines introducing yourself, then call it once. - Define a function
blank()that does nothing for now, usingpass.
Try to:
- Use clear, descriptive function names.
- Keep your indentation consistent.
- Put definitions above where they are called.
You’ll build on this foundation in the upcoming chapters, where you’ll learn more about parameters, arguments, and return values.