Data Types#

There are several data types in Python. To identify the data type we use the type built-in function. We would like to ask you to focus on understanding different data types very well. When it comes to programming, it is all about data types. We introduced data types at the very beginning and it comes again because every topic is related to data types. We will cover data types in more detail in their respective sections.

Checking data types#

To check the data type of certain data/variables we use the built-in type() function.

Example:

# Different python data types
# Let's declare variables with various data types

first_name = "Aurora"  # str
last_name = "Luna"  # str
country = "Indonesia"  # str
city = "Palembang"  # str
age = 6  # int

# Printing out types
print(type("Aurora"))  # str
print(type(first_name))  # str
print(type(10))  # int
print(type(3.14))  # float
print(type(1 + 1j))  # complex
print(type(True))  # bool
print(type([1, 2, 3, 4]))  # list
print(type({"name": "Aurora", "age": 6, "is_student": True}))  # dict
print(type((1, 2)))  # tuple
print(type(zip([1, 2], [3, 4])))  # set
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'zip'>

Casting data types#

Casting is a process of converting one data type to another data type. We use int(), float(), str(), list(), set(). When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with a string, the number should be first converted to a string.

Example:

# int to float
num_int = 10
print("num_int", num_int)  # 10
num_float = float(num_int)
print("num_float:", num_float)  # 10.0

# float to int
gravity = 9.81
print(int(gravity))  # 9

# int to str
num_int = 10
print(num_int)  # 10
num_str = str(num_int)
print(num_str)  # "10"

# str to int or float
num_str = "10.6"
print("num_float", float(num_str))  # 10.6
print("num_int", int(float(num_str)))  # 10

# str to list
first_name = "Aurora"
print(first_name)  # "Aurora"
first_name_to_list = list(first_name)
print(first_name_to_list)  # ['A', 'u', 'r', 'o', 'r', 'a']
num_int 10
num_float: 10.0
9
10
10
num_float 10.6
num_int 10
Aurora
['A', 'u', 'r', 'o', 'r', 'a']