简体   繁体   中英

A simple python code about if

Under 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.

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. Most datatypes have intrinsic boolean property in Python. for numbers any non-zero values translates to True while zero translates to False

Python Documentation on truth 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. The following values are considered false:

zero of any numeric type, for example, 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.

To understand what happened in if i: , try this.

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. Numerical value of 0 is interpreted as False and every other as True.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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