Rolando Andrade
Back to Content

Variables and Data Types Explained with Pseudocode: Programming Fundamentals (4)

Learn what variables, constants and data types are, how to declare and assign them, and how a program keeps values in memory, with runnable examples.

· 8 min read
Variables and Data Types Explained with Pseudocode: Programming Fundamentals (4)

A variable is a named space in memory that holds one value, and that value can change while the program runs. Every variable has a data type. The data type says which values the variable can hold, which operations you can do with it, and how it is stored in memory. A constant is like a variable, but its value never changes.

After this lesson, you can declare variables of the five basic types, give them values, read values from the keyboard, and know when to use a constant.

In this lesson you will:

  • Declare a variable and assign it a value, then change that value.
  • Pick the right data type: Integer, Real, String, Char or Boolean.
  • Read values from the user and store them in variables.
  • Use a constant for a value that must never change.
  • Swap the values of two variables without losing one of them.

This lesson takes about 35 minutes. You only need a web browser.

Why programs need variables

A program almost never works with fixed numbers. A program that adds 3 and 4 is useless. A program that adds any two numbers the user types is useful. To do that, the program needs a place to keep each number until it uses it. That place is a variable.

The data type exists because memory is only bits. The pattern 01000001 can be the number 65 or the letter A. The data type tells the computer how to read those bits, and it tells you what you can do with the value. You can divide two numbers, but you cannot divide two names.

This matters even if an AI agent writes your code. When you review its code, many of the bugs you find are about data: a value stored in the wrong type, a variable that was never given a value, a name used before it exists. You can only see them if you know what each variable should hold.

How computers store information

The smallest unit of information is the bit. A bit can only be 0 or 1. Eight bits make a byte, for example 00000001. One byte can hold 256 different patterns (2 to the power of 8), so it can represent the numbers from 0 to 255.

Try it with the byte below. Press a bit to turn it on or off, and see how the same eight bits read as a number and as a letter.

Pattern 01000001

Read as an Integer 65

Read as a Char 'A'

Eight bits give 256 patterns, so one byte holds a number from 0 to 255.

The bits never change meaning by themselves. 01000001 is 65 when you read it as an Integer and A when you read it as a Char. The data type decides.

Bigger amounts use prefixes. A kilobit (kb) is 1000 bits and a kilobyte (kB) is 1000 bytes. A kibibit (Kibit) is 1024 bits, because some units use powers of 2. After kilo come mega, giga and tera, each one 1000 times bigger.

A variable takes some of those bytes. The bigger or more complex the value, the more bytes it needs.

What a variable has

In computer science, a variable is a space in memory with four things:

  • An address: where it lives in memory. The computer handles this for you.
  • A name: the identifier you use to refer to it, like age.
  • A value: what it holds right now, like 17.
  • A data type: what kind of value it can hold, like a whole number.
Address Name and type Value 1000 age Integer 18 17 1004 name String "Ana Torres" 1016 height Real 1.68 1024 isAdult Boolean True 1025 SPEED_OF_LIGHT Constant 299792458
Each variable is a box in memory with an address, a name, a type and a value. Assigning a new value replaces the old one. A constant's value is locked.

The five basic data types

The course uses five primitive data types. Primitive means they are basic types built into the language, not made from other types.

Type What it holds Examples Python
Integer Whole numbers, positive or negative 17, -5, 100 int
Real Numbers with decimals (also called floating point) 3.14, -0.5, 1.68 float
String Text, a sequence of characters "Hello", "Ana Torres", "123" str
Char One single character 'A', '7' str of length 1
Boolean A truth value True, False bool

Some notes from the course:

  • You can store an Integer in a Real variable. Few languages let you store a Real in an Integer, because the decimals would be lost.
  • Booleans follow the rules of Boolean logic. You will use them for decisions in Conditionals.
  • Strings can be joined, searched, split and replaced. They get their own lesson later in the series.
  • "123" in quotes is a String, not a number. It is text that only looks like a number.

Identifiers: naming things

An identifier is the name you give to a variable, a constant or a program. In StepCode, an identifier:

  • Starts with a letter or an underscore (_).
  • Has no spaces. Use firstName or first_name instead of first name.
  • Is not a keyword of the language. You cannot name a variable While or Write.

StepCode does not tell uppercase from lowercase in names, so age and Age are the same variable. Python does: in Python, age and Age are two different variables. Pick one style and keep it.

Good names save time. total tells you more than t, and isAdult tells you the variable is a Boolean before you read its type.

Declaration and assignment

Using a variable has two steps.

Declaration creates the variable. You give it a name and a type. In StepCode you write Define name As Type;. You can declare several variables of the same type in one line, separated by commas.

Assignment stores a value in the variable. In StepCode you write name <- value;. Read the arrow as “gets”: age <- 17 means “age gets 17”. In Python, assignment uses =.

Assignment replaces the old value. The old value is gone. The right side is computed first, and then the result goes into the variable on the left. That is why age <- age + 1; works: it reads the current age, adds 1, and stores the result back in age.

Variables and constants

A variable can change while the program runs. A constant cannot change, and you know its value before the program starts. The speed of light, the number of days in a week and a tax rate set by law are good constants.

In StepCode you declare a constant with Constant NAME <- value;. By convention, constant names use uppercase letters, like SPEED_OF_LIGHT. Python has no real constants, so programmers use the same uppercase convention, like PI = 3.14159, and agree not to change it.

Use a constant when a value has a meaning. price * TAX_RATE explains itself. price * 0.16 makes the reader guess what 0.16 is.

Guided practice

Each part below is a complete program. Run it, compare the output, and then change it to see what happens.

1. Declare a variable and change its value

Edit the code and press Run to try it.

You should see:

Age now: 17
Age next year: 18

Write can show several values separated by commas. It shows them one after the other, with no space between them, so the space goes inside the text: "Age now: ".

2. Use all five data types

This program fills a student card with one variable of each type. Notice that isAdult gets the result of a comparison, age >= 18, which is True or False.

Edit the code and press Run to try it.

You should see:

Name: Ana Torres
Initial: A
Age: 19
Height: 1.68 m
Adult: True

A String goes between double quotes. A Char goes between single quotes and holds exactly one character.

3. Read values from the user

Read waits for the user to type a value and stores it in a variable. The variable must already be declared, and the typed value must fit its type.

Edit the code and press Run to try it.

Run it, type Ana and then 19.

You should see:

Enter your name: 
Enter your age: 
I am Ana and I am 19 years old.

4. Use a constant

This exercise comes from the course guide, and you may remember it from the pseudocode lesson. Researchers find a particle and want to know how much energy it releases, with Einstein’s formula E = mc², where c is the speed of light, 299792458 meters per second. The speed of light never changes, so it is a constant.

Edit the code and press Run to try it.

Run it and type 0.001 (one gram).

You should see:

Enter the mass in kilograms: 
Energy released: 89875517873681.77 joules

Now try to add the line SPEED_OF_LIGHT <- 300000000; after the constant. StepCode refuses to run the program and shows:

"SPEED_OF_LIGHT" is a constant: its value cannot change.

That is the point of a constant. The language protects the value for you.

5. Swap two variables

The task: read two numbers a and b, and swap their values. A first attempt looks like this. Run it with 1 and 2.

Edit the code and press Run to try it.

You should see:

Enter A: 
Enter B: 
A is now: 2
B is now: 2

Both are 2. The line a <- b; replaced the old value of a, so when b <- a; runs, the 1 no longer exists anywhere. The fix is a third variable that keeps the old value of a before it is overwritten:

Edit the code and press Run to try it.

Run it with 1 and 2. You should see:

Enter A: 
Enter B: 
A is now: 2
B is now: 1

Step through both versions below and follow the 1.

A step by step view of swapping a = 1 and b = 2. Without a temporary variable: a <- b makes a 2 and loses the 1, then b <- a makes b 2, so both hold 2. With a temporary variable: temp <- a keeps 1, a <- b makes a 2, and b <- temp makes b 1, so the values are swapped.

b gets the 1 from temp. The swap worked: a is 2 and b is 1.

Without temp, the first line overwrites the 1 and nothing can bring it back. With temp, the 1 waits in a third box until b needs it.

This small bug teaches the most important rule of assignment: the old value is lost. Keep it in another variable first if you still need it. You will use this swap again to sort numbers in Arrays, and turn it into a Swap procedure in Procedures and functions.

Common mistakes

If you see A Real cannot be stored where a Integer is expected: use "Trunc" or "Round"., it means you tried to store a number with decimals, like 17.5, in an Integer variable. Change the variable to Real, or convert the value with Trunc (drop the decimals) or Round (round to the nearest whole number).

If you see A String cannot be stored where a Integer is expected: convert it with "ToNumber"., it means you wrote a number in quotes, like age <- "17";. Quotes make it text. Remove the quotes, or convert the text with ToNumber.

If you see "agee" is not declared. Did you mean "age"?, it means the name is misspelled. StepCode compares it with the names you declared and suggests the closest one.

If you see "age" is not declared: declare it with "Define" before using it., it means you assigned or used a variable without a Define line. Add the declaration at the top of the program.

If you see "total" has no value yet: give it one before using it. while the program runs, it means you read a variable before any assignment. For example, total <- total + 1; fails when total never got a first value. Give it a starting value, like total <- 0;, before you use it.

If you see A Char holds one single letter, and this text has 2., it means you put more than one character in a Char. Use a String instead.

Boundaries

A variable is not its value. The variable is the box. The value is what is inside right now, and it can change with every assignment.

A constant is not the same as a literal. A literal is a value written directly in the code, like 17 or "Hello". A constant is a name for a value, like SPEED_OF_LIGHT. Named constants make code easier to read and to change.

The = sign does not mean the same in every language. In StepCode, <- assigns and = compares. In Python, = assigns and == compares. Mixing them up is one of the most common beginner mistakes, and one to watch for when you translate code between languages.

The choice of type depends on the context. A phone number has digits, but you never add phone numbers, and a leading zero matters, so it is a String. The number of children is always whole, so it is an Integer.

Practice exercises

These come from the practice guide of the unit.

Exercise 1. Pick the data type. Say which type fits each item. Some depend on the context.

Name of a person; exam score; state of a door (open or closed); date of birth; phone number; gender of a person; product available in stock; number of children; postal code; approval of a request; result of a comparison.

Solution
  • Name of a person: String.
  • Exam score: Integer or Real, depending on whether the scale has decimals.
  • State of a door: Boolean (True for open, False for closed), or a String with “open” and “closed”.
  • Date of birth: String, or a special date type if the language has one.
  • Phone number: String.
  • Gender of a person: String, or a Char like 'M', 'F' or 'O'.
  • Product available in stock: Boolean, or an Integer with 0 and 1.
  • Number of children: Integer.
  • Postal code: String or Integer, depending on the country and the system.
  • Approval of a request: Boolean, or a String like “Approved” and “Not approved”.
  • Result of a comparison: Boolean.

Exercise 2. Trace the value. What is the final value of value? Trace each line on paper before you run it. The trace table in a later lesson makes this easy.

Edit the code and press Run to try it.
Solution

value is 20, then 3 to the power of 2 minus 2, which is 7, then 5, and finally 5 times 3. You should see:

value = 15

Exercise 3. Deduce the output. What does this program show?

Edit the code and press Run to try it.
Solution

The first Write shows both values with no space between them. The second puts a space in the middle. You should see:

15
1 5

The first line looks like the number fifteen, but it is a 1 followed by a 5. Small details like this one are easy to miss when you read output quickly.

What you learned

  • A variable is a space in memory with an address, a name, a value and a data type.
  • The five basic types are Integer, Real, String, Char and Boolean, and the type decides what you can store and do.
  • Define declares a variable, <- assigns a value, and Read stores what the user types.
  • A constant holds a value that never changes, and StepCode stops any attempt to change it.
  • Assignment replaces the old value, so you need a temporary variable to swap two values.

Next steps

In the next lesson, Operators and expressions, you will combine variables with arithmetic, comparison and logical operators, and learn the order in which they are computed.