Table of Contents
Variables: The Storage Boxes of Programming
Variables are like labeled boxes where we store information that our programs can use and modify. Understanding variables is fundamental to all programming.
What is a Variable?
A variable is a named storage location that holds data. Think of it as a box with a label on it. You can put things in the box, take them out, or replace them with something else.
Variable Example
// Creating a variable named "age" and storing the value 25
age = 25
// Creating a variable named "name" and storing text
name = "Alice"
// Using variables
print("Hello, " + name + "! You are " + age + " years old.")
Common Data Types
1. Numbers
- Integers: Whole numbers like 1, 42, -17
- Decimals: Numbers with decimal points like 3.14, -0.5
2. Text (Strings)
Text data enclosed in quotes: "Hello World", "Programming is fun!"
3. Boolean (True/False)
Values that are either true or false: true, false
4. Lists/Arrays
Collections of items: [1, 2, 3, 4] or ["apple", "banana", "orange"]
Data Type Examples
// Numbers
score = 100
temperature = 98.6
// Text/String
message = "Welcome to programming!"
// Boolean
isLoggedIn = true
gameOver = false
// List
colors = ["red", "green", "blue"]
numbers = [1, 2, 3, 4, 5]
Variable Naming Rules
- Use descriptive names:
userName
instead ofx
- Start with a letter, not a number
- No spaces (use camelCase or underscores):
firstName
orfirst_name
- Avoid special characters except underscore
Why Data Types Matter
Different data types can do different things:
- Numbers can be added, subtracted, multiplied
- Strings can be combined or searched
- Booleans help make decisions in programs
- Lists can store multiple related items
🎯 Practice Exercise
Create variables for:
- Your favorite number (integer)
- Your height in feet (decimal)
- Your favorite movie (string)
- Whether you like pizza (boolean)
- Three of your hobbies (list)
Common Mistakes to Avoid
- Forgetting quotes around text:
name = Alice
❌ vsname = "Alice"
✅ - Using reserved words as variable names
- Inconsistent naming conventions