Forums

Could not covert string to float

x = float(input("Please insert money: "))

Traceback (most recent call last):
File "/home/J2Carter/calc1.py", line 8, in <module>
x = float(input("Please insert money: "))
ValueError: could not convert string to float:

That happens when the user enters a string how can I fix that?

you could choose check if it is a string this way
if a == string:
do this

and then throw an error otherwise

use raw_input so it's always a string and doesn't have nasty code injection problems, and then int(x) to turn it into an integer, float(x) to turn it into a float etc

NB raw_input is Python 2 only. In Python 2, it's just input. How about something like this?

try:
    x = float(input("Please insert money: "))
except ValueError:
   print("error, that was not a number, please try again")