A Python function bundles steps under a name so you can run them whenever you want.
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(celsius_to_fahrenheit(30)) # 86.0The anatomy#
def greet(name, greeting="Hello"):
"""Return a friendly greeting."""
return f"{greeting}, {name}!"
print(greet("Ada")) # Hello, Ada!
print(greet("Ada", "Welcome")) # Welcome, Ada!
print(greet(greeting="Hi", name="Sam")) # Hi, Sam!defstarts the definition, and the line ends in a colon- The indented block is the body
- The string on the first line is a docstring — visible via
help(greet) - Naming arguments when calling makes long calls far more readable
Return: one value or several#
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, average = stats([4, 8, 15, 16])
print(low, high, average)Python returns a tuple, and you unpack it into separate names.
A function with no return gives back None:
def show(x):
print(x)
result = show(5) # prints 5
print(result) # NoneReturning early#
return stops the function immediately. Handling awkward cases first keeps the main logic un-nested:
def divide(a, b):
if b == 0:
return None
return a / bScope#
total = 0
def add(n):
total = n # creates a new local variable
return total
add(5)
print(total) # still 0Functions can read outer variables but not reassign them without the global keyword. Avoid global — return the value and assign it at the call site instead. Code that only depends on its arguments is far easier to test.
Accepting any number of arguments#
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
def describe(**details):
for key, value in details.items():
print(f"{key}: {value}")
describe(name="Ada", age=36)*args collects extra positional arguments into a tuple; **kwargs collects named ones into a dictionary.
Lambdas#
double = lambda n: n * 2
print(double(4)) # 8
people = [{"name": "Ada", "age": 36}, {"name": "Sam", "age": 24}]
people.sort(key=lambda p: p["age"])A lambda is a one-expression function with no name. It is genuinely useful as a key= argument and rarely worth it anywhere else.
Type hints and docstrings#
def apply_discount(price: float, percent: float = 10) -> float:
"""Return the price after taking off a percentage."""
return price - (price * percent / 100)Python does not enforce the hints, but your editor uses them for autocomplete and warnings.
Questions people ask#
How long should a function be?
Short enough to fit on your screen and be described in one sentence. If the description needs an “and”, it is probably two functions.
Can functions call themselves?
Yes — that is recursion. It suits problems that break into smaller copies of themselves, like walking a folder tree. Loops are clearer for most everyday work.
What is the difference between an argument and a parameter?
A parameter is the name in the definition; an argument is the actual value you pass in. Most people use the words interchangeably.