Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

error handling - Confusing python - Cannot convert string to float

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: Code

As you can see, the program asks for how many miles you can walk and gives you a response depending on what you type in.

This is the code in text format:

print("Welcome to Healthometer, powered by Python...")
miles = input("How many miles can you walk?: ")
if float(miles) <= 0:
    print("Who do you think you are?!! Go and walk 1000 miles now!")
elif float(miles) >= 10:
    print("You are very healthy! Keep it up!")
elif float(miles) > 0 and miles < 10:
    print("Good. Try doing 10 miles")
else:
    print("Please type in a number!")
    miles = float(input("How many miles can you walk?: "))
    if miles <= 0:
        print("Who do you think you are?!! Go and walk 1000 miles now!")
    elif miles >= 10:
        print("You are very healthy! Keep it up!")
    elif miles > 0 and miles < 10:
        print("Good. Try doing 10 miles")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...