Skip to content
Programming contents

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 ←:

Pseudocode
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:

Pseudocode
Algorithm Birthday
    age ← 30
    age ← age + 1
    Write age
EndAlgorithm
On screen
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:

TypeExamplesWhat for
Number30, 9.99, -4Counting and calculating
Text"Ana", "Hello"Words and sentences, always in quotes
BooleanTrue, FalseAnswering 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).

Pseudocode
price ← 20
quantity ← 3
total ← price * quantity
Write "Total: ", total
On screen
Total: 60

Try it

Exercise

Write an algorithm that asks for two numbers and writes their sum.

Show the solution
Pseudocode
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.