0
0
Pythonprogramming~5 mins

type() and isinstance() in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the type() function do in Python?

The type() function returns the exact type of an object, such as int, str, or list.

Click to reveal answer
beginner
What is the purpose of isinstance() in Python?
<p><code>isinstance()</code> checks if an object is an instance of a class or a subclass, returning <code>True</code> or <code>False</code>.</p>
Click to reveal answer
intermediate
How is type() different from isinstance()?
<p><code>type()</code> checks for the exact type of an object, while <code>isinstance()</code> checks if the object is of a type or any subclass of that type.</p>
Click to reveal answer
intermediate
What will isinstance(5, (int, float)) return and why?

It returns True because 5 is an int, and isinstance() can check against a tuple of types.

Click to reveal answer
intermediate
Can <code>type()</code> be used to check if an object is a subclass instance?
<p>No, <code>type()</code> only checks the exact type, so it does not consider subclass relationships. Use <code>isinstance()</code> for that.</p>
Click to reveal answer
What does type('hello') return?
Ahello
B<class 'str'>
Cstring
DTypeError
Which function checks if an object is an instance of a class or its subclass?
Atype()
Binstance()
Cclass()
Disinstance()
What will type(3.14) == float return?
AFalse
B3.14
CTrue
DTypeError
Which is the correct way to check if obj is either an int or float?
Aisinstance(obj, (int, float))
Btype(obj) == int or float
Ctype(obj) in (int, float)
Disinstance(obj, int) and isinstance(obj, float)
If class Dog(Animal): pass, what will type(dog) == Animal return if dog is a Dog instance?
AFalse
BTrue
CTypeError
DDepends on Python version
Explain the difference between type() and isinstance() in Python.
Think about how each function treats subclasses.
You got /4 concepts.
    How can you check if a variable is either an integer or a float using Python built-in functions?
    Remember isinstance() can check multiple types at once.
    You got /3 concepts.