if語句
基本語句結構
if 判斷條件1:
執行語句1……
elif 判斷條件2:
執行語句2……
elif 判斷條件3:
執行語句3……
else:
執行語句4……
只有當“判斷條件”的值是True的時候,才執行下面的執行語句。
那麼,在python中,怎麼知道一個判斷條件是不是真呢?可以通過一個內置函數bool()來判斷一個條件的結果True還是False。看看下面的例子
>>> bool("")
False
>>> bool(0)
False
>>> bool('none')
True
>>> bool(False)
False
>>> bool("False")
True
>>> bool(True)
True
>>> bool("True")
True
>>> bool(3>4)
False
>>> bool("b">"a")
True
>>> bool(not "")
True
>>> bool(not True)
False
在執行語句中,其實不一定非要把bool()寫上的。如同這樣:
>>> x = 9
>>> if bool(x>7): #條件爲True則執行下面的
... print "%d more than 7"%x
... else:
... print "%d not more than 7"%x
...
9 more than 7
>>> if x>7:
... print "%d more than 7"%x
... else:
... print "%d not more than 7"%x
...
9 more than 7
以上兩個寫法是等效的,但是,在實際的編程中,我們不用if bool(x>7)的格式,而是使用if x>7的樣式,還要特別提醒,如果寫成if (x>7),用一個括號把條件表達式括起來,是不是可以呢?可以,但也不是python提倡的。
>>> if (x>7): #不提倡這麼寫,這不是python風格
... print "%d more than 7"%x
...
9 more than 7
練習
下面就做一個練習,要求是:
- 接收任何字符和數字的輸入
- 判斷輸入的內容,如果不是整數是字符,就告訴給用戶;如果是小數,也告訴用戶
- 如果輸入的是整數,判斷這個整數是奇數還是偶數,並且告訴給用戶
在這個練習中,顯然要對輸入的內容進行判斷,以下幾點需要看官注意:
- 通過raw_input()得到的輸入內容,都是str類型
- 要判斷一個字符串是否是由純粹數字組成,可以使用str.isdigit()(建議看官查看該內置函數官方文檔)
下面的代碼是一個參考:
#! /usr/bin/env python
#coding:utf-8
print "請輸入字符串,然後按下回車鍵:"
user_input = raw_input()
result = user_input.isdigit()
if not result:
print "您輸入的不完全是數字"
elif int(user_input)%2==0:
print "您輸入的是一個偶數"
elif int(user_input)%2!=0:
print "您輸入的是一個奇數"
else:
print "您沒有輸入什麼呢吧"
特別提醒列爲,這個代碼不是非常完善的,還有能夠修改的地方,看官能否完善之?
再來一個如何?
已知一個由整數構成的list,從中跳出奇數和偶數,並且各放在一個list中。
請看官在看下面的參考代碼之前,自己寫一寫。
#!/usr/bin/env python
#coding:utf-8
import random
numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到隨機的list
odd = []
even = []
for x in numbers:
if x%2==0:
even.append(x)
else:
odd.append(x)
print numbers
print "odd:",odd
print "even:",even
用這個例子演示一下if在list解析中的應用。看能不能繼續改進一些呢?
可以將循環的那部分用下面的list解析代替
#!/usr/bin/env python
#coding:utf-8
import random
numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到隨機的list
odd = [x for x in numbers if x%2!=0]
even = [x for x in numbers if x%2==0]
print numbers
print "odd:",odd
print "even:",even
一個有趣的賦值--三元操作符
這裏說的有趣賦值是什麼樣子的呢?請看:
>>> name = "hiekay" if "hi" else "github"
>>> name
'hiekay'
>>> name = 'hiekay' if "" else "python"
>>> name
'python'
>>> name = "hiekay" if "github" else ""
>>> name
'hiekay'
總結一下:A = Y if X else Z
什麼意思,結合前面的例子,可以看出:
- 如果X爲真,那麼就執行A=Y
- 如果X爲假,就執行A=Z
x = 2 y = 8 a = "python" if x>y else "hiekay" a 'hu' b = "python" if x<y else "hiekay" b 'python'