Confusing python - Cannot convert string to float

后端 未结 4 2217
小蘑菇
小蘑菇 2020-12-11 14:11

I got a value error and even if I try playing around with the code, it doesn\'t work!

How can I get it right? - I am using Python 3.3.2!

Here is the code:

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 15:00

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

    • If you have a string with only numbers, python's smart enough to do what you're 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 won't be able to get back to you for a while, so I'll 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 code's 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, it'll break from the loop and go to the code you put lower down.

提交回复
热议问题