Python Functions Introduction
In this page:
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():
print("Hello!")
greet()
greet()
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__)
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))
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
say_hi()
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: