Functions
intermediatePart of Core Python
Theory
Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and improve readability. Python functions are defined using the def keyword.
def function_name(parameters):
"""Optional docstring"""
# function body
return valueParameters and arguments: Parameters are the names in the function definition. Arguments are the actual values passed when calling:
- Positional arguments — matched by position
- Keyword arguments — passed using parameter names (
func(x=10, y=20)) - Default arguments — parameters with default values (
def func(x=5)) *args— captures extra positional arguments as a tuple**kwargs— captures extra keyword arguments as a dictionary
Return values: Functions use return to send a value back to the caller. A function without a return statement returns None. Multiple values can be returned as a tuple.
def add(a, b):
return a + b
result = add(3, 5) # 8Docstrings document what a function does. They are placed immediately after the function signature using triple quotes. The help() function displays docstrings.
Scope (LEGB rule): Python resolves variable names in this order:
- Local — inside the current function
- Enclosing — in enclosing functions (nested functions)
- Global — at the module level
- Built-in — Python's built-in names
The global keyword allows modifying a global variable from within a function. Use it sparingly.
Lambda functions are small, anonymous functions defined in a single expression:
square = lambda x: x ** 2
add = lambda a, b: a + bHigher-order functions take functions as arguments:
map(function, iterable)— applies function to each itemfilter(function, iterable)— keeps items where function returns Truereduce(function, iterable)— cumulatively applies function (fromfunctools)
List comprehensions provide a concise way to create lists based on existing sequences:
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]Practical Examples
Exercises
Calculator Function
Write a function called 'calculator' that takes three parameters: a, b, and operation ('add', 'subtract', 'multiply', 'divide'). Perform the requested operation and return the result. Include a docstring. Test with all four operations.
Starter Code:
def calculator(a, b, operation):\n # Your code hereExpected Output:
add(10, 5) = 15\nsubtract(10, 5) = 5\nmultiply(10, 5) = 50\ndivide(10, 5) = 2.0Variable Arguments Average
Write a function 'average' that accepts any number of numeric arguments using *args. Return the average. If no arguments are passed, return 0. Also write a lambda function that squares a number and use map() with it.
Starter Code:
def average(*args):\n # Your code hereExpected Output:
average(10, 20, 30) = 20.0\naverage(5, 15) = 10.0\naverage() = 0Comprehension and Filter Practice
Given a list of words: ['apple', 'banana', 'avocado', 'cherry', 'apricot', 'blueberry'], use a list comprehension to: 1) Create a list of words starting with 'a', 2) Create a list of word lengths for words longer than 5 letters, 3) Use filter() with a lambda to get words that contain 'berry'.
Starter Code:
words = ['apple', 'banana', 'avocado', 'cherry', 'apricot', 'blueberry']\n# Your comprehensions hereExpected Output:
A-words: ['apple', 'avocado', 'apricot']\nLong word lengths: [6, 7, 9]\nBerry words: ['blueberry']Mini Quiz
Mini Quiz
Mini Project
Mini Project: Student Grade Manager
Create a set of functions to manage student grades. The program should calculate averages, assign letter grades, and generate reports.
Requirements:
Bonus Challenge
Add a function that reads student names and scores from user input and generates a formatted report card.