Python Learning
🐍 Python Type Checking
🔹 What is Type Checking?
Type checking is the process of checking the data type of a value or variable. Python provides several ways to do this.
age = 17
name = "Ted"
skills = ["Python", "AI", "Data Science"]
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(skills)) # <class 'list'>
🔹 Using isinstance()
isinstance() is often more useful when you want to check whether a value belongs to a particular type.
age = 17
if isinstance(age, int):
print("Age is an integer")
🔹 Type Hints
Python also supports type hints, which make your code easier to understand and allow tools such as IDEs and static type checkers to detect potential problems.
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
Here:
price: float → expected to be a decimal number
quantity: int → expected to be an integer
-> float → expected return type
📌 Key takeaway:
Python is dynamically typed, but that doesn't mean you should ignore types. Using type(), isinstance(), and type hints can make your Python code more reliable and easier to maintain.
2 · 576 ·