Variables and Data Types
Variables are the foundation of every program. They let you store data and refer to it by name so you can use it later.
What is a Variable?
Think of a variable as a labeled box. The label is the variable's name, and the box holds a value. You can put something in the box, look at what's inside, or replace it with something new.
Core Data Types
Every programming language has these fundamental types:
| Type | What it stores | Examples |
|------|---------------|----------|
| String | Text | "Hello", "Alice", "42" |
| Integer | Whole numbers | 1, 42, -7, 0 |
| Float/Double | Decimal numbers | 3.14, 5.7, -0.001 |
| Boolean | True or false | true, false |
Static vs Dynamic Typing
Languages differ in how strict they are about types:
- Dynamic typing (Python, JavaScript): The language figures out the type for you. You just assign a value.
- Static typing (C++, Java): You must explicitly declare what type each variable holds. This catches errors earlier.
Neither approach is better — they're different tradeoffs between flexibility and safety.
Naming Conventions
Good variable names make code readable:
- Use descriptive names:
user_agenotx - Be consistent: pick
camelCaseorsnake_caseand stick with it - Avoid single letters except for loop counters (
i,j)
Try It Yourself
In the editor, try:
- Create a variable for your favorite number and print it
- Create variables for a product name and price, then print both
- Try changing a variable's value and printing it again