Python Tutorial menu

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

CategoryTypeExample
Textstr"Ayesha"
Whole numberint25
Decimal numberfloat99.5
True or falseboolTrue
Ordered listlist["pen", "book"]
Fixed listtuple(24.8, 67.0)
Unique itemsset{"red", "green"}
Key and value pairsdict{"name": "Ali", "age": 19}
NothingNoneTypeNone

Checking the Type

Use the type() function to see the type of any value:

Example

python
print(type("Hello"))
print(type(42))
print(type(3.14))
print(type(True))
print(type(None))
Output
<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

python
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))
Output
<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

python
a = str(100)
b = int("45")
c = float(7)
print(a, type(a))
print(b, type(b))
print(c, type(c))
Output
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)?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp