agyanadda@gmail.com

Python Functions

Functions and Modules 1 min read Updated Dec 4, 2026 Topic 17 of 32

A function is a named block of reusable code. Define it with def.

Parameters and return

  • def add(a, b): return a + b
  • Without return, a function returns None
  • Return several values: return x, y (a tuple)

Kinds of arguments

  • Positional: greet("Asha", 21)
  • Keyword: greet(age=21, name="Asha")
  • Default values: def greet(name, msg="Hello")
  • *args — any number of positional arguments (a tuple)
  • **kwargs — any number of keyword arguments (a dict)

⚠️ Never use a mutable default like def f(items=[]) — the same list is shared between calls. Use None and create the list inside.

Scope

Variables created inside a function are local. Read globals freely; to change one, use global (better: pass values in and return results).

Type hints

def area(w: float, h: float) -> float: — hints help editors and tools; Python does not enforce them.

Docstrings

Describe what the function does in the first line.

Example

Example — Functions with different arguments Python
def bill(*prices: float, discount: float = 0, **extra) -> float:
    """Return the total after discount, plus any extra charges."""
    total = sum(prices) * (1 - discount / 100)
    total += sum(extra.values())
    return round(total, 2)

print(bill(100, 250, 50))
print(bill(100, 250, 50, discount=10))
print(bill(500, discount=5, delivery=40, packing=10))

def add_item(item, cart=None):
    if cart is None:          # safe default
        cart = []
    cart.append(item)
    return cart

print(add_item("pen"), add_item("book"))

def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([4, 9, 1])
print(lo, hi)

Output: 400, 360.0, 525.0, ['pen'] ['book'] (each call gets its own list), 1 9

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does a function return if it has no return statement?

Exercise 2 True / False

def f(items=[]) is a safe way to give a list default.

Exercise 3 Fill in the Blank

Collect any number of keyword arguments with **___

Frequently Asked Questions

Parameters are the names in the function definition (def add(a, b)). Arguments are the actual values you pass when calling it (add(2, 3)).