Please enable JavaScript to use CodeHS

Chapter 4

Functions and Exceptions

4.1 Functions

Functions

In this lesson, you’ll learn how to make your own functions. A function allows programmers to break up their programs into smaller parts, and make the program easier to understand.

Here is an example of a function:

def greeting():
  print("Hello!")
  print("Nice to meet you.")
Plain text

To define a function, use the keyword def, then name the function and finish up with a colon.

Below this, and indented, you will tell Python what you want this function to do. In the example above, we simply want Python to print two lines.

An important note to be aware of is that defining a function won’t do anything unless the function is called. When a function is only defined, nothing actually happens in the console. Defining a function merely teaches Python how to do something. In the example above, it teaches Python how to print a greeting.

The function must be called for Python to run the function. Each time it is called, the code in the function will be executed. Functions provide programmers with a way to save some code for later, and then use and re-use the code without having to type it out each time. Run the following example to see how this works!

Define and Call a Function

This code will print out two greeting messages.

Functions and Variables

Whenever a function is called, the code inside the function runs. You can declare variables in functions the same way that you declare variables outside of functions - using an assignment statement.

Here’s another example of a function that uses a variable.

def print_a_number():
     x = 10
     print(x)

print_a_number()
Plain text

You’ll want to be careful when using variables within functions, however. If you do this, the variable is only available within the function!

In the above example, there’s a variable called x inside print_a_number, but that doesn’t mean that there’s a variable called x outsideprint_a_number. Trying to use x after calling print_a_number causes an error.

def print_a_number():
     x = 10
     print(x)

print_a_number()
print(x + 1)
Plain text
Error: Line 6
NameError: name 'x' is not defined on line 6
Plain text

What you can do is declare a variable outside of the function. When you do this, you can still access it inside the function.

In this example, x is available in both parts of the program. This program will print the number 10 and then print the number 11.

x = 10
def print_a_number():
     print(x)

print_a_number()
print(x + 1)
Plain text

There is one more thing to be aware of concerning variables and functions. In the next example, there are TWO variables called x. One of them lives inside the function, and the other one lives outside of it.

Two Different X's

In this example, x is available in both parts of the program. This program will print the number 10 and then print the number 11.

The print function in print_a_number refers to the version of x declared just above the print. When the function is called, it will print the number 20. However, the very last print function in the program refers to the version of x declared at the beginning of the program, so it will print the number 11.

Extended Greeting

Run the program and explore with these guiding questions:

  • Add an additional print function that greets the user by name.
  • Call the function a second time.
  • Move the function to the end of the program. What happens when you try to run the program now?

Optional Challenge: Alter the program so that if the user chooses an invalid option, they are continually prompted to enter a new input. Once a valid input is given, end the program.

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    Choose the option below that correctly defines and calls the function, plant_tree().

Exercise: Weather

Write a program that will give suggested transportation based on the weather.

Ask the user for the weather outside with three options (sunny, rainy, or snowy) and give the correct footwear suggestion (bike, car, or snowmobile). Each option should be written as its own function that prints a message based on the input.

For example, if the following input was given:

What is the weather? (sunny, rainy, snowy): rainy
Plain text

The following output should be given:

On a rainy day, you should drive a car.
Plain text

Note: Be sure to print a notice if an invalid option was chosen!