27Aug  Admin

Casting is when you convert a variable value from one type to another. This is, in Python, done with functions such as int() or float() or str()

Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int()

This Python cast function is used to construct any integral number with the help of an integral literal, a string literal (obtained by rounding down the previous whole number), or a float literal (a whole number is represented by providing a string).

Example

x = int(2)
y = int(4.8)
z = int(“8”)
print(x)
print(y)
print(z)

Output

2

4

8

  • float()

This construction function helps in the construction of any float number with the help of a float literal, an integral literal, or a string literal (if a float or an integer is represented by a string).

Example

x = float(4)
y = float(7.8)
z = float(“5”)
w = float(“2.4”)
print(x)
print(y)
print(z)
print(w)

Output

4.0
7.8
5.0
2.4

  • str()

This construction function helps in the construction of any string with the help of a lot of different data types.

Example

x = str(“s2”)
y = str(9)
z = str(5.0)
print(x)
print(y)
print(z)


Output

s2
9
5.0