Python Functions


So far, we've been writing all our code in one block. But writing code like this can be very impractical. For example, suppose we had to check if our users were entering numbers instead of strings. We could set up an If Statement and prompt them to enter information correctly. However, we might need to do this lots of time. Instead of writing the same error checking code over and over again, we can set up something called a function. This is a separate block of code that we can call in to action whenever we need it. Let's see how functions work.

Start a new project for this and add a Python file to it.

To set up a function, you start with the keyword def. This is needed for every function you are setting up (defining). After a space, you need to come up with a name for your function. (This can be just about anything you want, but the same rules to naming variables apply to functions.) After your function name, it needs a pair of round brackets. The round brackets are used to pass values over to your function. But they can be empty, if your function doesn't need anything passed to it. To complete the function definition, you end it with a colon. Type the following as the first line for your new function:

def error_message():

The first line of your function shouldn't be indented, but all the lines inside of your function should be.

Add a simple print statement as the next line of your function. Make sure it is indented:

def error_message():

print("Something went wrong")

Functions don't do anything until you call them into action. You do that by typing the name of your function (no need for the def keyword). You add the round brackets after the name of your function. The colon is not needed at the end.

Add this line to your code:


Don't type it immediately after the other two lines. By convention, two blank lines are added after setting up your function and the rest of your code. But here's what it should look like now:

A simple Python function

Run your code. You should see "Something went wrong" printed to the output window.

So typing the name of your function, followed by its round brackets, is enough to call that function into action.

You may be wondering if your function can go after the call. Can you do this, for example?


def error_message():

print("Something went wrong")

The answer is, no, you can't. Python executes your lines of code from top to bottom. If you call your function first, it won't know anything about a function that's further down in your code, so it will give you an error.

Functions can be as long and as complicated as you like. But they tend to do just one job. And a job that might need to be done again and again in your code. They ensure that you're not typing the same code repeatedly.

In the next lesson, you'll see how to hand values over to your functions.

Passing values to functions >