def creates a reusable function in Python, grouping code under a name for later execution. Functions improve readability, reduce repetition, and encapsulate logic.
A def statement declares a function, followed by a name, parentheses, and a colon. The indented block beneath it contains the executable code. To call the function, use its name with parentheses.
Example:
def greet():
print("Hello, World!")
greet()
This prints "Hello, World!" when called.
Functions consist of:
def, followed by the function name and parentheses.| Type | Description | Example |
|---|---|---|
| No arguments | Performs a task without requiring input. | def greet(): |
| With arguments | Accepts inputs to customize its behavior. | def greet(name): |
| Return value | Produces an output for further use. | def add(a, b): return a + b |
Many confuse def with other keywords like return or if. Unlike conditional statements, def defines reusable blocks of code. It doesn't execute code immediately but sets up a function for later use.
Another mistake is omitting parentheses. While some languages allow defining functions without them, Python requires parentheses to enclose arguments, even if none exist.
I once wrote a function to calculate the area of a circle. The function took the radius as an argument and returned the area.
def circle_area(radius):
return 3.14159 * radius ** 2
area = circle_area(5)
print(area)
This outputs 78.53975, the area of a circle with radius 5.
For more on Python syntax, see our guide on Python for loops and the Python this keyword.