Python•Functions
Python Functions (def): Arguments, *args, **kwargs & Return
Functions encapsulate code, accept positional and keyword arguments, unpack variable arguments (*args, **kwargs), and return values.
Syntax
def function_name(param1, param2=default, *args, **kwargs):
# statements
return result
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| param | Positional/Keyword | Inputs supplied to the function. |
| *args | Tuple unpack | Collects arbitrary positional arguments. |
| **kwargs | Dictionary unpack | Collects arbitrary keyword arguments. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Function Definition with Default Args & Multiple Return
def calculate_cart(items: list, tax_rate: float = 0.08, discount: float = 0.0):
"""Calculates subtotal, tax, and final amount for order."""
subtotal = sum(items)
discounted = subtotal * (1.0 - discount)
tax_amount = discounted * tax_rate
total = discounted + tax_amount
return {
"subtotal": round(subtotal, 2),
"tax": round(tax_amount, 2),
"total": round(total, 2)
}
order = calculate_cart([29.99, 49.50, 15.00], discount=0.10)
print("Order Receipt:")
print(f" Subtotal: ${order['subtotal']:.2f}")
print(f" Tax: ${order['tax']:.2f}")
print(f" Total: ${order['total']:.2f}")Expected Output:
Order Receipt: Subtotal: $94.49 Tax: $6.80 Total: $91.84
How It Works: Step-by-Step
- Lines 2-4: Defines function with default tax_rate and discount parameters.
- Lines 5-12: Computes calculations and packages results into a structured dictionary.
- Line 14: Calls function using positional items and keyword discount override.
Key Concepts
- def creates a function object and binds it to the specified name.
- Default arguments provide fallbacks when callers omit those parameters.
- Functions without an explicit return statement return None by default.
Common Mistake: Using mutable default arguments like [] or {} in function definitions
Default arguments are evaluated once at definition time, sharing the same list across all calls.
❌ Incorrect
def add_item(item, box=[]):
box.append(item)
return box✅ Correct
def add_item(item, box=None):
if box is None:
box = []
box.append(item)
return boxRelated Python Tutorials & Compiler
Python Variable Scope (LEGB Rule) and Lambda Functions
Understand how Python resolves variable names via the LEGB rule (Local, Enclosing, Global, Built-in) and anonymous lambdas.
Python Classes and Objects (OOP): __init__, Methods & self
Classes provide a means of bundling data and functionality together, creating blueprints for object instances.
Python Exception Handling: try, except, else, and finally
Exceptions in Python are handled gracefully using try...except blocks to catch runtime errors without crashing.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.