惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
T
The Blog of Author Tim Ferriss
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
L
LangChain Blog
博客园_首页
Vercel News
Vercel News
月光博客
月光博客
B
Blog RSS Feed
S
SegmentFault 最新的问题
博客园 - Franky
C
Check Point Blog
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
F
Fortinet All Blogs
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
罗磊的独立博客
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学

博客园 - ________囧丶殇

django系列 - 安装和新建项目 SQL - 基础 javascript刷新父页面 SQL - 约束 C语言(8) - 反转单向链表 C语言(7) - 数据结构之单向链表 C语言(6) - 各种排序算法的比较 C语言(5) - 选择排序 快速排序 C语言(4) - 插入排序 C语言(3) - 冒泡排序 归并排序 C语言(2) - 从指针开始 C语言(1) - 开始之前 python实践 - 抓取网页中的图片和数据 python实践 - 下载文件 python补充(2) - 内置函数 python补充(1) python笔记(十) - 异常和文件处理 python笔记(九) - 类 part2 python笔记(八) - 类 part1
python笔记(七) - and和or
________囧丶殇 · 2009-04-27 · via 博客园 - ________囧丶殇

使用 and 时,在布尔上下文中从左到右演算表达式的值。0、''、[]、()、{}、None 在布尔上下文中为假;其它任何东西都为真。如果所有的值都为真,or 返回最后一个真值。

>>> 'a' and 'b'         
'b'
>>> '' and 'b'          
''
>>> 'a' and 'b' and 'c' 
'c'

 使用 or 时,在布尔上下文中从左到右演算值,就像 and 一样。如果有一个值为真,or 立刻返回该值。

如果所有的值都为假,or 返回最后一个假值。

>>> 'a' or 'b'          
'a'
>>> '' or 'b'           
'b'
>>> '' or [] or {}      
{}
>>> def sidefx():
      
print "in sidefx()"
      
return 1
>>> 'a' or sidefx()     
'a'

python中的a?b:c技巧

>>> def main(syng):
    
print syng and "first" or "second"
>>> main(1)
first
>>> main(0)
second
>>> 

 and-or 技巧无效的场合

>>> def main(syng):
    
print syng and "" or "second"
>>> main(1)
second
>>> main(0)
second
>>> 

 安全使用 and-or 技巧

>>> def main(syng):
    
print (syng and [""or ["second"])[0]
>>> main(0)
second

>>> main(1)

>>>