简体   繁体   English

有关if的简单python代码

[英]A simple python code about if

Under python 2 在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

I notice the difference of those two results but I still don't understand what does if j mean. 我注意到这两个结果的区别,但是我仍然不明白如果j是什么意思。

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

The above if statements makes sure that i and j are not printed when the value of j is zero. 上面的if语句确保当j的值为零时不打印i和j。 Most datatypes have intrinsic boolean property in Python. 大多数数据类型在Python中都具有固有的布尔属性。 for numbers any non-zero values translates to True while zero translates to False 对于数字,任何非零值都转换为True,而零则转换为False

Python Documentation on truth testing: 关于真相测试的Python文档:

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

Specifically: 特别:

Any object can be tested for truth value, for use in an if or while condition. 可以测试任何对象的真值,以便在if或while条件下使用。 The following values are considered false: 以下值为“假”:

zero of any numeric type, for example, 0, 0L, 0.0 任何数字类型的零,例如0、0L,0.0

All other values are considered true 所有其他值都被认为是正确的

if j: will trigger when j is non-zero and do nothing when j is 0. if j:将在j非零时触发,而在j为0时不执行任何操作。

To understand what happened in if i: , try this. 要了解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

output: 输出:

-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

It checks if j is True. 它检查j是否为True。 Numerical value of 0 is interpreted as False and every other as True. 数值0解释为False,其他解释为True。

第二个循环以j为条件,如果j不为假,即j <> 0,则仅打印j不等于0的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM