Variables

Section Vocab:

  • Variable: named piece of code that stores a value

Associated Learning Outcome:

At the end of this module, students will be able to:

  • Identify variables within programs

In programming, a variable is a named storage location in memory that holds a value. This value can be changed or updated throughout the course of a program, which makes variables a powerful tool for processing and manipulating data.

One way to understand variables in programming is through the analogy of a mailbox. Imagine that you have a mailbox with a slot on top and a door on the front. The slot represents the variable name, and the door represents the variable value. When you create a variable in a program, you give it a name (i.e., the slot on top of the mailbox) and assign it a value (i.e., the contents of the mailbox).

For example, let’s say you want to write a program that calculates the average of two numbers. You might start by defining two variables called “num1” and “num2,” which hold the values of the numbers you want to average. Here’s how you might solve the problem using variables:

Introduction to the problem:

You have two numbers, let’s say 5 and 8, and you want to calculate their average.

Solving the problem using variables:

1.) Define two variables called “num1” and “num2” and assign them the values 5 and 8, respectively:

num1 = 5

num2 = 8

Optional

Copy the code above and paste it into the box to the right.

Paste it here (in the little grey box next to [ ]:)!

Press shift+enter or the little play button in the top left corner to run (execute) the program.

2.) Calculate the average of the two numbers by adding them together and dividing by 2, and assign the result to a new variable called “avg”:

avg = (num1 + num2) / 2

3.) Print the value of “avg” to the console to see the result:

print(avg)

Optional

Copy the code above and paste it into the box to the right.

Paste it here (in the little grey box next to [ ]:)!

Press shift+enter or the little play button in the top left corner to run (execute) the program.

This program uses variables to store the input values (num1 and num2) and the output value (avg) of the calculation. By using variables, we can write code that is more flexible, reusable, and easier to understand.

Watch/read the following resources and take the assessment when you are ready:

https://pythonnumericalmethods.berkeley.edu/notebooks/chapter02.01-Variables-and-Assignment.html