[Tutor] try except continue
tpc247@gmail.com
tpc247 at gmail.com
Mon Aug 1 23:00:51 CEST 2005
hi guys, so I've been running through Alan's code, and for a while I
suspected that the try block must be the first line of code after the
loop in order to be executed. The reason I say this is I wanted to
see for myself Alan's assertion that the continue skips to the next
iteration, instead of continuing with the rest of the try block, so I
did the following:
def f():
if error:
raise ValueError
else:
print "I'm in f()"
def g():
print "I'm in g()"
def h():
error = True
print "error is: ", error
n = 5
while n:
print "n is: ", n
n -= 1
try:
f()
g()
except ValueError:
error = False
continue
and I got the following as output:
>>> h()
error is: True
n is: 5
n is: 4
n is: 3
n is: 2
n is: 1
I gathered that since I didn't see the output of f() and g(), then
those two functions must have never executed, and thus the try block
must have never executed. However, when I moved the try block to be
the first line after the loop:
def h():
error = True
print "error is: ", error
n = 5
while n:
try:
f()
g()
except ValueError:
error = False
continue
print "n is: ", n
n -= 1
I got the following as output:
>>> h()
error is: True
Traceback (most recent call last):
File "<pyshell#365>", line 1, in -toplevel-
h()
File "<pyshell#364>", line 9, in h
except ValueError:
KeyboardInterrupt
and I actually had to press Ctrl-C to stop the never terminating
program. I simply wanted to confirm Alan's assertion that continue
will cause the loop to skip to the next iteration, but it seems I
can't seem to get my f() and g() to print even though they were able
to before. Am I doing something wrong ?
More information about the Tutor
mailing list