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:
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")
The traceback means what it says on the tin.
float
can convert strings that look like valid decimals intofloat
s. It can't 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.You need to take into account that the user might not fill in a proper value:
A
try/except
handles theValueError
that might occur whenfloat
tries to convert the input to a float.The problem is exactly what the Traceback log says:
Could not convert string to float
The way most people would approach this problem is with a
try/except
(see here), or using theisdigit()
function (see here).Try/Except
Isdigit()
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.
The code's really simple: