In Python, the type() function is used to determine the type of a given object. Here's a detailed explanation of how to use it:
Input is Shown Below :
Code :-
Output is Shown Below :
PS C:\Users\Mi\Desktop\JsApps> & "C:/Program Files/Python312/python.exe" c:/Users/Mi/Desktop/Python/intro.py <class 'int'> <class 'int'> <class 'str'> <class 'list'> <class 'tuple'> <class 'set'>
Explanation:
type(): This function returns the type of the specified object.x = 5: This line assigns the integer value 5 to the variablex.print(type(x)): Here, thetype()function is called withxas an argument. It returns the type of the object referred to byx, which is an integer. Theprint()function then prints this type, which will be<class 'int'>.print(type(5)): This line directly checks the type of the integer value 5 without assigning it to a variable first. It produces the same output as Example 1.y = "Hello, world!": This line assigns the string "Hello, world!" to the variabley.print(type(y)): Similarly, this line checks the type of the object referred to byy, which is a string. It prints<class 'str'>.z = [1, 2, 3, 4, 5]: This line assigns a list containing integers to the variablez.print(type(z)): Here, the type ofzis checked, which is a list. It prints<class 'list'>.
Using the type() function can be useful when you want to verify the type of an object, especially in cases where the behavior of your code depends on the type of data being processed.
Comments
Post a Comment