Type Conversion in Python

Type Conversion: It means to convert the operands of one data type into another data type.

Types of Conversions: Python supports two types of conversions:
1) Implicit Type Promotion/ Internal Conversion
2) Explicit Type Casting/ External Conversion

1) Implicit Type Promotion/ Internal Conversion : It is the conversion done by the python compiler/interpreter without user’s intervention.
1) int and complex are to be added, so int will be promoted to complex before evaluating.
5 + (7+7j)
( 5 + 0j) + (7 + 7j)
(12+7j)
2) int and float are to be added, so int will be promoted to float before evaluating.
5 + 7.5
= 5.0 + 7.5
= 12.5
3) float and complex are to be added, so float will be promoted to complex before evaluating.
7.6 + (2+5j)
= (7.6 + 0j) + (2 + 5j)
= (9.6+5j)

>>> 5 + (7+7j)
(12+7j)

>>> 5 + 7.5
12.5

>>> 7.6 + (2+5j)
(9.6+5j)

2) Explicit Type Casting/ External Conversion : It is explicitly done by the user. We can convert all data types into another possible types.

>>> int(10.5) + 5
15

>>> int(24.5) - 14
10
 

>>> float(10) + 5
15.0

>>> str(9467863365)
'9467863365'

We can convert strings into integers, only if the string contains only numeric characters

>>> int("9467282393")
9467282393

>>> int("gargs academy")
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    int("gargs academy")
ValueError: invalid literal for int() with base 10: 'gargs academy'

We cant convert complex type into integers or floats

>>> int(10 + 8j) + 12.6

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>

    int( 10 + 8j ) + 12.6

TypeError: can't convert complex to int

>>> float(4+6j) + 8.7
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    float(4+6j) + 8.7
TypeError: can't convert complex to float
error: You can only copy the programs code and output from this website. You are not allowed to copy anything else.