Type conversion means converting a value from one data type to another. In Python, this is often called typecasting.
int()
, float()
, str()
, etc.# Python automatically converts int to float in expressions
a = 5 # int
b = 2.5 # float
c = a + b # a converted to float automatically
print(c) # Output: 7.5 (float)
print(type(c)) # <class 'float'>
# Convert float to int (note: decimal part is truncated)
f = 9.8
i = int(f)
print(i) # Output: 9
# Convert int to float
i = 5
f = float(i)
print(f) # Output: 5.0
# Convert int to string
i = 100
s = str(i)
print(s) # Output: "100"
# Convert string to int (string must represent a valid integer)
s = "42"
i = int(s)
print(i) # Output: 42
# Convert string to float
s = "3.14"
f = float(s)
print(f) # Output: 3.14
# Convert other types to boolean
print(bool(0)) # False
print(bool(10)) # True
print(bool("")) # False
print(bool("False")) # True (non-empty string)
int(x)
— converts x to integerfloat(x)
— converts x to floatstr(x)
— converts x to stringbool(x)
— converts x to booleancomplex(x)
— converts x to complex numberlist(x)
, tuple(x)
, set(x)
— convert to collection typesValueError
occurs.# Get two numbers as input and add them
num1 = input("Enter first number: ") # input returns string
num2 = input("Enter second number: ")
# Convert strings to int before adding
sum_ = int(num1) + int(num2)
print("Sum is:", sum_)