Skip to content

Functions

Arguments

Positional Arguments

def print_at(x:int, y:int, text:str):
    ...

print_at(10, 20, "Hello World")

Keyword Arguments

def print_at(x:int, y:int, text:str):
    ...

print_at(x=10, y=20, text="Hello World")

Default Values

def print_at(x:int = 0, y:int = 0, text:str = "Hello World"):
    ...

print_at(x=10, y=20, text="Hello World")

Arbitary Arguments

def make_pizza(*toppings)):
    for topping in toppings:
        add(topping)

Preventing a function from modifying a list

Pass a copy of a list to a function like this...

do_something_destructive(my_important_list[:])

Local Functions

Can define functions within the scope of another function. e.g.

from functools import reduce

def mul(*numbers):
    def mul2(a, b):
        return a * b
    return reduce(mul2, numbers)

Lambdas

An example lambda in python...

reduce(lambda x, y : x * y)