Open in TheBrain

FOR Loops List Comprehensions

<p>Feb 13, 2013 07:41 PM

&#160;

section 4.2 FOR statements... actually look at 4.4 &#160;PRIME NUMBER example!!

&#160;

&#62;&#62;&#62; for n in range(2, 10):

... for x in range(2, n):

... if n % x == 0:

... print n, 'equals', x, '*', n/x

... break

... else:

... # loop fell through without finding a factor

... print n, 'is a prime number'

...

2 is a prime number

3 is a prime number

4 equals 2 * 2

5 is a prime number

6 equals 2 * 3

</pre>

<p>&#160;

tonite this drove me nucking futz!

&#160;

note: &#160;for loop normally takes a : with the conditional above

HOWEVER it does NOT take a COLON in a &#160;LIST COMPREHENSION!

&#160;

see examples at 5. &#160;these work:

&#160;

&#62;&#62;&#62; numbers

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

&#62;&#62;&#62; numbers = [i for i in range(10) if i&#62;3]

&#62;&#62;&#62; numbers

[4, 5, 6, 7, 8, 9] &#160;and this works

&#160;

&#62;&#62;&#62; numbers = [i for i in range(10) if i%2==1]

&#62;&#62;&#62; numbers

[1, 3, 5, 7, 9]

&#160;

Note: &#160;do not put an indentation in a list comprehension... it won't work!non

&#160;

&#160;

&#160;</p>