View Single Post
  #1 (permalink)  
Old October 17th, 2015, 10:53 AM
Egalth Egalth is offline
Registered User
Points: 11, Level: 1
Points: 11, Level: 1 Points: 11, Level: 1 Points: 11, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2015
Posts: 3
Thanks: 2
Thanked 2 Times in 2 Posts
Default 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]
Reply With Quote
The Following User Says Thank You to Egalth For This Useful Post:
Yehuda Katz (June 26th, 2017)