How do you check if a variable is initialized in Python?

The Python’s

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function checks whether the object or variable is an instance of the specified class type or data type.

For example,

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
3 checks if
num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
4 is an instance of a class
num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
5.

Also, Solve: Python Basic Exercise and Beginners Quiz

Table of contents

How To Use isinstance() Function in Python

Let’s see the syntax first before moving to the example.

Syntax:

isinstance(object, classinfo)
  • It takes two arguments, and both are mandatory.
  • The
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    2 function checks if the
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    7 argument is an instance or subclass of
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    8 class argument

Python isinstance()

Using

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object.

  1. Pass object to isinstance()

    Pass the variable you want to check as

    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    7 argument to the
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    2. Here the object can be any class object or any variable name

  2. Specify the Class or Type name as a
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    8 argument

    For example,

    Yes
    3 to check if
    Yes
    4 is an instance of a class
    Yes
    5.
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    8 is a type name or Class name you want to check against the variable. Here you can specify data type name or Class name.
    You can also pass multiple classes/types in a tuple format. For example, you can pass
    Yes
    5,
    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    5,
    Yes
    9,
    # Check if 80 is an instance of class int
    number = 80
    print(isinstance(number, int))
    # output True
    
    print(isinstance(number, float))
    # output False
    
    pi = 3.14
    # Check 3.14 is an instance of class float
    print(isinstance(pi, float))
    # Output True
    
    # Check if (1 + 2j) is an instance of complex
    complex_num = 1 + 2j
    print(isinstance(complex_num, complex))
    # Output True
    
    # Check if 'PYnative' is an instance of class string
    name = "PYnative.com"
    print(isinstance(name, str))
    # Output True
    
    # Check if names is an instance of class list
    names = ["Eric", "Scott", "Kelly"]
    print(isinstance(names, list))
    # Output True
    
    # Check if student_report is an instance of class dict
    student_report = {"John": 80, "Eric": 70, "Donald": 90}
    print(isinstance(student_report, dict))
    # Output True
    
    # Check if names is an instance of class tuple
    names = ("Sam", "Kelly", 'Emma')
    print(isinstance(names, tuple))
    # Output True
    
    # Check if numbers is an instance of class tuple
    numbers = {11, 22, 33, 44, 55}
    print(isinstance(numbers, set))
    # Output True
    0, or any user-created class.

  3. Execute your operation, If result is True

    The

    num = 90
    result = isinstance(num, int)
    if result:
        print("Yes")
    else:
        print("No")
    2 returns True if an object or variable is of a specified type otherwise False.

Example

Using isintance() we can verify whether a variable is a number or string. Let’s assume variable

# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
2, and you want to check whether num is an instance of an int type.

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")

Output:

Yes

As we can see in the output, the

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 returned
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
4 because
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
5 hold an integer value.

Note: If the

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
8 argument is not a Class, type, or tuple of types, a
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
7 exception is raised.

isinstance() With Built-In Types

As you know, Every value (variable) in Python has a type. In Python, we can use different built-in types such as

Yes
5,
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
9, list, tuple, strings, dictionary. Most of the time, you want to check the type of value to do some operations. In this case,
num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function is useful.

# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True

Note: If we use the

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 with any variable or object with a
var = None
# empty but not None
s1 = ''
print(isinstance(var, float))
# Output False
print(isinstance(s1, str))
# Output True
2, it returns
var = None
# empty but not None
s1 = ''
print(isinstance(var, float))
# Output False
print(isinstance(s1, str))
# Output True
3. Let see the simple example of it.

var = None
# empty but not None
s1 = ''
print(isinstance(var, float))
# Output False
print(isinstance(s1, str))
# Output True

isinstance() With Multiple Classes

You can also check the instance with multiple types. Let’s say you have a variable, and you wanted to check whether it holds any numeric value or not, for example, a numeric value can be an

Yes
5 or
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
9.

To verify whether a variable is an instance of one of the specified types, we need to mention all types in a tuple and pass it to the classInfo argument of

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2.

Example

def check_number(var):
    if isinstance(var, (int, float)):
        print('variable', var, 'is instance of numeric type')
    else:
        print('variable', var, 'is not instance of numeric type')

num1 = 80
check_number(num1)
# Output variable 80 is instance of numeric type

num2 = 55.70
check_number(num2)
# Output variable 55.7 is instance of numeric type

num3 = '20'
check_number(num3)
# Output variable '20' is not instance of numeric type

isinstance() With Python Class

The

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 works as a comparison operator, and it compares the object with the specified class type.

You can verify if the

var = None
# empty but not None
s1 = ''
print(isinstance(var, float))
# Output False
print(isinstance(s1, str))
# Output True
8 object is an instance of a user-defined class Employee using the
num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function. It must return True.

class Employee:

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

class Person:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex

emp = Employee("Emma", 11000)
per = Person("Brent", "male")

# Checking if a emp object is an instance of Employee
print(isinstance(emp, Employee))
# Output True

# Checking if the per object is an instance of Employee
print(isinstance(per, Employee))
# Output False

isinstance() function With Inheritance

The object of the subclass type is also a type of parent class. For example, If Car is a subclass of a Vehicle, then the object of Car can be referred to by either Car or Vehicle. In this case, the

def check_number(var):
    if isinstance(var, (int, float)):
        print('variable', var, 'is instance of numeric type')
    else:
        print('variable', var, 'is not instance of numeric type')

num1 = 80
check_number(num1)
# Output variable 80 is instance of numeric type

num2 = 55.70
check_number(num2)
# Output variable 55.7 is instance of numeric type

num3 = '20'
check_number(num3)
# Output variable '20' is not instance of numeric type
0 will return
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
4.

The

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function works on the principle of the is-a relationship. The concept of an is-a relationship is based on class inheritance.

The

def check_number(var):
    if isinstance(var, (int, float)):
        print('variable', var, 'is instance of numeric type')
    else:
        print('variable', var, 'is not instance of numeric type')

num1 = 80
check_number(num1)
# Output variable 80 is instance of numeric type

num2 = 55.70
check_number(num2)
# Output variable 55.7 is instance of numeric type

num3 = '20'
check_number(num3)
# Output variable '20' is not instance of numeric type
3 returns True if the classinfo argument of the instance() is the object’s class’s parent class.

To demonstrate this, I have created two classes, Developer and PythonDeveoper. Here PythonDeveoper is a sub-class of a Developer class.

class Developer(object):

    # Constructor
    def __init__(self, name):
        self.name = name

    def display(self):
        print("Developer:", self.name, "-")

class PythonDeveloper(Developer):

    # Constructor
    def __init__(self, name, language):
        self.name = name
        self.language = language

    def display(self):
        print("Python Developer:", self.name, "language:", self.language, "-")

# Object of PythonDeveloper
dev = PythonDeveloper("Eric", "Python")
# is PythonDeveloper object an instance of a PythonDeveloper Class
print(isinstance(dev, PythonDeveloper))
# Output True

# is python_dev object an instance of a Developer Class
print(isinstance(dev, Developer))
# Output True

Note: The

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function is beneficial for casting objects at runtime because once you get to know the given class is a subclass of a parent class, you can do casting appropriately if required.

isinstance with Python list

As you know, a Python list is used to store multiple values at the same time. These values can be of any data type like numbers, strings, or any Class objects.

In this section, we will test the following operations with the Python list using the

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function:

  • Checking if an object is of type
    Yes
    9 in python.
  • Check if an element of a list is a list.
  • Verify if elements of a list are numbers or strings.
  • Python check if all elements of a list are the same type

Checking if an object is an instance of a list type

sample_list = ["Emma", "Stevan", "Brent"]
res = isinstance(sample_list, list)
print(sample_list, 'is instance of list?', res)

# Output 'Emma', 'Stevan', 'Brent'] is instance of list? True

Check if an element of a list is a nested list

To check if one of the elements in the list is itself a list. For example, you have the following list, Use the

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 to verify if the list contains a nested list

sampleList = ['Emma', 'Stevan', ['Jordan', 'Donald', 'Sam']]

Iterate a list and verify each element’s class, and if it a list type, we can say that the list contains a nested list.

num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
0

Check if elements of a list are numbers or strings

Check each element’s type with multiple numeric types such as

Yes
5,
# Check if 80 is an instance of class int
number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex
complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string
name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list
names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict
student_report = {"John": 80, "Eric": 70, "Donald": 90}
print(isinstance(student_report, dict))
# Output True

# Check if names is an instance of class tuple
names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple
numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True
9, and
class Employee:

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

class Person:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex

emp = Employee("Emma", 11000)
per = Person("Brent", "male")

# Checking if a emp object is an instance of Employee
print(isinstance(emp, Employee))
# Output True

# Checking if the per object is an instance of Employee
print(isinstance(per, Employee))
# Output False
0using the
num = 90
result = isinstance(num, int)
if result:
    print("Yes")
else:
    print("No")
2 function.

How are variables initialized in Python?

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

How do you check variables in Python?

To get the type of a variable in Python, you can use the built-in type() function.

How do you check if a variable is undefined in Python?

Python Code: try: x = 1 except NameError: print("Variable is not defined....!") else: print("Variable is defined.") try: y except NameError: print("Variable is not defined....!") else: print("Variable is defined.") Sample Output: Variable is defined.

How to check if environment variable exists in Python?

# Checking if an Environment Variable Exists in Python import os if 'USER' in os. environ: print('Environment variable exists! ') else: print('Environment variable does not exist. ') # Returns: # Environment variable exists!