Confirm with isinstance()
In this step, we will explore the isinstance()
function in Python, which provides another way to verify the data type of a variable. The isinstance()
function checks if an object is an instance of a specified class or type. This is particularly useful for more complex type checking scenarios.
Let's continue modifying the integers.py
file. Open integers.py
in the VS Code editor and add the following lines of code:
## Assigning integer values to variables
x = 10
y = -5
z = 0
## Printing the values of the variables
print("The value of x is:", x)
print("The value of y is:", y)
print("The value of z is:", z)
## Using the type() function to identify the data type
print("The type of x is:", type(x))
print("The type of y is:", type(y))
print("The type of z is:", type(z))
## Using isinstance() to confirm the data type
print("Is x an integer?", isinstance(x, int))
print("Is y an integer?", isinstance(y, int))
print("Is z an integer?", isinstance(z, int))
In this code, we've added three new print()
statements that use the isinstance()
function to check if the variables x
, y
, and z
are instances of the int
class. The isinstance()
function returns True
if the object is an instance of the specified class, and False
otherwise.
Now, run the script again using the following command in the terminal:
python integers.py
You should see the following output:
The value of x is: 10
The value of y is: -5
The value of z is: 0
The type of x is: <class 'int'>
The type of y is: <class 'int'>
The type of z is: <class 'int'>
Is x an integer? True
Is y an integer? True
Is z an integer? True
The isinstance()
function confirms that x
, y
, and z
are indeed integers. This method is often preferred over type()
for its flexibility, especially when dealing with inheritance and polymorphism.