def functionName(): # This is the function that is being made
print('line 1')
print('line 2')
print('line 3')
functionName() # Run the function
functionName() # Run the function again
line 1 line 2 line 3 line 1 line 2 line 3
Functions are not very useful this way because they run exactly the same each time.
To make them useful, there is a way to pass a value to them so that they can be different each time. The order of values is used to set the values.
Notice that the value 'blue' got set into the color variable similar to the equal sign.
def addClothesToDrawer(color, clothes): # The 1st value is color, 2nd value is clothes
print('Add ' + color + ' ' + clothes)
addClothesToDrawer('blue', 'socks') # The 1st value sets color, 2nd value sets clothes
addClothesToDrawer('red', 'shirt')
Add blue socks Add red shirt
Names for functions are important. Names can be very descriptive like, "ThisAddsTwoNumbersAndPrintsTheResult", but this can be hard to read in a program if every name is really long especially when functions get more complex.
def add(num1, num2):
val = num1 - num2 # THIS IS NOT AN ADD!
print(val)
add(5, 2) # This really subtracts, so it is very confusing.
3
Notice that the "return" word can send a value back to the place where the function was run or "called from".
def add(num1, num2):
val = num1 + num2
return(val)
def subtract(num1, num2):
val = num1 - num2
return(val)
print(add(5, 3)) # Run or "call" the "add" function, then print what was returned.
print(subtract(5,3))
8 2
Notice in the following code that the "val" variable is different in every function. There are different storage locations inside functions. Also notice that the returned value is named "val" inside the function, and gets set into (like the equal sign) "returnedValue" outside of the function.
def change(val):
val = 5
print('In change function:', val)
return val
val = 3
returnedValue = change(val)
print('Outside of change function:', val)
print('Outside of change function returned value:', returnedValue)
In change function: 5 Outside of change function: 3 Outside of change function returned value: 5
Lists and dictionaries are different and are shared between functions.
def change(values):
values[0] = 5
print('In change function:', values)
return values
values = [0] * 1 # Make a list with a size of 1 and filled with 0.
values[0] = 3 # The value of 3 is changed in the change function.
returnedValues = change(values)
print('Outside of change function:', values)
print('Outside of change function returned values:', returnedValues)
In change function: [5] Outside of change function: [5] Outside of change function returned values: [5]
Functions can be nested. For example, a rectangle is made from 4 lines. Each line is made from many points on the line. See the fields/graphics/6-drawRectangle.py example.
So there are many advantages of functions.