Turbo
Turbo

Reputation: 323

Implementation of try/except in Python?

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

Upvotes: 0

Views: 636

Answers (3)

Matt Reynolds
Matt Reynolds

Reputation: 807

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.

Upvotes: 2

JeremyFromEarth
JeremyFromEarth

Reputation: 14354

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

Upvotes: 0

jramirez
jramirez

Reputation: 8685

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

Upvotes: 1

Related Questions