Data types
Every value in Python has a type, which decides what you can do with it. You can add two numbers, but you cannot divide a word by three.
The main built-in types
| Type | What it holds | Example |
|---|---|---|
int | whole numbers | 42, -7, 0 |
float | numbers with a decimal point | 3.14, -0.5, 2.0 |
str | text (a string) | "hello", 'Python' |
bool | true or false | True, False |
list | an ordered, changeable collection | [1, 2, 3] |
tuple | an ordered collection that cannot change | (1, 2, 3) |
dict | key/value pairs | {"name": "Asha", "age": 21} |
set | unique items, no order | {1, 2, 3} |
NoneType | "no value" | None |
You will learn each of these in detail in later lessons.
Checking a type
The type() function tells you the type of any value:
print(type(42))
print(type(3.14))
print(type("hello"))
print(type(True))
print(type([1, 2, 3]))
print(type(None))Python works out the type for you
You never declare a type in Python. The type belongs to the value, not the variable, so the same name can refer to different types over time:
thing = 10
print(type(thing))
thing = "ten"
print(type(thing))This is called dynamic typing. It is convenient, but it means you have to keep track of what your variables hold.
Why types matter
The same operator can do different things depending on the type:
print(2 + 3) # numbers: addition
print("2" + "3") # strings: joining
print("ha" * 3) # string times int: repetitionAnd some combinations make no sense, so Python refuses:
print("Age: " + 21)TypeError: can only concatenate str (not "int") to str. The fix is to convert the number to a string first, which is the topic of the next lessons: "Age: " + str(21).