詳解Python中的條件判斷語句
這篇文章主要介紹了Python中的條件判斷語句,是Python入門中的基礎知識,需要的朋友可以參考下
一個else語句可以使用if語句結合起來。如果在if語句中的條件運算式解析為0或false值,那麼else語句包含代碼執行。
else語句是可選的聲明,並if語句下面最多隻有一個else語句。
文法:
if ... else語句的文法是:
?
|
1
2
3
4 |
if expression:
statement(s)
else:
statement(s)
|
例子:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
#!/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
2
3
4
5 |
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
|
elif 語句
elif語句可以檢查多個運算式的真值,並執行一個代碼塊的條件之一計算結果為true。
if...elif 語句是可選的。然而不像else,對此可以有最多一個語句,if語句下邊可以有任意數量elif語句。
if...elif 語句的文法是:
?
|
1
2
3
4
5
6
7
8 |
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
|
Python核心不提供switch或case語句在其他語言,但我們可以用if..elif...語句來類比switch case如下:
例子
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
#!/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!"
|
當執行上面的代碼,產生以下結果:
?
|
1
2
3 |
3 - Got a true expression value
100
Good bye!
|