x%2==0是什么意思?

2024-06-12 20:04:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信这是很基本的,我应该理解,但我不懂!

我要做的是:

循环并按接收顺序打印出数字列表中的所有偶数。不要按顺序打印237之后的任何数字。

这是我为这些数字准备的程序。

numbers = [
    951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 
    615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 
    386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 
    399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 
    815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 
    958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 
    743, 527
]

# your code goes here
for x in numbers:
    if x % 2 == 0:
        print x
    if x == 237:
        break

我得到了正确的解决方案,一切都很好,但是我不知道==0是为了什么。 我使用它的唯一原因是因为它在练习前的课程中被用在了另一个例子中!


Tags: in程序列表foryourifhere顺序
3条回答

== 0表示“等于0(零)”。因此if foo == 0:表示“如果foo等于0,则执行以下操作”,因此if x % 2 == 0:表示“如果x % 2等于0,则执行以下操作”。

if x % 2 == 0检查数字是否为偶数。

当数是奇数时,x % 21,当数是偶数时,0

x % 2给出x/2整除后的余数(在本例中仅处理整数时,否则为公共类型)。%称为模运算符。当然,当余数为0时,数字是偶数。

Docs

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

相关问题 更多 >