[Tutor] question about for loops
Richard D. Moores
rdmoores at gmail.com
Thu Jan 7 15:32:20 CET 2010
On Thu, Jan 7, 2010 at 05:03, Alan Plum <alan.plum at uni-koeln.de> wrote:
> Variable unpacking works like this:
>
> points = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]
>
> for (x,y) in points:
> print 'x: %d, y: %d' % (x, y)
>
> Without unpacking:
>
> for point in points:
> print 'x: %d, y: %d' % (point[0], point[1]) # point is a tuple
>
> Similarly consider this expression:
>
> (a, b) = (50, 100) # a = 50, b = 100
> c = (a, b) # c[0] = a, c[1] = b
>
> It's a really useful language feature if you're ever dealing with tuples
> that carry certain semantics (e.g. x, y and z coordinates in a point
> tuple) but don't want to create a new type.
>
>
> Hope that helps,
Certainly does. Thank you.
I did something like your 3rd example, in these lines from the script
I posted yesterday in the thread about the fractions module.
f = str(Fraction(str(r)).limit_denominator(100))
n, d = f.split('/')
num, denom = int(n), int(d)
fraction = num/denom
Dick Moores
More information about the Tutor
mailing list