error handling – Confusing python – Cannot convert string to float

error handling – Confusing python – Cannot convert string to float

You need to take into account that the user might not fill in a proper value:

try:
    miles = float(input(How many miles can you walk? ))
except ValueError:
    print(That is not a valid number of miles)

A try/except handles the ValueError that might occur when float tries to convert the input to a float.

The problem is exactly what the Traceback log says: Could not convert string to float

  • If you have a string with only numbers, pythons smart enough to do what youre trying and converts the string to a float.
  • If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.

The way most people would approach this problem is with a try/except (see here), or using the isdigit() function (see here).

Try/Except

try:
    miles = float(input(How many miles can you walk?: ))
except:
    print(Please type in a number!)

Isdigit()

miles = input(How many miles can you walk?: )
if not miles.isdigit():
    print(Please type a number!)

Note that the latter will still return false if there are decimal points in the string

EDIT

Okay, I wont be able to get back to you for a while, so Ill post the answer just in case.

while True:
    try:
        miles = float(input(How many miles can you walk?: ))
        break
    except:
        print(Please type in a number!)

#All of the ifs and stuff

The codes really simple:

  • It will keep trying to convert the input to a float, looping back to the beginning if it fails.
  • When eventually it succeeds, itll break from the loop and go to the code you put lower down.

error handling – Confusing python – Cannot convert string to float

The traceback means what it says on the tin.

>>> float(22)
22.0
>>> float(a lot)
Traceback (most recent call last):
  File <stdin>, line 1, in <module>
ValueError: could not convert string to float: a lot

float can convert strings that look like valid decimals into floats. It cant convert arbitrary alphanumeric strings, notably including How am I supposed to know?.

If you want to handle arbitrary user input, you have to catch this exception, with a try/except block.

Leave a Reply

Your email address will not be published. Required fields are marked *