** Casting** is known as type conversion, the process involves changing a variable's data type from one type to another. This process ensures operations can be performed correctly and that data is used as intended.
Python supports 2 main types of casting;
1. Implicit casting
Python interpreter automatically does this type of casting, for instance, when an arithmetic operation between an integer and a float takes place, Python will automatically convert the integer to a float before performing the calculation.
2. Explicit casting
This type of casting is done manually by the programmer using built-in functions.
Common functions are;
int(): converts value to an integer
float(): converts value to a floating point number
str(): converts value to a string
bool(): converts value to boolean
`x = 7 # x is an integer
y = "14" # y is a string
z = x + int(y) # Explicitly casting y to an integer before adding it to x
print(z) # Output: 21`
NOTE: Casting can lead to loss of precision; converting a float to an integer shortens the decimal part.
Top comments (0)