Functions


Collapse Content

# Use "def" to create new functions
def add(x, y):
    print("x is %s and y is %s" % (x, y))
    return x + y    # Return values with a return statement

# Calling functions with parameters
add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11

# Another way to call functions is with keyword arguments
add(y=6, x=5)   # Keyword arguments can arrive in any order.

# You can define functions that take a variable number of positional arguments
def varargs(*args):
    return args

varargs(1, 2, 3) #=> (1,2,3)


# You can also define functions that take a variable number of keyword arguments
def keyword_args(**kwargs):
    return kwargs

# Let's call it to see what happens
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}

# You can do both at once, if you like
def all_the_args(*args, **kwargs):
    print(args)
    print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

# When calling functions, you can do the opposite of args/kwargs!
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)

Advanced Functional Stuff


# Python has first class functions (Like Javascript)
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
add_10(3) #=> 13

# There are also anonymous functions
(lambda x: x > 2)(3) #=> True

# There are built-in higher order functions
map(add_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]

# We can use list comprehensions for nice maps and filters
[add_10(i) for i in [1, 2, 3]]  #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]

Challenge

The following function sums the even numbers of its parameters:

def sumEven(*vars):
    sum = 0
    for n in vars:
        if n%2==0:
            sum += n 
    return sum

For example, sumEven(2,3,4) would return 6.

You have a tuple named tup. Write one line of code (13 characters) that passes tup to sumEven() so it returns the sum of it's even numbers.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

The function makeMultiplier, takes in one parameter, x. Fill in the function body so it returns a function that takes in one parameter y and returns the product of x and y.

For example, calling makeMultiplier(3) should return a function that returns 3*y, while calling makeMultiplierr(10) should return a function that returns 10*y.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]