image
image
image

Converting Integer to Float

image

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=451

number_flo=4.51

number_new=number_int+number_flo

print(“the type of data of number_int-“, type(number_int))

print(“the type of data of number_flo-“, type(number_flo))

print(“value of number_new-“number_new)

print(“type of data of number_new-“, type(number_new))

Discussion

The programming is adding two variables one of data type integer and the other float and storing the value in a new variable of data type float. Python automatically converts small data types into larger data types to avoid prevent data loss. This is known as implicit type conversion.

––––––––

image

Point to Note

Python cannot, however, convert numerical data types into string data type or string data type into numerical data type implicitly. Attempting such a conversion will generate an error.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=432    #lower data type

number_str=”241”  #higher data type

print(“The type of data of number_int-“, type(number_int))

print(“The type of data of number_str-“, type(number_str))

print(number_int+number_str)

Challenge: Can you guess why this is occurring? Python interpreter is unable to understand whether we want concatenation or addition precisely. When it assumes the concatenation, it fails to locate the other string. When it assumes the addition approach, it fails to locate the other number. The solution to the error above is to have an explicit type conversion.