NotesPythonFunctions

Functions & Arguments

Defining reusable logic: parameters, defaults, *args/**kwargs, and return values.

A function is defined with def and returns None implicitly if there's no return.

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("CodeWithMunnaX"))              # Hello, CodeWithMunnaX!
print(greet("CodeWithMunnaX", "Welcome"))   # Welcome, CodeWithMunnaX!
print(greet(name="CodeWithMunnaX", greeting="Hey"))  # keyword arguments — order stops mattering

Parameters without a default (name) are required; parameters with one (greeting="Hello") are optional. Once you give one parameter a default, every parameter after it must also have one.

Variable-length arguments

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. This is how functions like print() accept any number of arguments.

def total_views(*counts, **labels):
    print("counts:", counts)   # a tuple
    print("labels:", labels)   # a dict
    return sum(counts)

result = total_views(120, 340, 500, channel="CodeWithMunnaX")
print("total:", result)

Why default mutable arguments can bite you

Never use a mutable default value like [] or {} — it's created once, when the function is defined, and shared across every call that doesn't pass its own value.

def add_video(title, playlist=[]):   # BUG: shared list across calls
    playlist.append(title)
    return playlist

print(add_video("Intro"))       # ['Intro']
print(add_video("Variables"))   # ['Intro', 'Variables'] -- 'Intro' leaked in!

Fix it with None as a sentinel and create the real default inside the function body:

def add_video(title, playlist=None):
    if playlist is None:
        playlist = []
    playlist.append(title)
    return playlist

Type hints (optional, but good practice)

Type hints don't change runtime behavior — Python doesn't enforce them — but they document intent and let editors/tools catch mistakes.

def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"
Key points to remember
  • A function with no return statement returns None.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • Never use a mutable object (list/dict) as a default argument — it's created once at definition time and shared across every call.
  • Once one parameter has a default value, every parameter after it must have one too.
  • Type hints (name: str, -> str) document intent but aren't enforced by Python at runtime.

*args, **kwargs, and the mutable-default trap

Revision Flashcards

1 / 3

Tap a card to flip it and see the answer.