and和or / and & or
对于and和or,可以连接多个值,其分别遵循原则:
- 全是 And: 返回第一个遇到的无效值,若全有效,返回最后一个有效值
- 全是 Or: 返回第一个遇到的有效值,若全无效,返回最后一个无效值
- 混用 And & Or: 优先对所有 and 进行计算,随后计算所有 or,计算规则同上。
1 print(1 and 0 and 2) # 0 2 print(1 and 2 and 3) # 3 3 print(0 or 1 or 0) # 1 4 print(0 or ‘‘ or None) # None 5 # Equal to (1 and 0) or (3 and 2 and 4) or (None and 5) 6 print(1 and 0 or 3 and 2 and 4 or None and 5) # 4
可以利用这些特性进行一些狡猾的处理,例如print出有效内容,内容无效则显示自定义的字符串。
可参考下面的代码
1 """ 2 The return of ‘and‘ and ‘or‘ 3 As for ‘or‘, it will return the first valid one, if all invalid, return the last invalid one 4 As for ‘and‘, it will return the first invalid one, if all valid, return the last valid one 5 """ 6 class Foo(): pass 7 8 def foo(): pass 9 10 valid = [7, True, (7,), [7], {‘7‘: 7}, foo, Foo] 11 invalid = [0, None, False, ‘‘, (), [], {}] 12 13 # ‘or‘: Invalid or Valid --> return the first valid one 14 print(‘----Below is Invalid or Valid----‘) 15 for iv in invalid: 16 print(iv or ‘Valid‘ or ‘Real‘) 17 18 # ‘or‘: Invalid or Invalid --> return the last invalid one 19 print(‘----Below is Invalid or Invalid----‘) 20 for iv in invalid: 21 print(iv or None or False) 22 23 # ‘or‘: Valid or Valid --> return the first valid one 24 print(‘----Below is Valid or Valid----‘) 25 for vl in valid: 26 print(vl or ‘Valid‘) 27 28 # ‘and‘: Invalid and Valid --> return the first invalid one 29 print(‘----Below is Invalid and Valid----‘) 30 for iv in invalid: 31 print(iv and ‘Valid‘ and ‘Real‘) 32 33 # ‘and‘: Valid and Valid --> return the last valid one 34 print(‘----Below is Valid and Valid----‘) 35 for vl in valid: 36 print(vl and 7 and True) 37 38 # ‘and‘: Valid or Invalid --> return the first invalid one 39 print(‘----Below is Valid and Invalid----‘) 40 for vl in valid: 41 print(vl and None and False) 42 43 print(‘----Below is tricky print----‘) 44 # We can use it to make a tricky print 45 for iv in invalid: 46 print(‘I have %s‘ % (iv or ‘None‘)) 47 for vl in valid: 48 print(‘I have %s‘ % (vl or ‘None‘))
和输出结果
----Below is Invalid or Valid---- Valid Valid Valid Valid Valid Valid Valid ----Below is Invalid or Invalid---- False False False False False False False ----Below is Valid or Valid---- 7 True (7,) [7] {‘7‘: 7} <function foo at 0x02F7F930> <class ‘__main__.Foo‘> ----Below is Invalid and Valid---- 0 None False () [] {} ----Below is Valid and Valid---- True True True True True True True ----Below is Valid and Invalid---- None None None None None None None ----Below is tricky print---- I have None I have None I have None I have None I have None I have None I have None I have 7 I have True I have 7 I have [7] I have {‘7‘: 7} I have <function foo at 0x02F7F930> I have <class ‘__main__.Foo‘>