All topics
2

Data and variables: a labeled box

Free

1. The problem

You are helping a friend move. On each box you put a label that says what is inside: "kitchen," "books," "cables." Later you don't open every box. You read the label and grab the right one.

A computer keeps data the same way. To work with a number or a word, it puts the value in a box and sticks a label with a name on it.

2. The box and its label

A variable is a labeled box that holds one value. The label is a name, and you choose it. The value is what's inside.

age 30 name "Alex" isOpen true

In code this looks like age = 30. Read it as: "the box labeled age now holds 30." Later you can ask for age, and you don't have to keep the number in your head.

3. The value can change

You can put a new value in the box. Then the old one is gone:

  • age = 30 → the box holds 30
  • age = 31 → same box, now it holds 31

The label stays the same, and only what's inside changes. That is where the name variable comes from: its value can vary.

4. Your turn (no code)

Two boxes: a = 5 and b = 8. You run one step: "put into a whatever is in b." After that step, what is in a, and what is in b?

Answer: both hold 8. The step copies the value from b into a. The copy replaces what a held before, so the 5 is gone. b still holds 8, because copying takes nothing out of it.

5. Takeaway

A variable is a named box for one value. You put a value in by name, read it back by the same name, and replace it when you need to. Everything a program "remembers" sits in boxes like these.

On LeetCode

This lesson writes no code yet, so it has no LeetCode problem of its own. Every solution keeps its answer so far in a variable, and lesson 6 is where you first put one inside a function LeetCode can test.

Reading as a guest

Every free lesson is open to read and run. A free account marks lessons done and shows where you are in the course.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy