0

I just got really confused by this code:

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")

However, look at the error: https://i.sstatic.net/PYT80.png

Someone told me to try try/except in Python, though after looking at the documentation, I have no idea what to do and how to implement it with all the other ifs and elifs in the code. I tried doing this:

print("Welcome to Healthometer, powered by Python...")
try:
    miles = float(input("How many miles can you walk? "))
except ValueError:
    print("That is not a valid number of miles")

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")

But it gave: line 7, in if float(miles) <= 0: NameError: name 'miles' is not defined

I am using Python 3.3.2

7
  • You just posted this question already and they did tell you how to use it. stackoverflow.com/questions/19736589/… Commented Nov 1, 2013 at 23:12
  • Yes they did but not how to implement it in the code! Commented Nov 1, 2013 at 23:13
  • I got a whole load of errors when I put it in the code. Commented Nov 1, 2013 at 23:14
  • You're getting this "That is not a valid number of miles" right ? Commented Nov 1, 2013 at 23:16
  • @jeremynealbrown: Please could you write it as an answer and give the corrected code. Thanks a lot! Commented Nov 1, 2013 at 23:20

3 Answers 3

2

I answered on your other question, but I thought I might as well answer here too.

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
#Make sure not to put these in the loop, they go AFTER!!

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.

Edit:

To further explain, the reason you were getting the error NameError: name 'miles' is not defined is because the Try/Except would fail, and would not define miles as the input. Instead, it would print "Please type..." and then proceed to the ifs anyways.

That's why you need the loop. It makes your code keep trying to define miles until it succeeds, and only then does it break from the loop and go to the logic.

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

6 Comments

you still need to declare miles before the try/except other wise the rest of the if statements will fail.
@jramirez Oh, really? I use python 2.7, and you don't need to in that version. Are you certain you need to in python 3.3?
@TimTimmy Sorry, I'm not sure what you're saying. What?
After much sweat and perspiration I have chosen your answer - Be warned - -I may choose another one if it is better but yours is 3.3 Python!
@TimTimmy I just looked at this again, and realized I should mention something. Now that you have the check at the beginning, you will definitely have a valid number, so you don't need the else: section at the bottom of your code. You can save a bunch of space and make your code clearer if you simply remove that whole else section
|
1

What is happening probably is that you are falling into the except block therefore the miles variable is never getting declared and the rest of your code needs that variable. By adding the raise it will force your code to exit so that rest of the code never runs in case of a problem with the input.

try:
    miles = float(input("How many miles can you walk? "))
except Exception, e:
    print("That is not a valid number of miles")
    raise e

EDIT:

I see what you are tying to do now. This will make your code work as you intended. The way you are approaching this problem is not very good btw. You need to read more about how to handle user input.

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

3 Comments

What does the 'e' stand for?
e is an instance of the Exception
I am staring at a screen full of code I do not understand. :( WHat is the Value Error? WHat is the point of Miles = None? Sorry for wasting your time!
0

If the input is invalid, the except statement is executed and yet your script continues beyond that. You have a couple of options. You could tell python to exit the application using sys.exit() or you could implement some other behavior such as telling the user to try again or defaulting to some hardcoded value.

Use exit like so:

import sys

try:
    miles = float(input("How many miles can you walk? "))
except Exception, e:
    print("That is not a valid number of miles")
    sys.exit()

Or you could ask the user to try again:

miles = None
def ask():
    global miles
    try:
        miles = float(input("How many miles can you walk? "))
    except: 
        print("Invalid input, try again")
        ask()

ask()
# remaining code here

4 Comments

So hard - jeremynealbrown or jramirez as the accepted answer? If I chose one of you, the other will not be happy with me!
Consider your end user. Are they going to understand the output of an exception or a friendly message and the application just closing?
No need to be sorry. All of the answers are very similar. It pretty much comes down to a matter of taste. Hope you enjoy learning Python!
A very polite comment indeed. Thank you for your cooperation.

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.