Reputation: 11
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
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:
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
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