+ 2

For loop question

This is the 2nd question in the module 2 quiz, and I am at a loss for whats happening here. Why is it printing all the even numbers between 2 and 10? for i in range(10): if not i % 2 == 0: print(i+1)

14th Jan 2020, 1:54 AM
Wes Fletcher
Wes Fletcher - avatar
5 Réponses
+ 3
Here's an explanation. We're going through a for loop 10 times, starting from 0. Each time, we're checking the modular value of the loop number(getting the remainder of a number divided by a number, symbolized by %). If it doesn't return 0(if it can't be divided by 2), then it will print itself plus 1. So, let's say we're in the third iteration. 3 % 2 returns one, which is not equal to zero. Because of this, it will return 3 + 1, or 4.
14th Jan 2020, 1:59 AM
Jianmin Chen
Jianmin Chen - avatar
+ 6
for i in range(10): ### The variable i takes on 10 ### different numbers: ### 0, 1, 2, 3, 5, 6, 7, 8, 9 if not i % 2 == 0: ### Every i gets checked, if it can ### be cleanly divided by two, ### without leaving a remainder. ### Would be true for 0, 2, 4, 6, 8. ### ⚠️ But the condition is ### negated. ⚠️ ### So *not* cleanly divisible and ### thus filtering ### 1, 3, 5, 7, 9 instead. print(i+1): ### 1 is added to each filtered ### number from above and gets ### printed on a new line: ### print(1+1) ### print(3+1) ### print(5+1) ### ... and so on ...
15th Jan 2020, 5:13 PM
FeNneK
FeNneK - avatar
+ 2
if not i % 2==0 means 1,3,5,7,9 And +1 value is printing means 1+1,3+1,5+1,7+1,9+1
14th Jan 2020, 1:58 AM
Prathvi
Prathvi - avatar
0
hi
16th Jan 2020, 11:02 AM
Rizwan Usmani
Rizwan Usmani - avatar
- 2
i starts from 0 and stops till 9 If not 0==0 is not True is False If not 1==0 is not False is True So the condition executes and prints 2 Similarly it prints 4 6 8 10
14th Jan 2020, 3:02 AM
monica
monica - avatar