基本用法
判斷,基于一定的條件,決定是否要執行特定的一段代碼,例如判斷一個數是不是正數:
x = 0.5
if x > 0:
print("Hey!")
print("x is positive")
Hey!
x is positive
在這里,如果 x > 0 為 False ,那么程序將不會執行兩條 print 語句。
雖然都是用 if 關鍵詞定義判斷,但與C,Java等語言不同,Python不使用 {} 將 if 語句控制的區域包含起來。Python使用的是縮進方法。同時,也不需要用 () 將判斷條件括起來。
上面例子中的這兩條語句:
print ("Hey!")
print ("x is positive")
就叫做一個代碼塊,同一個代碼塊使用同樣的縮進值,它們組成了這條 if 語句的主體。
不同的縮進值表示不同的代碼塊,例如:
x = 0.5
if x > 0:
print("Hey!")
print("x is positive")
print("This is still part of the block")
print("This isn't part of the block, and will always print.")
Hey!
x is positive
This is still part of the block
This isn't part of the block, and will always print.
在這兩個例子中,最后一句并不是if語句中的內容,所以不管條件滿不滿足,它都會被執行。
一個完整的 if 結構通常如下所示(注意:條件后的 : 是必須要的,縮進值需要一樣):
if <condition 1>:
<statement 1>
<statement 2>
elif <condition 2>:
<statements>
else:
<statements>
當條件1被滿足時,執行 if 下面的語句,當條件1不滿足的時候,轉到 elif ,看它的條件2滿不滿足,滿足執行 elif 下面的語句,不滿足則執行 else 下面的語句。
值的測試
Python不僅僅可以使用布爾型變量作為條件,它可以直接在if中使用任何表達式作為條件:
大部分表達式的值都會被當作True,但以下表達式值會被當作False:
- False
- None
- 0
- 空字符串,空列表,空字典,空集合
mylist = [3, 1, 4, 1, 5, 9]
if mylist:
print("The first element is:", mylist[0])
else:
print("There is no first element.")
The first element is: 3
修改為空列表:
mylist = []
if mylist:
print("The first element is:", mylist[0])
else:
print("There is no first element.")
There is no first element.
然這種用法并不推薦,推薦使用 if len(mylist) > 0: 來判斷一個列表是否為空。