In [ ]:
from __future__ import print_function

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 explictly 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


In [2]:
def my_fun(i):
    print("in the function, i = {}".format(i))
    
my_fun(10)
my_fun(5)


in the function, i = 10
in the function, i = 5

In [3]:
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.


In [4]:
global_var = 10

def print_fun(string, n):
    if n < global_var:
        print(string*n)
    else:
        print(string*global_var)

print_fun("-", 5)
print_fun("-", 20)


-----
----------

In [5]:
global_var = 100

In [6]:
print_fun("-",50)


--------------------------------------------------

By default, python will let you read from a global, but not update it.


In [8]:
outer = 1.0

def update():
    # uncomment this to allow us to access outer in the calling namespace
    global outer
    outer = -100.0
    print("in function outer = {}".format(outer))
    
update()
print("outside, outer = {}".format(outer))


in function outer = -100.0
outside, outer = -100.0

functions always return a value—if one is not explicitly given, then they return None, otherwise, they can return values (even multiple values) of any type


In [9]:
a = my_fun(10)
print(a)


in the function, i = 10
None

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


In [10]:
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.



In [12]:
def max_len(s):
    l = -1
    for w in s.split():
        if len(w) > l:
            l = len(w)
    return l

max_len("this is a test string with a random long word sasadfdfdsadaf")


Out[12]:
14

None is a special quantity in python (analogous to null in some other languages). We can test on None—the preferred manner is to use is:


In [13]:
def do_nothing():
    pass

a = do_nothing()
if a is None:
    print("we didn't do anything")


we didn't do anything

In [14]:
a is None


Out[14]:
True

More Complex Functions

Here's a more complex example. We return a pair of variables—behind the scenes in python this is done by packing them into a tuple and then unpacking on the calling end. Also note the docstring here.


In [15]:
def fib2(n): # return Fibonacci series up to n (from the python tutorial)
    """Return a list containing the Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)    # see below
        a, b = b, a+b
    return result, len(result)

fib, n = fib2(250)
print(n)
print(fib)


14
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

Note that this function includes a docstring (just after the function definition). This is used by the help system


In [16]:
help(fib2)


Help on function fib2 in module __main__:

fib2(n)
    Return a list containing the Fibonacci series up to n.

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.


In [17]:
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:


In [18]:
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.


In [ ]:


In [19]:
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]

In [20]:
L = fnew(1)
print(fnew(2, L=L))


[1, 2]

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


In [21]:
L


Out[21]:
[1, 2]

Lambdas

Lambdas are "disposible" functions. These are small, nameless functions that are often used as arguments in other functions.

Ex, from the official tutorial: we have a list of tuples. We want to sort the list based on the second item in the tuple. The sort method can take a key optional argument that tells us how to interpret the list item for sorting


In [22]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda p: p[1])

In [23]:
pairs


Out[23]:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Here we use a lambda in an extract from a list (with the filter command)


In [24]:
squares = [x**2 for x in range(100)]
sq = list(filter(lambda x : x%2 == 0 and x%3 == 0, squares))
sq


Out[24]:
[0,
 36,
 144,
 324,
 576,
 900,
 1296,
 1764,
 2304,
 2916,
 3600,
 4356,
 5184,
 6084,
 7056,
 8100,
 9216]

In [25]:
help(filter)


Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

Exceptions

Python raises exceptions when it encounters an error. The idea is that you can trap these exceptions and take an appropriate action instead of causing the code to crash. The mechanism for this is try / except. Here's an example that causes an exception, ZeroDivisionError:


In [26]:
a = 1/0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-26-43f32eee7feb> in <module>()
----> 1 a = 1/0

ZeroDivisionError: division by zero

and here we handle this


In [27]:
try:
    a = 1/0
except ZeroDivisionError:
    print("warning: you divided by zero")
    a = 1

a


warning: you divided by zero
Out[27]:
1

another example—trying to access a key that doesn't exist in a dictionary:'


In [28]:
dict = {"a":1, "b":2, "c":3}

In [29]:
v = dict["d"]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-29-6cf437493b9d> in <module>()
----> 1 v = dict["d"]

KeyError: 'd'

In [30]:
try:
    v = dict["d"]
except:
    v = None

print(v)


None

In [ ]: