3. Variables & Data Types
Teaching your program to remember things
Your computer has two types of memory: RAM (Random Access Memory), which is fast and temporary — it forgets everything when you turn off the computer — and storage (SSD/HDD), which is slower but permanent.
When your program runs, it lives in RAM. Every value your program needs — a number, a name, a true/false flag — is stored somewhere in RAM. Variables are how you name those memory locations so you can use them.
At the deepest level, everything in a computer is binary — 1s and 0s. The number 5 is stored as 00000101. The letter 'A' is stored as 01000001. An image is millions of these bits organized in a specific pattern. Programming languages handle this translation for you.
Variables and Constants
A variable is a named container for a value. You give it a name, and you can store, change, and retrieve its value throughout your program.
A constant is a variable whose value should never change after it's set. In Python, we signal this by writing the name in ALL_CAPS — the language doesn't enforce it, but it's a strong convention:
Primitive Data Types
Primitive types are the fundamental building blocks of all data in programming. Every complex data structure is ultimately made of these.
- Integers (int): Whole numbers, positive, negative, or zero. No decimal point.score = 100 temperature = -5 year = 2025
- Floats (float): Numbers with decimal points. Used for anything requiring precision.price = 29.99 pi = 3.14159 percentage = 85.5⚠️ Watch Out
Floats are stored as approximations in binary. This means
0.1 + 0.2might give you0.30000000000000004, not exactly 0.3. For financial calculations, use thedecimalmodule in Python. - Strings (str): Text. Any sequence of characters enclosed in quotes. Strings are one of the most-used types in real programs.first_name = 'Ama' last_name = "Mensah" full_name = first_name + ' ' + last_name print(full_name) # Output: Ama Mensah
- Booleans (bool): The simplest type: either
TrueorFalse. Used in every decision your program makes.is_logged_in = True has_premium = False x = 10 print(x > 5) # True print(x == 3) # False
Type Conversion & Casting
Sometimes you need to convert one type to another. Python provides built-in functions for this:
Dynamic vs Static Typing
In Python and JavaScript, variables can hold any type — and you can even change a variable's type. This is called dynamic typing.
In languages like Java, C++, or TypeScript, you must declare what type a variable will hold — and it can only ever be that type. This is static typing. It catches bugs earlier but requires more upfront code.
Neither is universally better. Dynamic typing is faster to write and great for beginners. Static typing catches more errors and scales better in large teams. Python supports optional type hints that give you a middle ground.
Knowledge Check
Ready to test your understanding of 3. Variables & Data Types?