Practice: Type Checking
Q1. Print the type of an integer
Print the type of the value 100.
Goal: Use type().
Q2. Type name of a float
Print only the short name of the type of 2.5 (no <class ...> text).
Goal: Get a clean type name.
Q3. Is it a string?
Store 'python' in a variable and print whether it is a str using isinstance.
Goal: Use isinstance().
Q4. Number or not
Write a function is_number(x) that returns True for int or float and False otherwise. Print the results for 5, 2.5 and 'a'.
Goal: Check several types.
Q5. Number but not bool
Write is_real(x) that is True for int or float but False for bool. Print is_real(True) and is_real(3).
Goal: Handle the bool edge case.
Q6. Count the types
Given items = [1, 'a', 2, 3.5, 'b', 4], print how many of them are ints.
Goal: Combine loops with type checks.
Q7. Safe None check
Write a function that takes a value and returns 'missing' if it is None, otherwise 'present'. Call it with None and with 0.
Goal: Test None correctly.
Q8. Types in a list
Print the short type name of each item in [1, 'x', 2.0, None], one per line.
Goal: Loop over mixed values.
Q9. Output: type of a sum
What does this print?
print(type(2 + 3))
print(type(2 + 3.0))Goal: Predict result types.
Q10. Output: bool and int
What does this print?
print(isinstance(True, int))
print(type(True) == int)
print(True + 1)Goal: Understand bool as int.
Q11. Output: tuple of types
What does this print?
x = 3.0
print(isinstance(x, (int, str)))
print(isinstance(x, (int, float)))Goal: Use a tuple of types.
Q12. Output: type of None
What does this print?
print(type(None))
print(None is None)Goal: Know NoneType.
Q13. Output: subclass check
What does this print?
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(type(d) == Animal)
print(isinstance(d, Animal))
print(isinstance(d, Dog))Goal: Compare type and isinstance for classes.
Q14. Output: hints do nothing
What does this print?
def f(x: int) -> int:
return x
print(f('hi'))
print(f.__annotations__['x'])Goal: Know hints are not enforced.
Q15. Output: type of input-like values
What does this print?
a = '5'
b = 5
print(type(a) == type(b))
print(type(a).__name__, type(b).__name__)Goal: Compare types of similar-looking values.
Q16. Fix the bool bug
This function should reject booleans but does not. Fix it so is_int(True) returns False.
def is_int(x):
return isinstance(x, int)Goal: Fix a type check.
Q17. Fix the isinstance call
This code crashes with a TypeError. Fix it.
print(isinstance(5, [int, str]))Goal: Use isinstance correctly.
Q18. Fix the None test
The code tests for None in a poor way. Rewrite it with the recommended style.
value = None
if value == None:
print('empty')Goal: Use is None.
Q19. Why hints do not stop errors
A student says: my function has x: int, so Python will refuse a string. Explain what is wrong.
Goal: Explain type hints.
Q20. Why prefer isinstance
Give one reason to prefer isinstance() over type(x) == SomeType.
Goal: Compare the two tools.