In programming, as we start to write bigger and more complex programs, one thing we will start to notice is we will often have to repeat the same code in many different places.

Let’s imagine we are building an application that compares the travel time of driving, biking, and walking between two points. For any one of those modes of travel, the steps for calculating travel time might look like this:

1. Establish the distance between the two points
2. Determine the travel speed
3. Calculate time = distance / speed
4. Display the time to the user

We will need to perform these four steps for each mode of transportation. In our program, we could rewrite the same procedure over and over (and over), but there’s a better way!

Instead, we can use functions. A function is a container for code that allows us to reuse that code throughout a program. Functions save us the trouble of having to re-write code that we’ve already written!

We already have practice using functions such as print and type! Whenever we want to print something to the screen we “call” the print function by adding parentheses and providing an input value:

print("This will be printed!") --Output: This will be printed!

print is an example of a function that Lua created for us so that we can print as many times as we want in our programs. No need to recreate it ourselves!

In this lesson, we’ll learn how to create our own functions as well as how to:

  • Call functions
  • Provide inputs to functions that change their behavior
  • Return values from functions that we can use in our program
  • And much more!

Let’s get started!



Take a look at the provided code editor. It contains some code for calculating the travel time for walking, biking, and driving.

Press “Run” to see the results.


For a program this size, it isn’t such a big deal to copy and paste the same code three times. However, imagine that you had some code that you needed to copy and paste 100 times! What are some problems you might run into?

Click on the Hint to see an answer. Press “Run” to continue on.


What is an example of something you do multiple times throughout the day? What are the steps involved in doing that thing? What name would you give to that process?

Click on the Hint below to see an example. Press “Run” to continue on.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?