+ 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)
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.
+ 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 ...
+ 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
0
hi
- 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