How to check type of variable in Python in if condition

To check the type of a variable in Python in an if condition, you can use the isinstance function. The isinstance function returns True if the object passed as the first argument is an instance of the type passed as the second argument, and False otherwise.

Here is the syntax of the isinstance function:

isinstance(object, classinfo)

The object argument is the object whose type you want to check, and the classinfo argument is the type that you want to check against. The classinfo argument can be a type object or a tuple of type objects.

Here is an example of how to use the isinstance function to check the type of a variable in an if condition:

x = 10
if isinstance(x, int):
    print("x is an integer")
else:
    print("x is not an integer")

The output of the above code would be:

x is an integer

In the above example, the isinstance function is used to check if the variable x is an instance of the int type. Since x is an integer, the condition isinstance(x, int) evaluates to True and the statement print("x is an integer") is executed.

You can also use the isinstance function to check if an object is an instance of multiple types. For example, to check if a variable is either an integer or a string, you can do the following:

x = 10
if isinstance(x, (int, str)):
    print("x is an integer or a string")
else:
    print("x is not an integer or a string")

The output of the above code would be:

x is an integer or a string

Check if a variable is string in Python

To check if a variable is a string in Python, you can use the isinstance() function. Here’s an example:

my_var = "hello"

if isinstance(my_var, str):
    print("my_var is a string")
else:
    print("my_var is not a string")

The isinstance() function takes two arguments: the variable you want to check, and the type you want to check it against. In this case, we’re checking if my_var is an instance of the str type, which represents a string in Python. If it is, the code will print “my_var is a string”. If it’s not, it will print “my_var is not a string”.

You can also use the type() function to check the type of a variable, but isinstance() is generally more flexible because it can also check if the variable is an instance of a subclass of the specified type. For example:

class MyString(str):
    pass

my_var = MyString("hello")

if isinstance(my_var, str):
    print("my_var is a string")
else:
    print("my_var is not a string")

In this case, the code will still print “my_var is a string” because MyString is a subclass of str.

Leave a Comment