In [ ]:
from __future__ import print_function
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 [3]:
a = my_fun(0)
print(a)
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))
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)
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)
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]:
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")
In [14]:
a is None
Out[14]:
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)
Note that this function includes a docstring (just after the function definition). This is used by the help system
In [16]:
help(fib2)
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"))
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))
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))
In [20]:
L = fnew(1)
print(fnew(2, L=L))
Notice that the same None
that we saw previously comes into play here.
In [21]:
L
Out[21]:
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]:
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]:
In [25]:
help(filter)
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
and here we handle this
In [27]:
try:
a = 1/0
except ZeroDivisionError:
print("warning: you divided by zero")
a = 1
a
Out[27]:
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"]
In [30]:
try:
v = dict["d"]
except:
v = None
print(v)
In [ ]: