3. Functions#
Functions are our verbs in coding…kinda. You should think of a function as a machine that does things.
Note about thinking programmatically Consider what a washing machine does when you run it.
Locks the door.
Spins to judge the amount and balance of the clothing inside.
Adds water, a mix of cold and hot based on selected settings.
Empties the detergent tray into the water.
Agitates the clothes back and forth for some fixed time.
Drains the dirty water.
Adds fresh water to rinse.
Agitates the clothes again.
Drains the dirty water again.
Spins the clothes to remove excess water.
Unlocks the door.
Plays a tune to alert the user the load is done.
That’s a lot of steps when you break it down. If we were writing this in code and we had to do multiple loads of laundry, that would be a lot of copy-and-pasting.
Instead, we can bundle all the instructions into a function, say ‘run_load’. That way, with one line of code, we can re-use all of the instructions above. Also, if we decide to change the instructions in any way, we just change the function and those changes propogate to every use of ‘run_load’.
3.1. Anatomy of a function#
Python uses keywords and indentations to signify different tools and structures. This is called the syntax.
The syntax for a function is:
def function_name(input1 = default1, input2=default2):
commands
more commands
return output1, output2
Every function definition starts with the keyword def followed by the function name, parantheses, and a colon.
Everything else is optional. Functions need not have inputs or outputs. Functions need not have commands. But most useful functions have some of these.
Notice that everything under that first line of the function definition is indented. That is called the scope of the function, all the code that belongs to that function.
Let’s write some functions!
def area_rect(length = 1, width = 1):
area = length * width
return area
def perim_rect(length, width):
perim = 2 * (length + width)
return perim
def perim_area_rect(length, width):
return perim_rect(length, width), area_rect(length, width)
area1 = area_rect(7.3, 2.7)
perim1 = perim_rect(7.3, 2.7)
P, A = perim_area_rect(width = 7.3, length = 2.7)
print(P)
print(A)
20.0
19.71
def repeater(word, num = 2):
print(word*num)
repeater(5)
10