Python Functions

Anonymous functions

# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)

Default Value

def add(x, y=10):
    return x + y
add(5)      # => 15
add(5, 20)  # => 25

Returning multiple

def swap(x, y):
    return y, x
x = 1
y = 2
x, y = swap(x, y)  # => x = 2, y = 1

Keyword arguments

def keyword\_args(\*\*kwargs):
    return kwargs
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness")

Positional arguments

def varargs(\*args):
    return args
varargs(1, 2, 3)  # => (1, 2, 3)

Return

def add(x, y):
    print("x is %s, y is %s" %(x, y))
    return x + y
add(5, 6)    # => 11
Comments