Learning

Functions Basics

Functions Basics

Defining Functions

python
# Basic syntax def greet(name): """Greet the user by name.""" # Docstring return f'Hello, {name}!' # Calling message = greet('Alice') print(message) # 'Hello, Alice!' # Function without return (returns None implicitly) def log(message): print(f'[LOG]: {message}') result = log('Started') print(result) # None

Parameters vs Arguments

python
# Parameters: variables in the definition def add(a, b): # a, b are parameters return a + b # Arguments: actual values passed total = add(5, 10) # 5, 10 are arguments

Return Statement

python
# Returns single value def square(n): return n * n # Returns multiple values (actually a tuple!) def min_max(lst): return min(lst), max(lst) result = min_max([3, 1, 4]) print(type(result)) # <class 'tuple'> print(result) # (1, 4) # Early return (guard clause) def divide(a, b): if b == 0: return None # Exit early return a / b # A function can only return ONCE per call # Code after return is UNREACHABLE def bad(): return 1 print('Never runs') # Dead code!

Docstrings

python
def calculate_area(radius): """ Calculate the area of a circle. Args: radius (float): The radius of the circle. Returns: float: The area of the circle. """ import math return math.pi * radius ** 2 # Access docstring print(calculate_area.__doc__) # help() uses docstrings # help(calculate_area)

Functions are First-Class Objects

python
# Assign to variable my_func = print my_func('Hello') # Works! # Pass as argument def execute(func, value): return func(value) result = execute(square, 5) # 25 # Return from function def get_multiplier(factor): def inner(x): return x * factor return inner double = get_multiplier(2) print(double(10)) # 20
Key Rules
  • •Functions that don't explicitly return a value return None — always check for None if needed
  • •Returning multiple values (comma-separated) actually packs them into a tuple
  • •Code after a return statement is dead code — Python will not execute it
  • •Docstrings (triple-quoted strings right after def) are the standard way to document functions
  • •Functions are first-class objects — they can be assigned to variables, passed as args, and returned
Your Task

Create a function `calculate_rectangle(length, width)` that returns a dictionary containing `'area'`, `'perimeter'`, and `'diagonal'` (use `**0.5` for square root). Include a proper multi-line docstring. Create a function `is_even(n)` that returns True/False, then use it inside `filter_evens(numbers)` to return only even numbers.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define calculate_rectangle function
Should include a docstring
Should return a dictionary
Should define is_even function
Should define filter_evens function
filter_evens should call is_even inside