Variables and Data Types in Programming
What variables and common data types are, with short Python examples.
In programming, a variable is a named place that stores a value. The value can change as the program runs.
Creating variables (Python)
age = 15
price = 4.99
name = "Sam"
is_student = True
Common data types
| Type | Meaning | Example |
|---|---|---|
Integer (int) | whole numbers | 7, -3 |
Float (float) | numbers with decimals | 3.14 |
String (str) | text | "hello" |
Boolean (bool) | true or false | True |
Operations depend on type
5 + 3gives8(integer addition)."5" + "3"gives"53"(strings are joined)."5" + 3causes an error in Python because the types do not match. Convert first:int("5") + 3gives8.
Integer and decimal division in Python
7 / 2gives3.5.7 // 2gives3(whole-number division).7 % 2gives1(remainder).
Naming
Use clear names, such as total_score, not x. In Python, names cannot start with a digit or contain spaces.
Assignment is not equality
In x = x + 1, the = means "store the result on the right in the variable on the left", not "x equals x plus one". After it runs, x is one larger.
Common mistakes
- Mixing types without converting.
- Misspelling a variable name, which creates a new one or an error.
- Treating
=as a mathematical equals sign. To compare, use==.
Quick recap
Variables store values. Each value has a type that determines what operations are allowed. Convert types when needed.