-8

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")
5
  • 6
    what is the answer to float("I have no idea") ? Commented Nov 1, 2013 at 22:44
  • 1
    Please show code as text and not as graphics - it allows others to use and run the code Commented Nov 1, 2013 at 22:45
  • @JoranBeasley: the "else" bit to the bottom Commented Nov 1, 2013 at 22:45
  • Why has it been voted down four times? I corrected everything. Commented Nov 1, 2013 at 22:50
  • 1
    lol i like the spray paint effect Commented Feb 7, 2014 at 20:55

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

Amazing answer! Try looking at how to implement all this: stackoverflow.com/questions/19736880/…
@TimTimmy Check this link out, see if that gets you there. If not, leave another comment and I'll edit my answer here instead of branching the question to another post: tutorialspoint.com/python/python_exceptions.htm
@TimTimmy Nevermind, I won't be able to get back to you for a while so I put the code in my answer just in case.
"If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a " is so annoying — I'm trying to load housing IDs which are all numbers, and Python tries to apply a ton of magic to turn them into floats, and using str() doesn't help
2

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 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.

Comments

1

The point here it can not convert alphanumeric strings, in some cases if you are scraping data or something like $400, $ symbol is alphanumeric then it consider an string, if you try convert to float it display an error, i give you this example to show it only convert numbers to float, in this case i solved the problem like this data ='$400', price = data[1:], then if , if (float(price) < 300): and it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.