Python:Python Functions (def): Arguments, *args, **kwargs & Return
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:

ParameterTypeDescription
paramPositional/KeywordInputs supplied to the function.
*argsTuple unpackCollects arbitrary positional arguments.
**kwargsDictionary unpackCollects arbitrary keyword arguments.

Ready-to-Run Code Example

Executable in Compilra

Run 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 box

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler