5. Python Data Types
What you will learn
- The built-in data types
- How to check and convert types
- Truthy and falsy values
- Mutable and immutable types
The main types
| Type | Example | Meaning |
|---|---|---|
str |
"Hello" |
Text |
int |
42 |
Whole number |
float |
3.14 |
Decimal number |
bool |
True, False |
Yes or no |
list |
[1, 2, 3] |
Ordered, changeable collection |
tuple |
(1, 2, 3) |
Ordered, unchangeable collection |
set |
{1, 2, 3} |
Unordered collection of unique items |
dict |
{"name": "Sam"} |
Key and value pairs |
NoneType |
None |
No value |
Lists, tuples, sets, and dictionaries each get their own lesson later.
Checking a type
Python code
values = ["Hi", 42, 3.14, True, [1, 2], (1, 2), {"a": 1}, None]
for value in values:
print(value, "is", type(value).__name__)
Output
Hi is str
42 is int
3.14 is float
True is bool
[1, 2] is list
(1, 2) is tuple
{'a': 1} is dict
None is NoneType
isinstance(value, int) returns True or False and is the usual way to test a type in a program.
Converting types
Python code
print(int("25") + 5)
print(float("3.5"))
print(str(99) + " items")
print(int(7.9))
print(bool("hello"), bool(""))
print(list("abc"))
Output
30 3.5 99 items 7 True False ['a', 'b', 'c']
int(7.9) cuts off the decimals without rounding. A conversion that cannot work raises an error:
Python code: this fails
int("abc")
What Python reports
ValueError: invalid literal for int() with base 10: 'abc'
You will learn to handle such errors in the Exceptions lesson.
Truthy and falsy
In a condition, these values count as False: False, None, 0, 0.0, "", [], (), {}, and set(). Nearly everything else counts as True.
Python code
for value in ["", "0", 0, [], [0], None, "text"]:
print(repr(value), "is", "truthy" if value else "falsy")
Output
'' is falsy '0' is truthy 0 is falsy [] is falsy [0] is truthy None is falsy 'text' is truthy
The text "0" is truthy, because it is a non-empty string.
Mutable and immutable
An immutable value cannot be changed after it is made: str, int, float, bool, and tuple. A mutable value can be changed in place: list, dict, and set.
Python code
word = "cat"
word.upper()
print(word)
word = word.upper()
print(word)
items = [1, 2]
items.append(3)
print(items)
Output
cat CAT [1, 2, 3]
The string method returned a new string, so you must store it. The list changed in place.
None
None means “no value”. Test for it with is, not ==.
Python code
result = None
if result is None:
print("No result yet")
Output
No result yet
Anything typed in with input() or read from a file arrives as a string. Convert it before doing maths.
Common mistakes
- Doing maths on text that came from
input(). - Expecting
int()to round. - Forgetting that string methods return new strings.
- Comparing to
Nonewith==. - Thinking
"0"is falsy.
Exercise
a = "10" and b = "5" are text. Print their sum as a number (15), then print the type of the result.
Show solution
a = "10"
b = "5"
total = int(a) + int(b)
print(total)
print(type(total).__name__)
Output: 15 then int
Knowledge check
1. Which function shows a value’s type?
type()
2. Is a list mutable?
Yes. A tuple is not.
3. How should you test whether a value is None?
With is None.
Summary
- Core types: str, int, float, bool, list, tuple, set, dict, and None.
- Convert with
int(),float(),str(), andbool(), and expect errors for impossible conversions. - Know the falsy values, and the difference between mutable and immutable.