Type Conversion
In Python, data can exist in different forms — like strings, integers, floats, or booleans. Sometimes, you may need to convert one type into another. This process is called type conversion or type casting.
In Python, data can exist in different forms — like strings, integers, floats, or booleans. Sometimes, you may need to convert one type into another. This process is called type conversion or type casting.
Python supports two main types of conversions:
Python automatically promotes compatible data types during operations. For example, it promotes an int to a float when needed.
x = 5
y = 2.0
result = x + y
print(result)
print(type(result))
7.0
<class 'float'>
In the example above, x is an integer and y is a floating-point number. When added together, Python automatically converts x to a float, so the result is also a float: 7.0. The type() function confirms this by outputting <class 'float'>.
This is where you take control using Python’s built-in conversion functions. Let’s explore them one by one.
| Function | Description |
|---|---|
int() | Converts to integer |
float() | Converts to float |
bool() | Converts to boolean |
str() | Converts to string |
s = "123"
num = int(s)
print(num)
print(type(num))
123
<class 'int'>
In this example, the string "123" is successfully converted into the integer 123. The type() function confirms that num is now an int, not a str.
Be careful — if the string is not a valid integer, Python throws a ValueError.
s = "abc"
num = int(s) # This will crash
ValueError: invalid literal for int() with base 10: 'abc'
s = "12.34"
f = float(s)
print(f)
print(type(f))
12.34
<class 'float'>
In Python, any non-empty string is considered True. An empty string is False.
print(bool("hello")) # True
print(bool("")) # False
True
False
Converting a number to string is often needed while building messages, filenames, or storing data.
age = 25
text = "I am " + str(age) + " years old"
print(text)
I am 25 years old
When you convert a float to an int, it chops off everything after the decimal point. It doesn’t round — it truncates.
value = 3.99
print(int(value))
3
type() to VerifyAlways verify what type you are working with using type(). It helps avoid confusion and bugs.
x = "123"
print(type(x)) # Before conversion
x = int(x)
print(type(x)) # After conversion
<class 'str'>
<class 'int'>
Imagine asking Python to add a number and a string — it won’t make sense unless both are of the same type. Type conversion allows us to:
None — it’s False in a boolean context, but still a valid string.