Share:

Functions

intermediate

Part 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 value

Parameters 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)  # 8

Docstrings 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:

  1. Local — inside the current function
  2. Enclosing — in enclosing functions (nested functions)
  3. Global — at the module level
  4. 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 + b

Higher-order functions take functions as arguments:

  • map(function, iterable) — applies function to each item
  • filter(function, iterable) — keeps items where function returns True
  • reduce(function, iterable) — cumulatively applies function (from functools)

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

Example 1: Function Types and Parameters
python
Example 2: Lambda, Map, Filter, Comprehensions
python

Exercises

Calculator Function

easy

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 here

Expected Output:

add(10, 5) = 15\nsubtract(10, 5) = 5\nmultiply(10, 5) = 50\ndivide(10, 5) = 2.0

Variable Arguments Average

medium

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 here

Expected Output:

average(10, 20, 30) = 20.0\naverage(5, 15) = 10.0\naverage() = 0

Comprehension and Filter Practice

medium

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 here

Expected 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.