Functions in Python

Learn how to write functions in Python.

We'll cover the following

What are functions in Python?

A function is a piece of code that only runs when it is called. Python functions return a value using a return statement if one is specified. A function can be called anywhere after it has been declared.

By itself, a function does nothing. However, when we need to use a function, we can call it, and the code within the function will be executed.

The way to write a function in Python is:

def foo(<input>):
    <do something>
    return <value>

The def input defines a function. Notice the colon (:) and the white space? Like loops and if conditions, we need to use indentation for code under the for loop.

Let’s get started with functions! We’re going to write the code for counting words from a file as a function.

This is how we wrote it before:

words = data.split(" ")
print("The words in the text are:")
print(words)
num_words = len(words)

In the code widget below, look at lines 1-4. This is how we are going to write code in a function.

It takes in the list data and returns the number of words. Keep in mind that this is the exact same code as before. The only difference is that it’s now contained in a function.

If you don’t understand what line 14 below is doing, don’t worry, we’ll go over it in the next section.

Get hands-on with 1400+ tech skills courses.