Type casting is the process of converting one data type into another.
Python provides built-in functions that allow you to convert data from one type to another.
Type Casting Functions
Python has the following casting functions:
int()– converts a value to an integerfloat()– converts a value to a floatstr()– converts a value to a stringbool()– converts a value to a boolean
Casting to Integer
The int() function converts a value to an integer.
Example:
x = int(5.9)
y = int("10")
print(x)
print(y)
Output:
5
10
Casting to Float
The float() function converts a value to a floating-point number.
Example:
x = float(5)
y = float("10")
print(x)
print(y)
Output:
5.0
10.0
Casting to String
The str() function converts a value to a string.
Example:
x = str(100)
y = str(5.5)
print(x)
print(y)
Output:
100
5.5
Casting to Boolean
The bool() function converts a value to True or False.
Example:
print(bool(1))
print(bool(0))
Output:
True
False
Common Examples
Convert string to integer:
age = "25"
print(int(age))
Output:
25
Convert integer to string:
age = 25
print(str(age))
Output:
25
Convert integer to float:
price = 100
print(float(price))
Output:
100.0
Invalid Casting
Not all values can be converted.
Example:
x = int("Hello")
Output:
ValueError: invalid literal for int()
Why Use Type Casting?
Type casting is useful when:
- Taking user input
- Performing calculations
- Converting data from APIs
- Formatting output
Example:
age = input("Enter your age: ")
print(int(age) + 5)
Without int(), Python would treat the input as a string.
Summary
- Type casting converts one data type to another.
- Use
int()to convert to integers. - Use
float()to convert to floating-point numbers. - Use
str()to convert to strings. - Use
bool()to convert to boolean values. - Invalid conversions raise errors.