Implementation Of Try/except In Python?
Solution 1:
I answered on your other question, but I thought I might as well answer here too.
whileTrue:
try:
miles = float(input("How many miles can you walk?: "))
breakexcept:
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 if
s 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.
Solution 2:
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 = Nonetry:
miles = float(input("How many miles can you walk? "))
except ValueError:
print("That is not a valid number of miles")
Solution 3:
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 = Nonedefask():
global miles
try:
miles = float(input("How many miles can you walk? "))
except:
print("Invalid input, try again")
ask()
ask()
# remaining code here
Post a Comment for "Implementation Of Try/except In Python?"