In this article, you will learn how to check the type of a variable in Python.
The type() Function
The type() function is a built-in function that returns the type of an object. For example, the following code returns the type of the variable i:
i = [1, 2, 3] print(type(i))
This code will print out the following:
list
This means that the variable `i` is a list.
Example code
The following code shows how to use the `type()` function to check the type of different variables:
i = [1, 2, 3] print(type(i)) # list myPet = 'dog' print(type(myPet)) # str myNumber = 2.86 print(type(myNumber)) # float

How to Check if a Variable is a String
To check if a variable is a string, you can use the `isinstance()` function. The `isinstance()` function takes two arguments: the first argument is the variable you want to check, and the second argument is the type you want to check it against. For example, the following code checks if the variable `my_variable` is a string:
isinstance(my_variable, str)
This code will return True if the variable my_variable is a string, and False if it is not.
Here is an example of how to use the isinstance() function to check if a variable is a string:
my_variable = "This is a string." if isinstance(my_variable, str): print("The variable is a string.") else: print("The variable is not a string.")
This code will print the following:
The variable is a string.
Conclusion
In this article, you learned how to check the type of a variable in Python. You learned about the `type()` function and how to use it to check the type of different variables.
Key Takeaways
- To check the type of a variable in Python, you can use the `type()` function.
- The `isinstance()` function can be used to check if a variable is a specific type.
- The `type()` and `isinstance()` functions are both built-in functions in Python.