Understanding Functions
A functon is a named block of code designed to perform a specific task. By defining functions, you can execute the same code multiple times without repetition, simply by calling the function. This promotes code reusability and organization, allowing complex tasks to be broken down into manageable parts.
Defining Functions
In Python, functions are defined using the def keyword:
def display_greeting():
"""Output a basic greeting message."""
print("Welcome!")
display_greeting()
# Output:
# Welcome!
The function name, such as display_greeting(), must be followed by parentheses, wich may contain parameters. A colon (:) after the parentheses is required. The function body is indented below.
Parameters and Arguments
Parameters are variables listed in the function definition, while arguments are the actual values passed during a function call. For example:
def greet_person(person_name):
"""Print a personalized greeting."""
print(f"Hello, {person_name}!")
greet_person("Charlie")
Here, person_name is a parameter, and "Charlie" is an argument.
Positional Arguments
Arguments are matched to parameters based on their order:
def describe_preference(person, item):
"""State a person's preference for an item."""
print(f"{person.title()} likes {item}!")
describe_preference("Dana", "oranges")
# Output:
# Dana likes oranges!
Keyword Arguments
Arguments can be specified by parameter name, allowing order to be ignored:
def describe_preference(person, item):
print(f"{person.title()} likes {item}!")
describe_preference(item="oranges", person="Dana")
Default Values
Parameters can have default values, used if no argument is provided:
def describe_preference(person, item="grapes"):
print(f"{person.title()} likes {item}!")
describe_preference(person="Eve", item="cherries") # Uses provided values
describe_preference(person="Frank") # Uses default for item
describe_preference("Grace") # Uses default for item
# Output:
# Eve likes cherries!
# Frank likes grapes!
# Grace likes grapes!
Return Values
Functions can process data and return results using the return statement. Return values can be of any type, including complex structures like dictionaries:
def create_name_record(given_name, family_name):
"""Return a dictionary with name components."""
name_record = {"given": given_name, "family": family_name}
return name_record
musician = create_name_record("Jimi", "Hendrix")
print(musician)
# Output:
# {'given': 'Jimi', 'family': 'Hendrix'}
Passing Lists to Functions
Functions can accept lists as arguments to operate on multiple items:
def greet_people(people_list):
"""Greet each person in a list."""
for person in people_list:
print(f"Hello, {person.title()}!")
attendees = ["Alice", "Bob", "Charlie"]
greet_people(attendees)
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!
Handling Variable-Length Arguments
When the number of arguments is unknown, use *args to collect them into a tuple:
def collect_names(*names):
print(names)
collect_names("Dana", "Eve", "Frank")
# Output:
# ('Dana', 'Eve', 'Frank')
To arbitrary keyword arguments, use **kwargs to collect them into a dictionary:
def build_user_profile(first, last, **details):
"""Create a user profile with additional details."""
details["first_name"] = first
details["last_name"] = last
return details
profile = build_user_profile("John", "Doe", age=30, city="Boston")
print(profile)
# Output:
# {'age': 30, 'city': 'Boston', 'first_name': 'John', 'last_name': 'Doe'}
Modularizing Functions
Functions can be stored in modules (.py files) for reuse across programs. For example, save functions in utilities.py:
def process_items(pending_items, finished_items):
"""Move items from pending to finished list."""
while pending_items:
current = pending_items.pop()
print(f"Processing: {current}")
finished_items.append(current)
def display_finished(finished_items):
"""Show all completed items."""
print("Completed items:")
for item in finished_items:
print(item)
Importing Entire Modules
Import the module and use dot notation to access functions:
import utilities
pending = ["task1", "task2", "task3"]
completed = []
utilities.process_items(pending, completed)
utilities.display_finished(completed)
Importing Specific Functions
Selectively import functions to use them directly:
from utilities import process_items
process_items(pending, completed)
Using Aliases
Assign aliases to avoid naming conflicts or shorten names:
from utilities import process_items as pi
pi(pending, completed)
Importing All Functions
Import all functions from a module (use with caution to avoid conflicts):
from utilities import *
For clarity, it is generally recommended to import only needed functions or use module names with dot notation.