A function in Python is a reusable block of code that performs a specific task. You define it using the def keyword followed by a name, parentheses, and a colon.
The simplest function takes no arguments and returns nothing:
def greet():
print("Hello, World!")
greet()
Functions often accept inputs called parameters. These go inside the parentheses:
def greet(name):
print(f"Hello, {name}!")
Call it with an argument:
greet("Alice")
Use the return statement to send a value back to the caller:
def add(a, b):
return a + b
Store the result in a variable:
result = add(2, 3)
Many beginners forget colons after definitions or mismatched indentation. Python requires consistent whitespace.
Another error is calling a function before defining it. Python executes code top-to-bottom, so definitions must come first.
I built a temperature converter function during my first Python project. It took Celsius input and returned Fahrenheit:
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
This helped me understand how functions encapsulate logic for reuse across programs.
Good functions include docstrings - brief descriptions enclosed in triple quotes:
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
These appear when users type help(function_name) in the Python interpreter.
Variables created inside functions exist only while the function runs. This prevents naming conflicts between different functions.
Most functions should do one thing well. For complex tasks, break them into smaller helper functions.