View Single Post
October 17th, 2015, 11:53 AM
Egalth
Registered User
 Points: 11, Level: 1
 Activity: 0%

Join Date: Oct 2015
Posts: 3
Thanks: 2
Thanked 2 Times in 2 Posts
P19, "even squares", code error

On page 19, generator expressions are introduced. The following code from that page produces the expexted result in the form of a list of even squares:
Code:
```>>> [n*n for n in range(1,11) if not n*n % 2]
[4, 16, 36, 64, 100]```
At the bottom of the page there is an example of how to generate an identical result with a conventional for loop. However, the sample code produces odd integers, instead of even squares, because not and n*n are missing:
Code:
```>>> result = []
>>> for n in range(1,11):
...     if n*n % 2:              # Missing not
...         result.append(n)     # n instead of n*n
...
>>> print(result)
[1, 3, 5, 7, 9]```
This code produces the expected result:
Code:
```>>> result = []
>>> for n in range(1,11):
...     if not n*n % 2:
...         result.append(n*n)
...
>>> print(result)
[4, 16, 36, 64, 100]```
 The Following User Says Thank You to Egalth For This Useful Post: Yehuda Katz (June 26th, 2017)