0
Python question
The question is as follows: For i in range(1,5): print(i%3) It says the output is 1201, and I am completely clueless as to why? Could anyone help out?
3 Antworten
+ 7
The "for in" loop goes over the variable i from 1 to before 5, so...
First: i % 3 would be 1 % 3, 3 goes into 1, 0 times and then the remainder is "1".
Second: i % 3 would be 2 % 3, 3 goes into 2, 0 times and then the remainder is "2".
Third: i % 3 would be 3 % 3, 3 goes into 3, 1 time and there is no remainder so that results in "0".
Fourth: i % 3 would be 4 % 3, 3 goes into 4, 1 time and there is a reminder of "1".
Then that is the end of the loop so looking at all 4 outputs that would be "1201"
EDIT:
No Problem 🙂
+ 7
The output is
1
2
0
1
which is correct.
The 'for' loop (note the small 'f'!) iterates through range(1,5), i.e. it processes the integers 1, 2, 3 and 4.
For each of those numbers, i%3 is printed on a separate line.
% is the modulo operator, which can be thought of as the remainder after a division.
1%3 is calculated like this: 3 goes into 1 zero times with 1 left over, so 1%3 is 1
2%3 : 3 goes into 2 zero times with 2 left over, so 2%3 is 2
3%3 : 3 goes into 3 1 time with 0 left over, so 3%3 is 0
4%3 : 3 goes into 4 1 time with 1 left over, so 4%3 is 1
i.e. the answer is
1
2
0
1
Hope this helps :)
+ 1
Thanks David and LynTon!