Python 提供 if、else、elif 構建多重條件判斷。本文詳細說明語法、流程圖、範例,並示範如何用 if-elif 鏈模擬其他語言的 switch-case。
if expression:
statement(s)
else:
statement(s)
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
#!/usr/bin/python
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
print "Good bye!"
3 - Got a true expression value
100
Good bye!
注意: Python 無 switch-case,官方建議使用 if-elif 鏈或字典映射替代。