Interactive lesson · about 25 minutes
Python Variables and Data Types
Most early Python mistakes come from a wrong picture of what a variable is. This lesson gives you the right picture first, then tests it with questions you answer before you see the result.
By the end you will be able to:
- Explain what happens when you assign a value to a name.
- Name the five data types in this lesson and tell them apart.
- Predict what happens when two names point to the same list.
- Convert between types, and predict when a conversion fails.
1. A variable is a name, not a box
A common picture is a labeled box that holds a value. Python works differently. A variable is a name that points at a value. The equals sign attaches the name to the value on its right. It does not mean “is equal to.”
Predict: what does this print?
x = 5x = x + 1print(x)
2. Five data types you will use first
Every value has a type, and type(value) shows it. The table below lists the types in this lesson.
| Type | Holds | Example |
|---|---|---|
| int | Whole numbers | 42 |
| float | Numbers with a decimal point | 3.14 |
| str | Text, in quotes | "hello" |
| bool | True or False | True |
| list | An ordered collection you can change | [1, 2, 3] |
Try it: sort each value into its type.
Step 1: choose a value. Step 2: choose the type it belongs to. Each answer is checked straight away.
Values
Types
The hard one is usually "42". It looks like a number, but the quotes make it text, so you cannot add 1 to it directly. Note that True is a bool, even though Python can also treat it as 1 in arithmetic.
4. Converting between types
Python does not guess what you mean. You convert a value by calling a type name as a function: int(), float() or str(). Some conversions work, some drop information, and some fail.
| Code | Result | What happened |
|---|---|---|
| int("42") | 42 | Text of digits becomes a whole number. |
| int("4.2") | ValueError | int() does not accept a decimal point in text. |
| int(4.9) | 4 | The decimal part is cut off, not rounded. |
| float(3) | 3.0 | A whole number gains a decimal point. |
| str(3) | "3" | The number becomes text, which you can join to other text. |
Predict: what does this print?
print(int("4.2"))
Predict: what is the type of the result?
print(type(7 / 7))
5. Check yourself
Answer these before you look. If you get one wrong, go back to the section it comes from.
Question 1
a = [1]b = aa = [2]print(b)
Question 2
a = [1]b = ab.append(2)print(a)
Question 3
price = "9"print(int(price) + 1)
Keep going
Variables and data types are the first stage of the Python roadmap. The roadmap shows what to learn next, in what order, and when you are ready to apply.