Lesson 1.3: Data and variables
A program works with data. To use it, it keeps it in variables: boxes with a name.
The idea
A variable is a box with a name where the program keeps a value.
- The name is how you find it:
age,price,name. - The value is what's inside:
30,9.99,"Ana".
To store a value you use the arrow ←:
age ← 30
It reads "age takes the value 30". Names have no spaces: totalPrice, not total price.
One box, one value
If you store another value, the old one is gone:
Algorithm Birthday
age ← 30
age ← age + 1
Write age
EndAlgorithm
31
Read the second line right to left: it works out age + 1, which is 31, and stores it in age.
Data types
Every value has a type. Three are enough to start:
| Type | Examples | What for |
|---|---|---|
| Number | 30, 9.99, -4 | Counting and calculating |
| Text | "Ana", "Hello" | Words and sentences, always in quotes |
| Boolean | True, False | Answering yes or no |
Careful: 5 is a number and "5" is text. You can add with the first; not with the second.
Operations
With numbers: +, -, * (multiply) and / (divide).
price ← 20
quantity ← 3
total ← price * quantity
Write "Total: ", total
Total: 60
Try it
Write an algorithm that asks for two numbers and writes their sum.
Show the solution
Algorithm Add
Write "First number:"
Read a
Write "Second number:"
Read b
sum ← a + b
Write "The sum is ", sum
EndAlgorithm
Summary
- A variable is a named box that keeps a value.
←stores a value and wipes the old one.- Three types to start: number, text and boolean.