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

Functions

In Python, you can define functions without being tied to a class like Java, i.e. it does not have to be a method!

Otherwise, functions in Python are defined in pretty much the same way as in Java (or Java methods to be exact), 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))