xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Arguments

Functions and modules5 min readLesson 1 of 3

Minutes: 5

Positional arguments are matched by order; keyword arguments by name.

python
def move(x, y=0):
    return (x, y)

move(3)             # (3, 0)
move(3, y=5)        # (3, 5)
move(y=5, x=3)      # (3, 5)

A default is evaluated once, when the function is defined. Never use a mutable default like []; it is shared across calls.

python
def add_item(item, bucket=None):
    bucket = [] if bucket is None else bucket
    bucket.append(item)
    return bucket

For a function that accepts anything, collect the rest:

python
def total(*numbers):
    return sum(numbers)

def tag(**labels):
    return labels

Keep functions small enough that the call site reads like a sentence.