jstok at bluedog.apana.org.au
Tue Apr 18 18:41:56 CEST 2000
Daley, MarkX wrote in message ...
>This feels like a real newbie question, but here is the code that is
># Learning exceptions
> a = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
> print a
> b = 5
> for item in a:
> print b / a[item]
> except ZeroDivisionError:
Firstly, please retain correct indenting when posting code snippets.
Indenting is significant in Python. I've corrected it for you.
>Why is the list being processed in reverse? The exception works fine, but
>the math is backwards. I don't recall this happening before.
Iteration one binds to the name item the first element of a, which happens
to be -5.
You then try to divide b by a[item], which is a indexed by -5. Negative
indexes are legal in python and the effect is to return a reference to the
fifth element from the *right*.
In short, you've misapplied "for item in a" construct, which is very
different from the C construct. In Python it repeatedly binds the name
"item" to the next element of list "a", does the sub-block, then repeats
until there's no longer any elements left in a. You don't need to index a.
To do that, you'd do:
for i in range(0...len(a)):
print b / a[i]
But this will mark you with the stigma of a programmer hankering for his old
C days.... what you needed to write was merely:
for item in a:
print b / item
Jason Stokes: jstok at bluedog.apana.org.au
More information about the Python-list