2 - Data Types

python
Published

April 27, 2026

Numerical types

def main() -> None:
    x = int(3)
    y = float(3.3)

# converting from float to string
z = int(float(3.3)) 
print(z)
3

FP precision problem and Decimal

The problem with floating point (FP) number is precision.

def main() -> None:
    sum = 0.1 + 0.1 + 0.1
    expected = 0.3

    print(f"sum = {sum}, expected = {expected}")
    assert sum == expected

if __name__ == "__main__":
    main()
sum = 0.30000000000000004, expected = 0.3
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[2], line 9
      5     print(f"sum = {sum}, expected = {expected}")
      6     assert sum == expected
      7 
      8 if __name__ == "__main__":
----> 9     main()

Cell In[2], line 6, in main()
      2     sum = 0.1 + 0.1 + 0.1
      3     expected = 0.3
      4 
      5     print(f"sum = {sum}, expected = {expected}")
----> 6     assert sum == expected

AssertionError: 

In this case, it’s better to use Decimal type:

from decimal import Decimal

def main() -> None:
    sum = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
    expected = Decimal('0.3')

    print(f"sum = {sum}, expected = {expected}")
    assert sum == expected

if __name__ == "__main__":
    main()
sum = 0.3, expected = 0.3

Text types

# Strings can be surrounded by either single or double quotation marks
single_quoted_string = 'Hello, World!'
double_quoted_string = "Hello, World!"

# Strings using single or double quotes interchangeably
print(single_quoted_string)
print(double_quoted_string)

# Multi-line strings using triple quotes
multi_line_string = """This is a multi-line string.
It spans multiple lines.
This is often used for documentation."""
print(multi_line_string)

# Strings behave like lists: slicing, concatenation, and searching
# Slicing
substring = single_quoted_string[0:5]
print("Sliced string:", substring)

# Concatenation
concatenated_string = single_quoted_string + " How are you?"
print("Concatenated string:", concatenated_string)

# Searching
search_result = "World" in single_quoted_string
print("Searching for 'World':", search_result)

#Reassigning string
single_quoted_string = 'Goodbye, World!'
print("Reassigned string:", single_quoted_string)

# Python treats single characters and strings of characters as the same type
single_character = 'A'
print("Type of single_character:", type(single_character))
print("Type of single_quoted_string:", type(single_quoted_string))
Hello, World!
Hello, World!
This is a multi-line string.
It spans multiple lines.
This is often used for documentation.
Sliced string: Hello
Concatenated string: Hello, World! How are you?
Searching for 'World': True
Reassigned string: Goodbye, World!
Type of single_character: <class 'str'>
Type of single_quoted_string: <class 'str'>

f-strings

# Define variables for demonstration
product_name = "Laptop"
quantity = 3
unit_price_cents = 79999  # Unit price in cents

print(f"{product_name=}, {quantity=}, {unit_price_cents=}")

# Using f-strings to create a formatted string
summary = f"Product: {product_name}, Quantity: {quantity}, Total Price: ${(quantity * unit_price_cents) / 100:.2f}"
print(summary)

# Example of using f-strings for dynamic expressions
tax_rate = 0.07  # 7% tax rate
total_cost_cents = quantity * unit_price_cents
total_cost_with_tax = total_cost_cents * (1 + tax_rate)

# Formatting the total cost with tax using f-strings
formatted_total_cost = f"Total Cost (with tax): ${total_cost_with_tax / 100:.2f}"
print(formatted_total_cost)

# Comparison without using personal details
feature = "battery life"
hours = 10

# Demonstrating use of f-strings for including variable values and expressions
feature_description = f"The {product_name} has a {feature} of up to {hours} hours."
print(feature_description)

# Type of f_strings are still strings
print(type(feature_description))
product_name='Laptop', quantity=3, unit_price_cents=79999
Product: Laptop, Quantity: 3, Total Price: $2399.97
Total Cost (with tax): $2567.97
The Laptop has a battery life of up to 10 hours.
<class 'str'>

Limited-state types

def main() -> None:
    # True acts as 1, False acts as 0
    result = True + True # Equals 2
    zero = True * False # Equals 0

    print(f"result: {result}, zero: {zero}")
    print(f"zero: {zero}")

    options = ['False option', 'True option']
    choice = options[True] # Selects 'True option'

    print(f"choice: {choice}")

    denominator = 0
    numerator = 10
    safe_division = denominator and numerator / denominator

    print(f"safe_division: {safe_division}")

    number = 10
    result = "Positive" if number >= 0 else "Negative"

    NOT = not True # False
    AND = True and False # False
    OR = True or False # True

    print(f"NOT: {NOT}, AND: {AND}, OR: {OR}")

    truthy_count = sum([True, False, True, 1 == 1, False]) # 3

    print(f"truthy_count: {truthy_count}")

    x = 5
    is_valid_range = 1 <= x <= 10
    print(f"is_valid_range: {is_valid_range}")

if __name__ == "__main__":
    main()
result: 2, zero: 0
zero: 0
choice: True option
safe_division: 0
NOT: False, AND: False, OR: True
truthy_count: 3
is_valid_range: True

Enumerator data type

from enum import Enum

class EmployeeType(Enum):
    FULL_TIME = 1
    PART_TIME = 2
    CONTRACTOR = 3

def main() -> None:
    x = int(float(3.3))
    e_type = EmployeeType.FULL_TIME
    print(e_type)
    print(e_type.value)

if __name__ == "__main__":
    main()
EmployeeType.FULL_TIME
1

Or we can use the auto function so that we do not have to hard-code the values:

from enum import Enum, auto

class EmployeeType(Enum):
    FULL_TIME = auto()
    PART_TIME = auto()
    CONTRACTOR = auto()

def main() -> None:
    x = int(float(3.3))
    e_type = EmployeeType.FULL_TIME
    print(e_type)
    print(e_type.value)

if __name__ == "__main__":
    main()
EmployeeType.FULL_TIME
1

Or we can use StrEnum so that the value is not arbitrary number but using string to be more explicit:

from enum import StrEnum, auto

class EmployeeType(StrEnum):
    FULL_TIME = auto()
    PART_TIME = "4_hour_shift" # we can manually define if we want to
    CONTRACTOR = auto()

def main() -> None:
    x = int(float(3.3))
    ft_e_type= EmployeeType.FULL_TIME
    pt_e_type = EmployeeType.PART_TIME
    print(ft_e_type.value)
    print(pt_e_type.value)

if __name__ == "__main__":
    main()
full_time
4_hour_shift