Data & State By the CodeCracker Team

Variables and Data Types: Storing Numbers, Text, and Booleans

Discover how programs remember information using variables, compare dynamic typing in Python with static types in C++, and avoid common pitfalls when updating or swapping values.

In This Article

  • Visualize variables as labeled storage boxes in memory that hold one value at a time.
  • Distinguish between assigning a brand-new value and incrementing an existing value.
  • Compare Python's dynamic type inference with explicit static types in C++ (int, double, string, bool).
  • Use a temporary third variable to swap two values without overwriting data.

What Is a Variable?

A program that cannot remember anything is severely limited. Imagine playing an arcade game where the screen forgets your score the instant you collect a coin, or a puzzle where the character cannot remember how many keys it has picked up. To keep track of changing information while a program runs, every programming language provides variables.

The clearest mental model for a variable is a labeled storage box inside the computer's memory. The label on the outside of the box is the variable's name (or identifier), such as player_score or has_red_key. The item placed inside the box is its current value, such as 150 or true. At any point during execution, your code can peek inside the box to read its current value, or take the old value out and replace it with a new one. Crucially, a simple variable can only hold one value at any given instant—putting a new value into the box immediately overwrites whatever was there before.

Declaring, Assigning, and Updating Variables

Working with variables involves three distinct operations that beginners sometimes blur together:

  • Declaration: Creating the variable and introducing its name to the program (and, in statically typed languages like C++, specifying what kind of data the box is allowed to hold).
  • Initialization / Assignment: Putting a specific value into the box using the assignment operator (= in Python and C++, or the set [variable] to [value] block in visual editors).
  • Updating / Mutation: Computing a new value based on the variable's existing value, such as adding 10 points to the current score.

In math class, the equals sign = is a statement of eternal balance: writing x = x + 1 in algebra is a contradiction with no solution. In programming, = is an action command, not an equation. It tells the computer: "First, evaluate the expression on the right-hand side using current memory values; second, store that final result into the variable named on the left-hand side." Because adding to or subtracting from a variable is so common, both Python and C++ provide shorthand compound assignment operators like += and -=.

Visual Block Logic

SET score TO 0
SET player_name TO "Ada"
SET is_alive TO true

CHANGE score BY 10
SET score TO score * 2

Python

score = 0
player_name = "Ada"
is_alive = True

score += 10
score = score * 2

C++

int score = 0;
std::string player_name = "Ada";
bool is_alive = true;

score += 10;
score = score * 2;
Key Idea: Read the assignment operator = aloud as "gets set to" rather than "equals." The right side is always calculated completely before the left side is updated.

Core Data Types: Numbers, Text, and Booleans

Not all data behaves the same way. Multiplying two numbers makes arithmetic sense, whereas multiplying two paragraphs of text does not. Every value stored in memory has a data type that determines how many bytes of memory it occupies and which operations are valid on it. Across visual blocks, Python, and C++, you will rely on four foundational types every day:

  1. Integers (int): Whole numbers without fractional parts, positive, negative, or zero (e.g., -12, 0, 42). Used for counting loop iterations, grid coordinates, and item inventories.
  2. Floating-Point Numbers (float in Python, double in C++): Numbers with decimal points (e.g., 3.14159, -0.5, 98.6). Used for continuous measurements like velocity, timers, and percentages.
  3. Strings (str in Python, std::string in C++): Sequences of characters enclosed in quotation marks (e.g., "Level Complete!"). Notice that "42" inside quotes is text, not an integer: concatenating "42" + "10" produces the string "4210", whereas adding the integers 42 + 10 produces 52.
  4. Booleans (bool): Logical truth values that can only ever be one of two states: True / False in Python (capitalized) or true / false in C++ (lowercase). Booleans drive every if statement and while loop condition.

Dynamic Typing (Python) vs. Static Typing (C++)

Look back at the code comparison above and notice the biggest syntactic difference between Python and C++. In Python, you simply write score = 0 without mentioning the word int. Python uses dynamic typing: the type is attached to the value itself at runtime, and a single variable name can hold an integer on one line and be reassigned to a string three lines later.

C++ uses static typing: when you declare a variable (int score = 0;), you permanently lock that variable's type at compile time. An int box can only ever hold whole numbers. If you accidentally try to assign a text string into score later in the file, the C++ compiler immediately stops and reports a type mismatch error before the program even runs. While declaring types requires slightly more typing upfront, static checking catches entire categories of bugs early and allows the compiler to generate remarkably fast machine code.

Beware of Integer Division in C++

One crucial type detail when transitioning from Python to C++ is how division (/) handles integers. In Python 3, dividing two integers with 7 / 2 automatically produces a float (3.5). In C++, if both operands are integers, 7 / 2 performs integer division and discards the fractional remainder, resulting in 3! To get a decimal result in C++, at least one operand must be a floating-point type (such as 7.0 / 2 or casting with static_cast<double>(a) / b).

The Classic Swap Puzzle and Naming Habits

Suppose variable a holds 10 and variable b holds 20, and you want to exchange their values so a becomes 20 and b becomes 10. A beginner often writes:

a = b   # a becomes 20 (the old value 10 is destroyed!)
b = a   # b gets set to a, which is already 20! Both are now 20.

Because assigning a = b overwrites the original value of a, you need a third temporary variable (temp) to hold the value safely during the exchange, just like needing an empty third glass to swap the contents of a glass of milk and a glass of juice.

Visual Block Logic

SET temp TO a
SET a TO b
SET b TO temp

Python

temp = a
a = b
b = temp
# (Or tuple unpack: a, b = b, a)

C++

int temp = a;
a = b;
b = temp;
// (Or std::swap(a, b);)

Variable Naming Rules and Readability Habits

Every programming language enforces strict rules on what characters are legal in a variable name, alongside community style conventions that keep code readable:

  • Start with a letter or underscore: Variable names can contain letters, digits, and underscores (_), but they can never start with a digit. level_2 is valid, whereas 2nd_level is a syntax error.
  • No spaces or punctuation: Spaces and hyphens are not allowed inside identifiers because the compiler interprets player-score as subtracting score from player. Use snake_case (words joined by underscores, standard in Python and C++) or camelCase (capitalizing each internal word).
  • Case sensitivity and reserved keywords: Score, score, and SCORE are three completely different variables. Also avoid language keywords like if, while, return, int, or class.
  • Choose descriptive nouns: A variable named x or temp2 tells the reader nothing about what it represents. Naming your variables remaining_lives, elapsed_seconds, and is_shield_active makes your code self-documenting and prevents unit mistakes.

Practice Exercise: Memory Trace Challenge

Trace the following sequence of statements line by line without running the code on a computer. Write down the exact value stored in coins, bonus, and total after all five lines finish executing:

int coins = 12;
int bonus = 5;
coins = coins + bonus;
bonus = coins - 3;
int total = coins + bonus * 2;

After finding the final numbers, rewrite the snippet in Python and add a boolean variable unlocked_chest that is True if total is at least 40 and False otherwise.