Casting in Python (Type Conversion)#
In Python, “casting” means converting a data type to another data type.
Since Python is a dynamically typed language, it is sometimes necessary to explicitly convert the data type of a variable.
1. int -> float#
In the following code, the variable a is of int type.
Since a is cast to float type as b = float(a), b is of float type and its value is the floating-point number 10.0.
a = 10
b = float(a)2. float -> int#
The following code casts the float type c to int type and stores it in the variable d.d is of int type and its value is the integer 20.
c = 20.0
d = int(c)3. float -> int#
When converting from float type to int type, the decimal part is truncated.
Therefore, the value of the variable f is the integer 30.
e = 30.8
f = int(e)4. int/float -> string#
The following code is an example of converting an int/float type to a string type.
The variable h is of string type and its value is ‘40’.
g = 40
h = str(g)5. string -> int/float#
The following code is an example of converting a string type to int/float type.
The variable j is of int type and its value is 50.
The variable k is of float type and its value is 50.0.
i = '50'
j = int(i)
k = float(i)