python - while(i%3)该怎么理解?
ringa_lee
ringa_lee 2017-04-18 10:13:14
0
10
2753

在看慕课的课程,有段代码为:

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

while后面的条件要为真,才能够执行代码块,但是i%3这个代表了什么条件呢?

ringa_lee
ringa_lee

ringa_lee

reply all(10)
Peter_Zhu

% The remainder operator is to see whether the latter is divisible by the former. The condition i%3 is to determine whether i is divisible by 3, so there are only two results: 0 or 1! For example, 9%3 = 0 10%3 = 1. Basic operators, the author can check more information, thank you

PHPzhong

A problem left over from history, 0 is false, non-0 is true, so while(i%3)等价于while(i%3 != 0).

小葫芦

First of all, let’s look at the condition of the while statement (i % 3). This upstairs explained that % means to find the remainder, i% 3 means to find the remainder of i divided by 3, so the while condition means to divide i 3 The remainder must be greater than 0.
Now we know that the value of i is 1, so the while condition is established, output 1, after i++, the value of i is 2. At this time, the while condition is also satisfied and the loop outputs 2,
then i++, at this time The value of i is 3 and does not meet the condition. The while loop will not be executed and will jump out.

阿神

As the questioner asked, the condition after while must be true to execute the code block. If the value of i%3 is 0, it is false and the following code block will not be executed. If it is not 0 (1 and 2), It is equivalent to true, and the subsequent code block is executed. The if statement is also the same. If the conditional statement is 0, it is false, and it is not executed; if it is non-0, it is true, and it is executed. hope this helps!

Ty80

i%3的结果难道不是获取余数么?比如i=3结果是0 i=5结果是2 而在做条件判断的时候会自动转成布尔类型,所以不能被3整除的才能进行运算,因此不管是1还是2都是可以进去,所以这题应该是求得找出10以内不能被3整除的数吧?

刘奇

Simple while(i%3) means that when i is divisible by 3, skip the loop.

刘奇
while (i % 3) { /* ... */ }

is equivalent to

while (i % 3 != 0) { /* ... */ }

i % 3 是模除(modulo)运算,对于整数操作数 ab 满足 a / b * b + a % b == a in

python

if and only if a 整除 b 时,a % b == 0.

So the condition for loop termination is i 整除 3

大家讲道理
while(i%3) 

means that the loop stops when i can be divided by 3. 0 is false, and non-0 is true. This is what it means. When i%3==0, there is no loop.

巴扎黑

i%3 Modulo calculation, there are three situations: 0 1 2 The true or false judgment of a value follows NaN undefined null 0 "" false, all are false, and the rest are true. At this time, when the modulus is 0, it is false, so Will not enter this cycle.

大家讲道理

When i loops until it is divisible by 3, break out of the loop

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template