CodeMIRAI
0 XP

Data types

2 min read 4 runnable examples Quiz included

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

TypeWhat it holdsExample
intwhole numbers42, -7, 0
floatnumbers with a decimal point3.14, -0.5, 2.0
strtext (a string)"hello", 'Python'
booltrue or falseTrue, False
listan ordered, changeable collection[1, 2, 3]
tuplean ordered collection that cannot change(1, 2, 3)
dictkey/value pairs{"name": "Asha", "age": 21}
setunique 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:

Python
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:

Python
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:

Python
print(2 + 3)          # numbers: addition
print("2" + "3")      # strings: joining
print("ha" * 3)       # string times int: repetition

And some combinations make no sense, so Python refuses:

Python
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).

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.