03 Jul Type Conversion in Python
Type Conversion in Python allows users to convert int type to another, for example, float to int, int to complex, int to float, etc. To convert a number from one type to another, for example, into float, we have the following methods in Python:
- float(num): To convert from num int to float type.
- int(num): To convert num to int type.
- long(num): To convert num to long type.
- complex(num): To convert from num int to complex type.
- Complex (Num1, num2): To convert num1 and num2 to complex type, wherein num1 will be the real part, whereas num2 will be the imaginary part with j.
Let us now see some examples of Type Conversion and convert one datatype to another:
Convert int to float in Python
Let us see an example of float() in Python to convert type int into float:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python # int datatype val = 5 print("Value: ",val) print("Value type: ",type(val)) # convert int to float res = float(val) print("Converted Value: ",res) print("Type of converted Value: ",type(res)) |
The output is as follows:
1 2 3 4 5 6 |
Value: 5 Value type: <class 'int'> Converted Value: 5.0 Type of converted Value: <class 'float'> |
Convert from float to int in Python
Let us see an example of the int() in Python to convert from type float to int:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python # float datatype val = 5.2 print("Value: ",val) print("Value type: ",type(val)) # convert float to int res = int(val) print("Converted Value: ",res) print("Type of converted Value: ",type(res)) |
The output is as follows:
1 2 3 4 5 6 |
Value: 5.2 Value type: <class 'float'> Converted Value: 5 Type of converted Value: <class 'int'> |
Convert int to complex in Python
Let us see an example of the complex() in Python to typecast int to complex type:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python # int datatype val = 7 print("Value: ",val) print("Value type: ",type(val)) # convert int to complex res = complex(val) print("Converted Value: ",res) print("Type of converted Value: ",type(res)) |
The output is as follows:
1 2 3 4 5 6 |
Value: 7 Value type: <class 'int'> Converted Value: (7+0j) Type of converted Value: <class 'complex'> |
Video Tutorial (English)
Video Tutorial (Hindi)
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments