if语句通用格式
if <test1>:
<statements1>
else <test2>:
<statements2>
Python中没有switch case 语句。然而python,多路分支是写成一系列的if/elif测试,或者对字典进行索引运算或搜索列表。
if/elif:
if choic == 'spam':
print(1)
elif choice == 'ham':
print(2)
else:
print('bad choice')
字典:
choice = 'spam'
print({'spam':1,
'ham':2}[choice])
if and in:
choice = 'spam'
if choice in branch: #branch is an dict
print(branch[choice])
真值测试
敲黑板,布尔运算符在python中是字符and, or, not,不是C的&&,||和| 。此外,布尔and和or运算在python中会返回真或假对象,而不是True或False
>>> 2<3, 3<2
(True, False)
>>>
像这类值的比较会返回True or False作为其真值结果,但and or运算符会返回对象,不是运算符的左侧就是运算符的右侧对象。Python会在找到的第一个真值操作数地方停止,即短路计算。
if/else 三元表达式
if x:
A = Y
else:
A = Z
A = Y if X else Z
Learning Python, Fourth Edition, by Mark Lutz.