Python Casting

Python Casting

In Python, casting is used to convert a variable from one data type to another. Python provides built-in functions like int(), float(), and str() for type conversion.

Types of Casting in Python

1. Integer Casting (int())

The int() function converts a value into an integer.

# Convert float to integer
x = int(10.5)
print(x)  # Output: 10

# Convert string to integer
y = int("20")
print(y)  # Output: 20
        

2. Float Casting (float())

The float() function converts a value into a floating-point number.

# Convert integer to float
a = float(5)
print(a)  # Output: 5.0

# Convert string to float
b = float("3.14")
print(b)  # Output: 3.14
        

3. String Casting (str())

The str() function converts a value into a string.

# Convert integer to string
num = str(100)
print(num)  # Output: '100'

# Convert float to string
pi = str(3.14)
print(pi)  # Output: '3.14'
        

Conclusion

  • Use int() to convert values into integers.
  • Use float() to convert values into floating-point numbers.
  • Use str() to convert values into strings.