Recap that strings are used to denote names, addresses, etc and floats are used to represent real numbers, Sometimes you might have input a value from a user which was intended to be a floating point variable but instead got stored as a string. You will need to convert it into a float inside your Python program. Let us learn how to do this!
First, let us create a program to obtain a floating point value from the user:
If we run this program, here is a sample interaction:
Note that the user’s input (which was “75”) is internally stored as a string so that when we print the type of the input, we obtain ‘str’ as the answer. This means we cannot do any arithmetic operations on it, like addition, subtraction, etc. We will need to convert it into a floating point value.
The way to convert a string to a float is to use the float() function, like so:
If we run the above program:
Note that the variable which was a string before is now a float, and reflects it in its value as 75.0.
This also means that we can input floating point values when queried:
Here, the 75.345 which used to be a string is converted to a float with the above value.
On the other hand, if we do:
We cannot map “hot” to a float using the float() function. The input to float() must be a string containing only numbers (and perhaps decimal points and negative signs).
As we have seen in this blogpost, it is extremely easy to convert a string to a float so that you can do arithmetic operations on the result which you could not do before.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.