The graph paper on Wren's clipboard is a mess. Next to Row 4 he has written 42, crossed it out, written 35, and crossed that out too.
The last number, 31, is circled.
"Which one is the water level now?" Comet asks.
"The last one," Wren says. "The others were true earlier, but they are gone now."
Nova projects a glowing box labeled waterLevel. "A variable works like that circle," she says. "It holds one value at a time."
"And when a new value arrives," Comet says, "the old one is replaced."
Nova blinks. "Let's test that idea with some pseudocode."
A variable is an abstraction inside a program that can hold a value.
Each variable holds one value at a time. That value can be a list holding many values, which you will meet in week five.
Using meaningful variable names helps people read the code and understand what each value means.
In this course, variable names are whole words joined together, like waterLevel or lightLevel.
The assignment operator lets a program change the value a variable represents.
The AP Computer Science Principles reference sheet writes assignment with an arrow pointing left. Read the arrow aloud as gets.
So waterLevel ← 42 is read as: water level gets 42.
The value stored in a variable is the most recent value assigned.
waterLevel ← 42 waterLevel ← 35 waterLevel ← 31 DISPLAY(waterLevel)
Now a trickier one. Read each line in order, and keep track of both variables.
lightLevel ← 60 tempLevel ← 25 lightLevel ← tempLevel tempLevel ← lightLevel
Variables can hold different types of data. These types include numbers, Booleans, lists and strings.
A Boolean value is either true or false.
A string is an ordered sequence of characters, such as the message "The tomatoes need water".
A list is an ordered sequence of elements, such as a whole day of readings.
| Statement | True or false? |
|---|---|
| A variable holds the most recent value assigned to it. | ? |
| A variable can hold two separate numbers at the same time. | ? |
| The name x is as clear as waterLevel. | ? |
| A string is an ordered sequence of characters. | ? |
Nice tracing. Tomorrow in Beacon Lab you trace Comet's first sensor routine line by line.