Functions provide a way to package often-used code into reusable and easy to use components. For example, here is some code that multiplies together two lists
list1 = [2, 4, 6, 8]
list2 = [10, 20, 30, 40]
list3 = []
for x, y in zip(list1,list2):
list3.append(x * y)
list3
We don't want to keep typing out the above code every time we want to multiply the numbers in two lists. Instead, we can collect that code together into a function
def multiply(a, b):
c = []
for x,y in zip(a,b):
c.append(x*y)
return c
We can now call this function directly on our lists, e.g.
list3 = multiply(list1, list2)
list3
The function is called using its name, and passing in the values as two arguments, e.g.
list4 = multiply( [1,2,3], [4,5,6] )
list4
The arguments are placed inside the round brackets. These are copied, in order, to the function. For example, [1,2,3]
is copied into a
, and [4,5,6]
is copied as b
. The code in the function is then executed. We can watch this code being run by adding in print statements, e.g.
def multiply(a, b):
print("a = %s" % a)
print("b = %s" % b)
c = []
for x,y in zip(a,b):
print("%s times %s equals %s" % (x,y,x*y))
c.append(x*y)
print("c = %s" % c)
return c
You must pass the right number of arguments into a function. For example, this is what happens if you get the number of arguments wrong...
list5 = multiply(list1)
You can write functions that take as many (or as few) arguments as you want. For example, here is a function that takes no arguments, and then a function that takes lots
def func0():
return "no arguments to this function"
def func1(a, b, c, d, e=5):
return a+b+c+d+e
func0()
func1(1, 2, 3, 4, 5)
func1(1, 2, 3, 4)
Note that with the last function we have set a default value of the argument e
. This is given the value of 5 if it is not specified. This allows us to pass 4 arguments instead of 5. Changing the default value by editing the definition of the function above will thus change the output of func1
when it is called with only four arguments.
Here is the morse code dictionary from the last session, together with the code that converts a message from English into morse code.
letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.',
'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--',
'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
'0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
' ':'/' }
message = "SOS We have hit an iceberg and need help quickly"
morse = []
for letter in message:
morse.append( letter_to_morse[letter.lower()] )
print(morse)