Writing Functions
Let’s write and call our own functions. We’ll start with functions that do not have parameters and do not have return values. See the next section of notes for information on writing functions that include parameters.
The basic format is:
def function_name():
# write your code here
# notice that it is indented
# everything indented at this level
# is inside this function
Python will give us an error if we try to define a function that is only comments and no code though, so let’s define a function with a print()
statement in it.
# After you've run the code above, you'll have the dog() function
# definition loaded up, now we can call this function
# Calling a function that you have written is the same as calling a built
# in function—the difference is that you can play with the implementation
# TODO: run this code!
dog() # no return value, no parameters, so just function_name()
Now, the real utility of functions comes when we put multiple lines or complex code in them, then call them many times so that we don’t have to re-write all that code over and over again!