In Python, implicit conversion (also known as implicit type conversion or coercion) refers to the automatic conversion of one data type to another by the interpreter, without the need for explicit instructions from the programmer.
Python performs implicit conversions when it encounters an operation involving different data types.
Here’s an example of implicit conversion in Python:
# Implicit conversion of int to float
a = 5 # integer
b = 2.5 # float
result = a + b # Python implicitly converts 'a' to float
print(result) # Output: 7.5
Code language: Python (python)
In the above example, the variable a
is an integer, and b
is a float. When we perform the addition operation a + b
, Python automatically converts the integer a
to a float before performing the addition.
As a result, the output is a float value of 7.5
.
Implicit conversion can also occur in other scenarios, such as when performing arithmetic operations between different numeric types or when concatenating strings with other data types.
Python tries to intelligently convert the operands to a compatible type for the operation to be executed.
It’s important to note that not all types can be implicitly converted, and certain type combinations may result in an error.
The rules for implicit conversion depend on the specific data types involved and the operation being performed.
Example for implicit type conversion in Python
# Implicit conversion of int to string
a = 10 # integer
b = "20" # string
result = a + b # Python implicitly converts 'a' to string and performs string concatenation
print(result) # Output: "1020"
Code language: Python (python)
In this example, we have an integer variable a
with a value of 10
and a string variable b
with a value of "20"
.
When we perform the addition operation a + b
, Python implicitly converts the integer a
to a string and performs string concatenation instead of arithmetic addition.
The result is a string "1020"
, which is the concatenation of the string "10"
and the string "20"
.
Read More;
- Simple Python Script Example [Super Simple!]
- K-means Clustering for Anomaly Detection
- Example for User-defined Exception in Python
- Example for Break and Continue in Python
- Example for Complex Number in Python
- How do I write a YAML file in Python?
- What is Statement in Python With Example?
- What is ‘Self’ in Python With Example
- What is Attribute in Python With Example
- Example JSON file for Python [With Explantion]
- What is Token in Python With Example
- List I j in Python [Detailed Examples]