Explore Integer and Boolean Types
In this step, we will explore the integer (int) and boolean (bool) data types in Python. Integers are whole numbers, such as 10, -5, or 0. Booleans represent one of two values: True or False, and are a subtype of integers.
An important concept in Python is immutability. Number types are immutable, which means that once a number object is created, its value cannot be changed. If you reassign a variable to a new number, it will point to a new object in memory. We can verify this using the built-in id() function, which returns an object's unique memory address, and the type() function, which shows its data type.
The lab environment has already created a file for you. In the WebIDE file explorer on the left, open the ~/project/number_types.py file. Add the following code to it:
## Demonstrate immutability of integers
a = 5
print(f"Initial value of a: {a}")
print(f"Type of a: {type(a)}")
print(f"ID of a: {id(a)}")
## Reassign 'a' to a new value
a = 6
print(f"\nNew value of a: {a}")
print(f"New ID of a: {id(a)}")
## Demonstrate boolean type
print("\n--- Boolean Types ---")
is_true = True
is_false = False
print(f"Value of is_true: {is_true}, Type: {type(is_true)}")
print(f"Value of is_false: {is_false}, Type: {type(is_false)}")
## Booleans behave like integers (1 and 0) in arithmetic
print(f"\nTrue + 5: {True + 5}")
print(f"False * 3: {False * 3}")
After adding the code, save the file. To run the script, open the integrated terminal in the WebIDE and execute the following command:
python ~/project/number_types.py
You should see output similar to the following. Note that the memory addresses (ID) will be different on your system.
Initial value of a: 5
Type of a: <class 'int'>
ID of a: <memory_address_1>
New value of a: 6
New ID of a: <memory_address_2>
--- Boolean Types ---
Value of is_true: True, Type: <class 'bool'>
Value of is_false: False, Type: <class 'bool'>
True + 5: 6
False * 3: 0
The output shows that when a was reassigned from 5 to 6, its ID changed, confirming that a new integer object was created. It also demonstrates that True is treated as 1 and False as 0 in calculations.