0
0
Pythonprogramming~5 mins

Type checking using type() in Python

Choose your learning style9 modes available
Introduction
Sometimes, you want to know what kind of data you have. The type() function helps you find out if a value is a number, text, or something else.
When you want to check if a user entered a number or text.
When you need to handle data differently based on its type.
When debugging to understand what kind of data a variable holds.
When writing functions that behave differently for different data types.
Syntax
Python
type(object)
The object can be any value or variable you want to check.
type() returns the type of the object, like for numbers.
Examples
Checks the type of the number 5, which is an integer.
Python
type(5)
Checks the type of the text 'hello', which is a string.
Python
type('hello')
Checks the type of a list of numbers.
Python
type([1, 2, 3])
Sample Program
This program checks and prints the types of three different variables: a number, a string, and a list.
Python
a = 10
b = 'apple'
c = [1, 2, 3]

print(type(a))
print(type(b))
print(type(c))
OutputSuccess
Important Notes
type() shows the exact type, including built-in types like int, str, list, and custom classes.
Use type() to compare types, but for checking if something is a type or subclass, isinstance() is often better.
Summary
type() tells you the kind of data stored in a variable.
It helps you write code that works correctly with different data types.
Use it to understand and debug your programs.