Python – Casting

Python Variable Casting means converting one data type variable into another data type variable. Casting functions return a new object representing the converted value.

Types of Casting Functions:

  • int(x): Converts a x variable into Integer from float, integer or string (String should be a whole number) variable.
  • float(x): Converts a x variable into Float from float, integer or string (String should be a integer or float) variable.
  • str(x): Converts a x variable into String from float, integer or string variable.

Data Type Conversion Examples:

a = 202             # Integer
x = str(a)          # Output: 202 -> String
y = int(a)          # Output: 202
z = float(a)      # Output: 202.0

b = 1.25 # Float
x = str(b)          # Output: 1.25 -> String
y = int(b)          # Output: 1
z = float(b)      # Output: 1.25

c = "StudyGyaan" # String
x = str(c)          # Output: 1.25 -> String
# y = int(c)  -> Cannot convert        
# z = float(c)  -> Cannot convert
Filed under: Python

No comment yet, add your voice below!


Leave a Reply