Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting is when you convert a variable value from one type to another. Python allows you to cast various data types into one another. This also allows you to specify a data type to a variable. This is called Python Casting.
This is done using constructor functions:
- int(): It constructs an integer number from an integer literal, a float literal, or a string literal.
- float(): It constructs a float number from an integer literal, a float literal or a string literal.
- str(): It constructs a string from a wide variety of data types, including strings, integer literals and float literals.
It is a method used to change the variables/ values declared in a certain data type into a different data type to match the operation required to be performed by the code snippet. In python, this feature can be accomplished by using constructor functions like int(), string(), float(), etc.
a = int(5) b = int("3") x = float(9) y = float(2.8) print(a) print(b) print(x) print(y)
5 3 9.0 2.8