Functions are fundamental building blocks in Python, enabling code reuse, modularity, and clarity. In Python,
functions are defined using the
def
keyword, followed by the function name and parentheses. Convention states that 2 blank lines should be put
between functions to make it clearer.
def function_name():
# Function body
print("Hello, World!")
To execute the function, call it by its name followed by parentheses.
functions_name()
Parameters and Arguments
When defining functions you can add parameters, allowing you to pass data into them and then call them with
arguments.
# Define a function with parameters in parentheses
def greet(name, message):
print(f"{message}, {name}!")
# Call a function with arguments that relate to the defined parameters
greet("Adam", "Hello")
You can assign default values to parameters, making them optional during function calls.
def greet(name, message="Hi"):
print(f"{message}, {name}!")
# Output: Hi, Bob!
greet(“Bob”)
#If you provide both arguments, the default is overridden
# Output: Bye, Bob!
greet(“Bob”, “Bye”)
*args allows a function to accept any number of positional arguments, which are accessible as a tuple. **kwargs
allows a function to accept any number of keyword arguments, accessible as a dictionary.
Docstrings are string literals that appear right after the function definition, used to document the function's
purpose. These will often be showed when you hover over calling a function later, describing the purpose of the
function to the developer. You can also access a function's docstring using the
__doc__
attribute.
def add(a, b):
"""Return the sum of a and b."""
return a + b
# Output: Return the sum of a and b.
print(add.__doc__)
Returning Values
Functions can return values using the return statement and can return multiple values as a tuple. This is
important because you can assign variables to the output returned by these functions.
# Return one value
def square(x):
return x * x
# Return multiple values
def stats(numbers):
total = sum(numbers)
count = len(numbers)
return total, count
# Assigning the returned values:
total, count = stats([1, 2, 3])
Assigning Functions to Variables
In Python, functions are first-class objects and can be assigned to variables.
You can also assign built-in methods to variables.
list1 = [1, 2, 3]
pop_item = list1.pop
# Removes and returns the last item
print(pop_item())
Decorators
Decorators are functions that modify the behaviour of other functions without changing their code.
def decorator_function(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper
@decorator_function
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function call
# Hello!
# After the function call
The
@decorator_function
syntax is a shorthand for
say_hello = decorator_function(say_hello).
Built-in Functions
Python provides several built-in functions to assist with various tasks:
type() returns the type of an object.
print(type(42)) # Output: <class 'int'>
print() outputs data to the console.
print("Hello, World!")
pprint() from the pprint module provides a "pretty-print" of data structures, making them more readable. You will need to import it in your files though.
from pprint import pprint
data = {'name': Adam', 'age': 34, 'hobbies': ['hiking', 'reading']}
pprint(data)
# This will output: {'age': 30, 'hobbies': ['hiking', 'reading'], 'name': 'Adam'}
raise SystemExit
is a way to intentionally stop your Python program. It is similar to calling
exit()
or
sys.exit().
You might use it when something unrecoverable happens, or to end a script early. It can also help when
testing or debugging, allowing you to stop the script once a certain condition is met.