Junior — Middle
What tools can be used to determine the type of a variable in Python?
sobes.tech AI
Answer from AI
In Python, you can determine the type of a variable in several ways:
type()function — returns the type of an object.
x = 10
print(type(x)) # <class 'int'>
isinstance()function — checks if an object is an instance of a specified type or its subclass.
x = [1, 2, 3]
print(isinstance(x, list)) # True
- Type annotations (type hints) — do not determine the type at runtime but assist static code analysis.
def func(a: int) -> str:
return str(a)
For dynamic runtime checks, type() and isinstance() are most commonly used.