I'm just starting out with Python 2.7 and I don't understand why something is happening:
In the following code, an embellished version of an example from the python 2.7.2 tutorial, I get an unexpected result:
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was not a valid number. Try again..."
else:
print 'Thanks,',x,'is indeed an integer'
finally:
print 'all done, bye'
When I put in an integer, the code ignores the else:
statement and cuts straight to finally:
. Clearly it's something to do with the while True:
at the top but why is it happening?
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
In Java, using a try block inside another try block is permitted. It is called as nested try block.
One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.
The break statement is pulling out of the loop, so the else statement will never be reached.
Put the break in the else clause instead, like so:
while True:
try:
x = int(raw_input("Please enter a number: "))
except ValueError:
print "Oops! That was not a valid number. Try again..."
else:
print 'Thanks,',x,'is indeed an integer'
break
print 'all done, bye'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With