Type Conversion

By | April 30, 2018

To write a good program you have to handle all the possible cases in the process of development. I need to get an input from user which needs to be an integer but user provided a float. How Python or programmer is going to handle such cases. So the topic is mainly of  Type conversion.

What is Type Conversion?

Let us break the words “Type” and “Conversion”. So it’s about conversion of one data type to another. We have two types of conversation.

  1. Implicit conversion – Developer/Programmer need not to involve, Python will do conversion from one type to another type. You need not to order your interpreter to do conversion.

    Here your interpreter did conversion of sum of two data types to float. Observe the same in output. We have already seen the purpose of type() in previous posts.

  2. Explicit Conversion:  Here you will order your interpreter to convert the data type of given conversion. Lets have a look at how it goes- We have some predefined functions to achieve this int(),float(), str() etc..

 int() – To convert float to int.

float()- To convert into float.

str()- To convert numbers to strings.

Lets look at code snippet:

Line 4 we are trying to add a int and string, So interpreter scolded us. Use type conversion here. Try below code:

#Explicit conversion or Type Casting
i_int=20
j_str=”70.8″
sum=i_int+float(j_str)
print(sum)
print(“Sum of int and float yields output as “,type(sum))

Output: 

90.8
Sum of int and float yields output as <class ‘float’>

Above code we have used float() function to change string to float. Do try other functions as well. Below code str() function used to convert integer into string. Output is concatenation of both the strings.

#Explicit conversion or Type Casting
i_int=100
j_str=”LearnModeOn”
print(str(i_int)+j_str)

  Output:

100LearnModeOn

If we are not using type casting we will end up with below error:

Try below conversions and comment us the output:

str(0)

int(’42’)

int(1.25)

float(10)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.