Type Conversion in Python

Type Conversion in Python allows users to convert an 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 a float, we have the following methods in Python:

  • float(num): To convert from num int to float type.
  • int(num): To convert num to the 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 the 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:

Demo15.py

# 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:

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:

Demo16.py

# 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:

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 an int to a complex type:

Demo17.py

#!/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:

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:

Python Numbers with Examples
Python IDLE
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment