One of the many cool things about Python is the really easy way to define functions. But before we can define any functions, we first need to define “function”! A function is a grouped bit of code that does some task. The print function in the last lesson is a function that outputs stuff to the console.
If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!
Here’s how we define a function of our own:
>>> def greeting():
... print('Hello World!')
...
To define a function, we use the tag def
followed by the name of our function. The code that the function performs comes after the line with the colon (:
). All following lines must be indented by 4 spaces (if you’re using the PyCharm Console, you can press the Tab key instead).
Make sure you hit enter a couple of times until the “>>>” shows up again. The lines with “…” mean you are continuing a command on the next line, you should not type them. You’ve now defined a function! To use it, type:
>>> greeting()
Hello World!
We can also pass it an argument by adding it in the parentheses. This allows the function to get data from outside of itself:
>>> def greeting(name):
... print("Hello " + name + "!")
...
>>> greeting("Frank")
Hello Frank!
Most often you will want to have multi-line functions. At the beginning of each line after the function name, it must start with a 4 space indentation.
>>> def greeting(name):
... print("Hello " + name + "!") # Note the 4 spaces
... print("How are you today?") # 4 spaces here too!
...
>>> greeting("Frank")
Hello Frank!
How are you today?
You will often need your function to have more than one variable available from outside. You can include more by separating them with commas. Remember that order matters!
>>> def greeting(first_name, last_name):
... print("Hello " + first_name + " " + last_name + "!")
... print("How are you today?")
...
>>> greeting("Frank", "Morgan")
Hello Frank Morgan!
How are you today?
Most good functions have a return statement at the end. It does exactly that: returns what’s after the return
to whatever called it. Like so:
>>> def adder(x, y):
... new_number = x + y
... return new_number
...
>>> adder(2, 3)
5
The good thing about return statements is that they allow functions to put their result into a variable!
>>> eight = adder(3, 5)
>>> eight
8
A good function definition describes what the function does. Here’s our greeting function with a good description. We use 3 double-quotes in a row (which is just a string that can span more than one line) to describe the function.
def greeting(first_name, last_name):
"""Prints a greeting for the given first
and last name."""
print("Hello " + first_name + " " + last_name + "!")
print("How are you today?")
Now the next person to look at this function won’t be confused about what it does!