How do you define and call functions in Python?
Functions are defined with the def keyword:
def function_name(parameters):
"""Docstring."""
body
return value
Key rules:
defcreates a function object and binds it to the name- Parameters are local to the function
returnsends a value back (default isNone)- Functions are first-class objects (can be assigned, passed, stored)
- Indentation defines the function body
Return behavior:
returnwith no value returnsNone- No
returnstatement returnsNone - Can return multiple values (actually returns a tuple)
returnimmediately exits the function
def name(params):
"""docstring"""
body
return value
- Functions are objects
- return None by default
- return x, y returns a tuple (x, y)
# Basic function
def greet(name):
"""Return a greeting string."""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# Function without return
def print_greeting(name):
print(f"Hello, {name}!")
result = print_greeting("Bob") # prints: Hello, Bob!
print(result) # None
# Multiple return values (tuple)
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([3, 1, 4, 1, 5])
print(f"min={lo}, max={hi}") # min=1, max=5
result = min_max([3, 1, 4])
print(type(result)) # <class 'tuple'>
# Early return
def divide(a, b):
if b == 0:
return None # early exit
return a / b
print(divide(10, 3)) # 3.333...
print(divide(10, 0)) # None
# Functions are objects
def square(x):
return x ** 2
f = square # assign function to variable
print(f(5)) # 25
print(type(square)) # <class 'function'>
# Functions can be passed as arguments
def apply(func, value):
return func(value)
print(apply(square, 4)) # 16
print(apply(len, "hello")) # 5
# Nested function definition
def outer():
def inner():
return "inner"
return inner()
print(outer()) # 'inner'
# Docstring access
print(greet.__doc__) # 'Return a greeting string.'
help(greet)
- •def creates a function object bound to a name
- •return None by default (no return or bare return)
- •Multiple return values are actually tuples
- •Functions are first-class objects (assignable, passable)
- •Docstrings are accessible via __doc__ or help()
- •def is executed at runtime, not compile time -- function is created when def runs
- •Functions without return give None -- do not use the result accidentally
- •Parameter names are local -- they do not affect variables with the same name outside
- •return immediately exits -- code after return is unreachable