1

There is a quiz on Coursera that I cannot understand

i = 1
while i % 3: 
    print(i, end = ' ')
    if i >= 10:
        break
    i += 1

I expect the output is 1,2,3,4,5,6,7,8,9, but the actual output is 1 2. I do not understand what is 'while i % 3', can someone explain this?

Orbit
  • 36
  • 3

4 Answers4

2

The % (modulo) operator in python calculates the remainder from the division of the first number by the second.

E.G: 5 % 3 == 2

When i is incremented to 3 in your program, the result of 3 % 3 is 0.

In Python, 0 == False, so when i increments to 3 it will then no longer satisfy the while loop condition.

You can try this yourself, by doing:

while 0:
    print("Hello world!")
busybear
  • 10,194
  • 1
  • 25
  • 42
Farrago-Alex
  • 128
  • 8
0

This stackoverflow answer sums it up quite nicely: https://stackoverflow.com/a/961351/9822083

The % symbol in python means the Modulus operator - possibly more easily understood as the 'remainder'. I believe what you meant to say was 'i < 3'

Jett
  • 781
  • 1
  • 14
  • 30
0

% stands for the modulus operator.

Returns the decimal part (remainder) of the quotient.

https://python-reference.readthedocs.io/en/latest/docs/operators/modulus.html

while i % 3 keeps executing as long as i % 3 returns a value that is not 0, which for the first time is i = 3

>>> 1 % 3
1
>>> 2 % 3
2
>>> 3 % 3
0
Community
  • 1
  • 1
Saritus
  • 918
  • 7
  • 15
0

any integer number counts as a 'True' for a while loop and when a 'False' is hit the while loop stops. So that 'if' statement is actually useless or redundant in this code.

>>>1 % 3
1 - which means true
>>>3 % 3
0 - which means false so the while loop stops and doesn't even run

This then ends the loop as you increment i. All this before the if statement can even run 10 times. So response is 1,2.

David Raji
  • 16
  • 2