Functions

Functions#

Functions are used to organize program flow, especially to allow us to easily do commonly needed tasks over and over again. We’ve already used a lot of functions, such as those that work on lists (append() and pop()) or strings (like replace()). Here we see how to write our own functions

A function takes arguments, listed in the () and returns a value. Even if you don’t explicitly give a return value, one will be return (e.g., None).

Here’s a simple example of a function that takes a single argument, i

def my_fun(i):
    print(f"in the function, i = {i}")
    
my_fun(10)
my_fun(5)
in the function, i = 10
in the function, i = 5
a = my_fun(0)
print(a)
in the function, i = 0
None

functions are one place where scope comes into play. A function has its own namespace. If a variable is not defined in that function, then it will look to the namespace from where it was called to see if that variable exists there.

However, you should avoid this as much as possible (variables that persist across namespaces are called global variables).

We already saw one instance of namespaces when we imported from the math module.

Here’s a simple function that takes two numbers and returns their product.

def multiply(a, b):
    return a*b

c = multiply(3, 4)
print(c)
12

Quick Exercise:

Write a simple function that takes a sentence (as a string) and returns an integer equal to the length of the longest word in the sentence. The len() function and the .split() methods will be useful here.

Keyword Arguments#

You can have optional arguments which provide defaults. Here’s a simple function that validates an answer, with an optional argument that can provide the correct answer.

def check_answer(val, correct_answer="a"):
    if val == correct_answer:
        return True
    else:
        return False

print(check_answer("a"))
print(check_answer("a", correct_answer="b"))
True
False

it is important to note that python evaluates the optional arguments once—when the function is defined. This means that if you make the default an empty object, for instance, it will persist across all calls.

This leads to one of the most common errors for beginners

Here’s an example of trying to initialize to an empty list:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
[1]
[1, 2]
[1, 2, 3]

Notice that each call does not create its own separate list. Instead a single empty list was created when the function was first processed, and this list persists in memory as the default value for the optional argument L.

If we want a unique list created each time (e.g., a separate place in memory), we instead initialize the argument’s value to None and then check its actual value and create an empty list in the function body itself if the default value was unchanged.

def fnew(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

print(fnew(1))
print(fnew(2))
print(fnew(3))
[1]
[2]
[3]
L = fnew(1)
print(fnew(2, L=L))
[1, 2]

Notice that the same None that we saw previously comes into play here.