SOMEONEE
SOMEONEE

Reputation: 11

ValueError: could not convert string to float

So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get...

ValueError: could not convert string to float

I don't know what the problem is, I've tried using raw_input but it doesn't work ether. Please keep in mind I'm green and am not aware of most methods for getting around a problem like this

num1 = float(input ()) #take a float and store it
chars = input () #take a string          and store it
num2 = float(input ())

Upvotes: 1

Views: 5226

Answers (2)

Barry Meijer
Barry Meijer

Reputation: 760

I think this is happening because in some cases 'input' contains non-numerical characters. Python is smart and when a string only contains numbers, it can be converted from string to float. When the string contains non-numerical characters, it is not possible for Python to convert it to a float.

You could fix this a few ways:

  1. Find out why and when there are non-numerical characters in your input and then fix it.
  2. Check if input contains numbers only with: isdecimal()
  3. Use a try/except

isdecimal() example:

my_input = raw_input()
if my_input.isdecimal():
    print("Ok, go ahead its all numbers")

UPDATE: Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer.

Upvotes: 0

Anand Tripathi
Anand Tripathi

Reputation: 16196

your code only convert string that are integers like in below statement

num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0

if you provide 13 as a input it will give the output as 13.0 but if you provide SOMEONEE as input it will give ValueError

And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function

Upvotes: 2

Related Questions