This is an archived version of the course. Please see the latest version of the course.

Functions

Functions in Python are the same as in C++, except that there is no need for static typing (neither for the parameter nor for the return type).

def compute_something(x, y, z):
    a = x + 2*y
    a = z*a + 3*x
    return a

result = compute_something(5, 6, 3)
print(result)

def is a keyword to indicate a function definition.

If you do not include a return statement, the function will automatically return None.

Although you can only return one object, that object can be a sequence (e.g. tuple), so technically you can return more than one object!

def do_more(x, y):
    return (2*y, x+y)

results = do_more(1, 2)
print(type(results))

x, y = do_more(1, 2)
print(type(x))
print(type(y))