关于if的简单python代码

时间:2014-03-25 12:44:07

标签: python if-statement for-loop double range

在python 2下

    for i in range(6):
        for j in range(i):print i,j

    for i in range(6):
        for j in range(i):
            if j:print i,j

我注意到这两个结果的区别,但我仍然不明白如果j意味着什么。

5 个答案:

答案 0 :(得分:1)

for i in range(6):
    for j in range(i):
        if j:print i,j

上述if语句确保当j的值为零时不打印i和j。 大多数数据类型在Python中都有内部布尔属性。对于数字,任何非零值都会转换为True,而零转换为False

答案 1 :(得分:1)

关于真值测试的Python文档:

http://docs.python.org/2/library/stdtypes.html#truth-value-testing

具体做法是:

  

可以测试任何对象的真值,以便在if或while中使用   条件。以下值被视为false:

     

任何数字类型的零,例如,0,0L,0.0

     

所有其他值都被视为真实

if j:将在j为非零时触发,在j为0时不执行任何操作。

答案 2 :(得分:1)

要了解if i:中发生的事情,请尝试此操作。

for i in range(-6,6):
    if i:
        print "%2d is evaluated as True"%i
    else:
        print "%2d is evaluated as False"%i

输出:

-6 is evaluated as True
-5 is evaluated as True
-4 is evaluated as True
-3 is evaluated as True
-2 is evaluated as True
-1 is evaluated as True
 0 is evaluated as False    <----- Just "if 0:" is evaluated as "if False:"
 1 is evaluated as True
 2 is evaluated as True
 3 is evaluated as True
 4 is evaluated as True
 5 is evaluated as True

答案 3 :(得分:0)

检查j是否为True。数值0被解释为False,而其他每个都被解释为True。

答案 4 :(得分:0)

如果j不是假的,则第二个循环是在j上进行调节,即如果j&gt; 0所以它只打印j不等于0的值