Introduction
A function is a reusable block of code that performs a specific task. In Python, functions are defined using the def
keyword. They help organize code, avoid repetition, and make programs more readable.
Syntax
def function_name(parameters):
# code block
return value
function_name
is the name of the function (use lowercase and underscores)parameters
are inputs to the function (optional)- The
return
statement outputs a value (optional)
Examples
Basic Function
def greet(): return "Hello, World!"
Function with Parameters
def add(a, b): return a + b
Return Statement
def multiply(x, y): result = x * y return result
Best Practices
- Use descriptive names (e.g.,
calculate_area
instead ofca
) - Add docstrings to explain purpose:
def square(n): """Return the square of a number.""" return n ** 2
- Avoid using
return
multiple times in a single function
Further Reading
For more about Python control flow, visit our Python Control Flow Tutorial.