Python Type Conversion
Python Type Conversion
In Python, type conversion is the process of converting the data type of a value into another. It allows you to operate on variables of different types safely and effectively.
There are two main types of type conversion in Python:
- Implicit Conversion (done automatically by Python)
- Explicit Conversion (done manually by the programmer)
Let’s explore both in detail with examples and explanations.
Implicit Type Conversion
Implicit conversion happens when Python automatically converts a value from one data type to another during an operation. This usually happens when combining values of different types where one type has higher precision than the other.
Python Promotes Data Types Automatically
When performing operations between int
and float
, Python converts the int
to float
to preserve precision.
a = 5 # int
b = 3.2 # float
result = a + b
print("Result:", result)
print("Type of result:", type(result))
Output:
Result: 8.2
Type of result: <class 'float'>
5
is an integer, and3.2
is a float.- The result is a float, because
float
is a more precise type thanint
.
Chained Conversions
Python can handle multiple types together:
x = True # bool
y = 10 # int
z = 2.5 # float
result = x + y + z
print("Final Result:", result)
print("Final Type:", type(result))
Output:
Final Result: 13.5
Final Type: <class 'float'>
True
is converted to1
(sincebool
is a subclass ofint
)- The total sum ends up as a
float
.
Limitations of Implicit Conversion
Not all types are compatible with automatic conversion. For example, combining a string and an integer without converting one of them will raise an error.
name = "Age: "
age = 30
# This will raise a TypeError
# print(name + age)
Error:
TypeError: can only concatenate str (not "int") to str
To fix this, explicit conversion is required.
Explicit Type Conversion (Type Casting)
Explicit conversion means you're converting types manually using built-in Python functions:
int()
– converts to integerfloat()
– converts to floatstr()
– converts to stringbool()
– converts to boolean
This process is also called type casting.
Converting Strings to Numbers
num_str = "42"
num_int = int(num_str)
print("Converted to int:", num_int)
print("Type:", type(num_int))
Output:
Converted to int: 42
Type: <class 'int'>
You can also convert decimal strings to floats:
decimal_str = "3.14"
decimal_float = float(decimal_str)
print("Converted to float:", decimal_float)
Output:
Converted to float: 3.14
Adding a String and a Number After Conversion
price_str = "100"
price_int = 20
total = int(price_str) + price_int
print("Total Price:", total)
Output:
Total Price: 120
Here, price_str
is explicitly converted to an integer so it can be added to price_int
.
Converting Other Types to String
Often useful for displaying information:
user = "Alice"
age = 28
message = user + " is " + str(age) + " years old."
print(message)
Output:
Alice is 28 years old.
You cannot concatenate strings with non-strings without converting them.
Boolean Conversion
You can convert various types to boolean using bool()
:
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("Hello")) # True
print(bool([])) # False
print(bool([1, 2])) # True
Python considers empty structures and zero-like values as False
, everything else is True
.
Summary
- Implicit Type Conversion is done automatically by Python when it’s safe.
- Explicit Type Conversion (Type Casting) is done manually using functions like
int()
,float()
,str()
, andbool()
. - Implicit conversion avoids data loss by promoting lower types to higher types.
- Explicit conversion allows you to control how data is transformed and interpreted.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.