+ 1

could someone explain this code for me(why it prints all the even numbers between 2 and 10)

for i in range(10): if not i % 2 == 0: print(i+1)

17th Jul 2019, 11:18 PM
kobrito
kobrito - avatar
2 Answers
+ 6
range(10) creates a list of integers starting from 0 to 9. The for-each loop iterates through this list of integers, and for those which are not even (not i%2==0), we print the result of this integer being incremented by 1 (print(i+1)). You can handtrace the code to get the results. not 0 % 2 == 0 false not 1 % 2 == 0 true print(1+1) 2 not 2 % 2 == 0 false not 3 % 2 == 0 true print(3+1) 4 ... not 9 % 2 == 0 true print(9+1) 10 By the complete sequence, you should get 2 4 6 8 10
18th Jul 2019, 1:03 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
A shorter way to write 'if not i % 2 == 0' is 'if i % 2'. 'if x' is the same as 'if x == True'. Since 0 is False and all other numbers are True, 'if x' means 'if x is any number other than 0' , i.e. 'if x != 0', which is the same as 'if not x == 0'. So here, 'if i % 2' is the same as 'if not i % 2 == 0'. Generally, writing Python code that is simple and direct is considered 'Pythonic', so saying 'if i % 2' is more Pythonic than saying 'if not i % 2 == 0'.
18th Jul 2019, 7:04 AM
David Ashton
David Ashton - avatar