{ Functions Basics. }



By the end of this chapter, you should be able to:

  • Explain the value and purpose of a function
  • Understand how to return output from functions

What is a function?

A function is a repeatable process or procedure. A real world analogy of a function is the brew button on a coffee machine. The coffee machine has inputs (hot water, coffee grounds), and outputs (hot coffee). When you press the button to brew a pot of coffee, you are starting a process that should return an expected output to you. The same thing is true in programming. A function takes a set of variables as inputs and returns a value as an output.

We have already seen many functions in action. For example, in the list chapter, we learned about append and many others. These are built-in functions that operate on a list. But in addition to built in-functions, we can also write our own functions! In Python, a function has the following format:

def function_name():
    # code gets indented here

Notice that we MUST indent on the following line. If you do not indent your code, you'll get an IndentationError! To invoke a function, use the ():

def first_function():
  print("Hello World!")

first_function() # Hello World!

Next, let's try to write a function called add_five_plus_five which outputs the sum of 5 + 5. Here's what that might look like:

def add_five_plus_five():
    5 + 5

Now let's run this function add_five_plus_five() and our output is....nothing! Why is that? We are missing a very important keyword: return.

In order to output values from a function, we need to use the return keyword. Let's see how we can fix our function now.

def add_five_plus_five():
    return 5 + 5

Now let's run this function add_five_plus_five() and our output is....10! If we would like, we can also save this information to a variable and use it at a later point in time like this:

ten = add_five_plus_five()
print(ten + 10) # 20

If we don't have a return statement in our function, it will always return None to us. This is true regardless of what else happens in the function. Take a look at this example:

def print_five_plus_five():
    print(5 + 5)

def add_five_plus_five():
    return 5 + 5

ten = add_five_plus_five()
maybe_ten = print_five_plus_five() # this line should print 10 to the console

ten # 10
maybe_ten # None

In the real world, we'd never really write functions like these because they are very rigid; all they do is add 5 and 5. Ideally, we'd like to be able to provide some input to our functions, but in order to do that we need to introduce a concept called parameters or arguments.

When you're ready, move on to Function Parameters


Creative Commons License