Type() function in Python

Overview:

  • The Python built-in function type() returns the type of an object.
  • The type of an object is represented as an object of class type.
  • In a Python program, each variable and each literal is an instance of some class. In the statement x = 1, x is an instance of class int.
  • Python is a strongly typed programming language. The type of an object determines the operations available on an object.
  • Python is also a dynamically typed language, hence no declaration of type is required when a variable is introduced in a scope. The type of a variable can be changed during the execution of the program by assigning objects of diffrent types as the program runs.

Example:

# Example Python program that uses
# the built-in function type() to determine the
# types of various objects

# Print the type of numeric values...
# An integer
count = 25
print(type(count))

# A float
pi = 3.14
print(type(pi))

# Print the type of few collections...
# A tuple
colors = ("Red", "Blue", "Green")
print(type(colors))

# A list
primes = [2, 3, 5, 7]
print(type(primes))

# Dictionary
flowersVsColors = {"Rose":"Red",
                    "Violet":"Blue",
                    "Sunflower":"Yellow"}
print(type(flowersVsColors))

# Print the type of a Python type
typeInfo = type(flowersVsColors)
print(type(typeInfo))

 


Copyright 2024 © pythontic.com