Python Functions
Python functions are named blocks of reusable code. You define a function once with the def keyword and then call it as many times as you like. Functions keep programs organised, avoid repetition, and make code easier to test.
Define and Call a Function
def greet(name):
print(f"Hello, {name}!")
greet("Olivia")
greet("Usman")Hello, Olivia! Hello, Usman!
name is a parameter: a variable listed in the definition. "Olivia" is an argument: the actual value passed when calling. The body must be indented under the def line.
Return Values
return sends a value back to the caller and ends the function. A function without return gives back None. You can return several values as a tuple.
def order_total(price, qty):
subtotal = price * qty
tax = subtotal * 0.1
return subtotal, round(subtotal + tax, 2)
sub, total = order_total(12.5, 3)
print(sub, total)37.5 41.25
Default and Keyword Arguments
A parameter can have a default value, which is used when the caller leaves it out. Callers can also name arguments, so the order does not matter and the call is self-explanatory.
def make_coffee(size="medium", sugar=0, milk=True):
return f"{size} coffee, {sugar} sugar, milk={milk}"
print(make_coffee())
print(make_coffee("large", 2))
print(make_coffee(milk=False, size="small"))medium coffee, 0 sugar, milk=True large coffee, 2 sugar, milk=True small coffee, 0 sugar, milk=False
Avoid mutable defaults like def f(items=[]). The same list is shared between calls. Use items=None and create the list inside the function instead.
*args and **kwargs
*args collects any number of positional arguments into a tuple. **kwargs collects any number of keyword arguments into a dictionary.
def average(*numbers):
return sum(numbers) / len(numbers)
def profile(**details):
for key, value in details.items():
print(f"{key} = {value}")
print(average(4, 8, 6))
profile(name="Emma", city="Manchester")6.0 name = Emma city = Manchester
Type Hints and Docstrings
Type hints document which types a function expects and returns. Python does not enforce them, but editors and tools like mypy use them to catch mistakes early.
def celsius_to_f(c: float) -> float:
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_f(30))
print(celsius_to_f(-40))86.0 -40.0
Recursion
A function can call itself. Each call must move towards a base case that stops the recursion.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))120
Frequently asked questions
What is the difference between a parameter and an argument?
A parameter is the name in the function definition, like name in def greet(name). An argument is the actual value passed in the call, like greet("Ali").
Can a Python function return multiple values?
Yes. Write return a, b and Python returns a tuple, which the caller can unpack with x, y = my_function().
What are *args and **kwargs in Python?
*args gathers extra positional arguments into a tuple, and **kwargs gathers extra keyword arguments into a dictionary. The names are just conventions; the stars do the work.
What does a Python function return if there is no return statement?
It returns None automatically.