Type casting in Python refers to the process of converting one data type into another. It is used when we need to perform operations between different data types or when we want a value in a specific format.
Python supports two types of type casting:
Implicit type casting is automatically performed by Python when it converts one data type into another without user intervention.
Python usually converts smaller data types into larger data types to avoid data loss.
x = 10 # int
y = 2.5 # float
result = x + y
print(result)
print(type(result))
Output
12.5
<class 'float'>
Explanation
x (int) into float automatically.int → float → complexExplicit type casting is done manually by the programmer using built-in functions to convert data from one type to another.
| Function | Description |
|---|---|
int() |
Converts value to integer |
float() |
Converts value to float |
str() |
Converts value to string |
bool() |
Converts value to boolean |
x = "10"
y = int(x)
print(y)
print(type(y))
Output
10
<class 'int'>
x = "3.14"
y = float(x)
print(y)
Output
3.14
x = 100
y = str(x)
print(y)
print(type(y))
Output
100
<class 'str'>
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
age = int(input("Enter age: "))
print(age + 5)
Explanation
x = (1, 2, 3)
y = list(x)
print(y)
x = [1, 2, 3]
y = tuple(x)
x = [1, 2, 2, 3]
y = set(x)
print(y)
x = "hello"
y = int(x) # Error
Explanation
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
sum = int(num1) + int(num2)
print("Sum =", sum)
Type casting is converting one data type to another.
Two types:
Common functions: int(), float(), str(), bool()
Required when working with user input and mixed data types
Helps avoid errors and ensures correct operations