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
print(“Sum of int and float yields output as “,type(sum))


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



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

Try below conversions and comment us the output:





Leave a Reply

Your email address will not be published.

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