a, b, c = 1, 0, 2 d = a if b else c # 2 1 <= a < 2 # True, 1 < a and a <2 False == False == True # False, False == False and False == True or_val = 2 or 3 # 2 and_val = 2 and 3 # 3
Python and 和 or 表达式的返回值为表达式最后执行的值,如:2 and 3 and 1 - 1 的值为 0,因为,表达式最后执行的是 1 - 1。和 PHP 不一样,PHP 返回表达式的对错判断 true/1 或 false/0。
List Comprehensions - 列表推导式/列表解析
1 2 3 4 5 6
args = [ x**2 for x in range(-10, 10) if x > 0 ] # it is the same as: args = [] for x in range(-10, 10): if x > 0: args.append(x**2)
example2:
1 2 3 4 5 6 7
args = [(x, y) for x in range(1, 10) for y in range(6, 10) if x != y] # it is the same as: args = [] for x in range(1, 10): for y in range(6, 10): if x != y: args.append((x, y))
1 2 3
with open('xx', 'x') as fp: for line in iter(fp.readline, ''): # 遍历文件的每行直到为空 xxx
1 2 3 4
for i in range(10): print(i) else: print('The for is not completed')