Python Data Types
Every value in Python has a data type, and the type decides what you can do with it.
Why Data Types Matter
You can add two numbers, but you cannot divide a name by 3. Python needs to know what kind of value it is working with. That kind is the data type.
The Main Built-in Types
| Category | Type | Example |
|---|---|---|
| Text | str | "Ayesha" |
| Whole number | int | 25 |
| Decimal number | float | 99.5 |
| True or false | bool | True |
| Ordered list | list | ["pen", "book"] |
| Fixed list | tuple | (24.8, 67.0) |
| Unique items | set | {"red", "green"} |
| Key and value pairs | dict | {"name": "Ali", "age": 19} |
| Nothing | NoneType | None |
Checking the Type
Use the type() function to see the type of any value:
Example
print(type("Hello"))
print(type(42))
print(type(3.14))
print(type(True))
print(type(None))<class 'str'> <class 'int'> <class 'float'> <class 'bool'> <class 'NoneType'>
Python Chooses the Type for You
You do not write the type when you create a variable. Python looks at the value and decides:
Example
city = "Karachi"
population = 20000000
rain_mm = 12.5
is_coastal = True
subjects = ["Maths", "English", "Computer"]
marks = {"Maths": 88, "English": 79}
print(type(city))
print(type(population))
print(type(rain_mm))
print(type(is_coastal))
print(type(subjects))
print(type(marks))<class 'str'> <class 'int'> <class 'float'> <class 'bool'> <class 'list'> <class 'dict'>
Quotes make all the difference. 25 is an int, but "25" is a str. You cannot do maths with "25" until you convert it.
Setting a Type on Purpose
Sometimes you want a specific type. Use the type name like a function:
Example
a = str(100)
b = int("45")
c = float(7)
print(a, type(a))
print(b, type(b))
print(c, type(c))100 <class 'str'> 45 <class 'int'> 7.0 <class 'float'>
This is called casting. The next lesson explains it in more detail.
Mutable and Immutable
Some types can be changed after they are created. Others cannot.
- Mutable (can change):
list,set,dict - Immutable (cannot change):
str,int,float,bool,tuple
You will see why this matters in the lessons on lists and tuples.
Exercise
Exercise
What is the data type of the value "3.5" (with quotes)?
