萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 條件判斷完整教學:if / else / elif 多重條件與模擬 switch-case

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

if-else 語法

if expression:
    statement(s)
else:
    statement(s)

if-elif-else 語法

if expression1:
    statement(s)
elif expression2:
    statement(s)
elif expression3:
    statement(s)
else:
    statement(s)

流程圖

if-else 流程圖

範例 1:基本 if-else

#!/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!

範例 2:elif 多重條件與模擬 switch-case

#!/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 鏈或字典映射替代。

copyright © 萬盛學電腦網 all rights reserved