Python Data Types
Every value in Python has a data type: the kind of value it is. The type decides what you can do with the value. You can divide two numbers but not two names; you can make text upper case but not a number. Python has a set of built-in types that cover almost everything programs need.
The built-in types
| Kind | Type | Example |
|---|---|---|
| Whole numbers | int | 42, -7, 1_000_000 |
| Decimal numbers | float | 3.14, -0.5, 2.0 |
| Text | str | "hello", 'Python' |
| True or false | bool | True, False |
| A list of values | list | [1, 2, 3] |
| A fixed list | tuple | (10, 20) |
| Unique values | set | {"red", "green"} |
| Key and value pairs | dict | {"name": "Asha", "age": 21} |
| No value | NoneType | None |
You will meet each of these types in its own topic. For now it is enough to recognise them.
Finding a value's type
The built-in function type 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({"a": 1}))
print(type(None))<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'list'> <class 'dict'> <class 'NoneType'>
The word class appears because in Python every type is a class, and every value is an object of its class. This becomes important when you write your own classes later.
The type follows the value
A variable has no type of its own: it takes the type of the value it holds at the moment. isinstance checks whether a value is of a given type:
x = 10
print(type(x).__name__, isinstance(x, int))
x = "ten"
print(type(x).__name__, isinstance(x, int))
print(10 == 10.0, "10" == 10)int True str False True False
The last line shows why types matter: the number 10 and the float 10.0 are equal, but the text "10" is not the number 10. Text that looks like a number must be converted before you can calculate with it, as the Casting topic shows.
Practice exercises
- Print the type of
7,7.0,"7"and[7]. - Create one variable of each type in the table and print each value with its type.
- Check with
isinstancewhetherTrueis anint, and find out why the answer surprises many people. - Compare
"5" + "5"with5 + 5and explain the difference.