简单的循环

2024-05-15 11:19:48 发布

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

我知道这听起来很傻,但我一辈子都搞不懂for循环返回13,11,9,7背后的逻辑。你知道吗

    for i in range(13,5,-1):
        if i % 2 != 0:
            print i

我知道第一个值是它开始的数字,第二个值是它停止的位置,第三个值是它所走的步数。“如果我%2!=0:“是什么把我甩了。有人能解释一下发生了什么事吗?你知道吗


Tags: inforifrange数字逻辑print步数
3条回答

第一位是range(13,5,-1),它只是从13向后计数到6。下一位是i%2 != 0i%2 == 0相当于说if even,或者“如果这个数字可以被2除而没有余数”,所以你的陈述是说“if odd”(这显然与“if not even”相同)。你知道吗

基本上,循环是从13开始打印奇数,然后减少到6(但是6是偶数,所以不能打印)

if i % 2 !=0

这条线的意思是“如果i除以2后的余数不等于0”,所以它检查i是否为奇数。for循环正在倒计时1,但是if语句跳过打印偶数。你知道吗

%是模运算符。从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.

相关问题 更多 >