Python Functions Introduction
In this page:
def function_name():
# body
function_name()
What is a Function?
A function is a named, reusable block of code defined with the def keyword that only runs when explicitly called — bundling logic into a function means writing it once and invoking it as many times as needed instead of repeating code.
Example: What is a Function?
def greet(): # defines a reusable function named greet
print("Hello!")
greet() # first call
greet() # second call, runs the same code again
Calling a Function
Writing def greet(): only registers the function's definition with the interpreter; nothing inside its body actually executes until you separately write greet() with parentheses to call it.
Example: Calling a Function
def greet():
print("Hi there")
# Nothing runs until greet() is called
greet()
docstrings
A docstring is a string literal placed as the very first line inside a function's body, documenting what the function does; tools like help() and most IDEs display it automatically, making it far more useful than an ordinary comment.
Example: docstrings
def greet():
"""Prints a friendly greeting."""
print("Hello!")
print(greet.__doc__) # __doc__ holds the function's docstring text
Control Flow in Functions
A function body can contain the full range of Python constructs — conditionals, loops, and calls to other functions — meaning functions can be as simple as one line or coordinate substantial logic internally.
Example: Control Flow in Functions
def classify(n):
if n % 2 == 0:
return "even"
else:
return "odd"
print(classify(4)) # calls the function and prints its return value
Dynamic Execution of Functions
Because functions are first-class objects in Python, you can assign one to a variable, store several in a list, or pass one as an argument to another function — treating behavior itself as a value you can move around, not just data.
Example: Dynamic Execution of Functions
def greet():
print("Hello!")
say_hi = greet # functions are values, so greet can be assigned to another name
say_hi() # calling say_hi runs the same code as greet()
- Defining a function and never calling it, so nothing happens;
greetwithout()also just refers to the function. - Calling a function before its
defhas run, which raisesNameError. - Printing the function call result when the function only prints, e.g.
print(greet())shows an extraNone.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: