3.Booleans and Conditionals
Booleans
Python有bool類型數(shù)據(jù),有兩種取值:True 和 False.
[1]
x = True print(x) print(type(x)) True <class 'bool'>我們通常從布爾運(yùn)算符中獲取布爾值,而不是直接在我們的代碼中放入True或False。 這些是回答yes或no的運(yùn)算符。 我們將在下面介紹其中一些運(yùn)算符。
Comparsion Operations
| a == b | a equal to b | ? | a != b | a not equal to b |
| a < b | a less than b | ? | a > b | a greater than b |
| a <= b | a less than or equal to b | ? | a >= b | a greater than or equal to b |
[2]
def can_run_for_president(age):"""Can someone of the given age run for president in the US?"""#The US constitution says you must "have attained to the Age of the thirty-five years"return age >= 35print("Can a 19-year-old run for president?", can_run_for_president(19))print("Can a 45-year-old run for president?", can_run_for_presidnet(45)) Can a 19-year-old run for president? False Can a 45-year-old run for president? True比較運(yùn)算有點(diǎn)聰明......
[3]
3.0 == 3 True但不是很聰明...
[4]
'3' == 3 True比較運(yùn)算符可以與我們已經(jīng)看到的算術(shù)運(yùn)算符組合,以表達(dá)無限的數(shù)學(xué)測試范圍。 例如,我們可以通過模2運(yùn)算來檢查數(shù)字是否為奇數(shù):
[5]
def is_odd(n):return (n % 2) == 1print("Is 100 odd?", is_odd(100)) print("Is -1 odd?", is_odd(-1)) Is 100 odd? False Is -1 odd? True在進(jìn)行比較時,請記住使用==而不是=。 如果你寫n == 2,你會問n的值是否與2相等。 當(dāng)你寫n = 2時,你正在改變n的值。
Combining Boolean Values
Python使用“and”,“or”和“not”的標(biāo)準(zhǔn)概念組合布爾值的運(yùn)算符。 事實(shí)上,相應(yīng)的Python運(yùn)算符只使用這些單詞:and,or ,not。
有了這些,我們可以使我們的can_run_for_president函數(shù)更準(zhǔn)確。
[6]
def can_run_for_president(age, is_natural_born_citizen):"""Can someone of the given age and citizenship status run for president in the US?"""# The US Constitution says you must be a natural born citizen *and* at least 35 years oldprint(can_run_for_president(19, True))print(can_run_for_president(55, False))print(can_run_for_president(55, True)) False False True你能猜出這個表達(dá)式的值嗎?
[7]
True or True and False TurePython具有優(yōu)先級規(guī)則,用于確定在上述表達(dá)式中運(yùn)算的順序。 例如,and優(yōu)先級高于or,這就是上面第一個表達(dá)式為True的原因。 如果我們從左到右對它進(jìn)行運(yùn)算,我們首先計(jì)算True或True(即True),然后計(jì)算and False,得到最終值為False。
您可以嘗試記住優(yōu)先順序,但更安全的選擇是使用自由括號。 這不僅有助于防止錯誤,還可以使您的意圖更清晰,任何人都可以閱讀您的代碼。
例如,請考慮以下表達(dá)式:
我會說今天的天氣很安全....
- ???? 如果我有一把傘......
- ???? 或者雨下的不是很大,我有一個帽子.....
- ???? 否則,我仍然很好,除非正在下雨,這但是一個工作日
但不僅僅是我的代碼很難閱讀,還有一個問題,我們可以通過添加一些括號來解決這兩個問題。
prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)你還可以添加更多的括號,如果你認(rèn)為這有助于可讀性:
prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday))我們也可以將它拆分成多行來強(qiáng)調(diào)上面描述的3部分結(jié)構(gòu):
prepared_for_weather = (have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday)) )Conditionals
雖然它們本身就足夠有用,但是當(dāng)與條件語句結(jié)合使用時,使用關(guān)鍵字if,elif和else,布爾語句真的開始閃耀。
條件語句(通常稱為if-then語句)允許程序員根據(jù)某些布爾條件執(zhí)行某些代碼段。 Python條件語句的基本示例是:
[8]
def inspect(x):if x == 0:print(x, "is zero")elif x > 0:print(x, "is positive")elif x < 0:print(x, "is negative")else:print(x, "is unlike anything I've ever seen...")inspect(0) inspect(-15) 0 is zero -15 is negativePython采用經(jīng)常用于其它語言的if和else; 它更獨(dú)特的關(guān)鍵詞是elif,是“else if”的縮寫。 在這些條件子句中,elif和else塊是可選的; 此外,您可以包含任意數(shù)量的elif語句。
請?zhí)貏e注意使用冒號(:)和空格來表示單獨(dú)的代碼塊。 這與我們定義函數(shù)時發(fā)生的情況類似 - 函數(shù)頭以:結(jié)尾,后面的行用4個空格縮進(jìn)。 所有后續(xù)的縮進(jìn)行都屬于函數(shù)體,直到我們遇到一條未縮進(jìn)的行,結(jié)束函數(shù)定義。
[9]
def f(x):if x > 0:print("Only printed when x is positive; x = ", x)print("Also only printed when x is positive; x = ", x)print("Always printed, regardless of x's value; x = ", x)f(1) f(0) Only printed when x is positive; x = 1 Also only printed when x is positive; x = 1 Always printed, regardless of x's value; x = 1 Always printed, regardless of x's value; x = 0Boolean conversion
我們已經(jīng)看到了int(),它將事物變成了int,而float()將事物變成了浮點(diǎn)數(shù),所以你可能不會驚訝于Python有一個bool()函數(shù)可以將事物變成bool。
[10]
print(bool(1)) # all numbers are treated as true, except 0 print(bool(0)) print(bool("asf")) # all strings are treated as true, except the empty string "" print(bool("")) # Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples) # are "falsey" and the rest are "truthy" True False True False如果條件語句和其他需要布爾值的地方,我們可以使用非布爾對象。 Python將隱式將它們視為相應(yīng)的布爾值:
[11]
if 0:print(0) elif "spam":print("spam") spamConditional expressions(aka 'ternary')
根據(jù)某些條件將變量設(shè)置為兩個值中的任何一個是一種常見的模式。
[12]
def quiz_message(grade):if grade < 50:outcome = 'failed'else:outcome = 'passed'print('You', outcome, 'the quiz with a grade of', grade)quiz_message(80) You passed the quiz with a grade of 80Python有一個方便的單行“條件表達(dá)式”語法來簡化這些情況:
[13]
def quiz_message(grade):outcome = 'failed' if grade < 50 else 'passed'print('You', outcome, 'the quiz with a grade of', grade)quiz_message(45) You failed the quiz with a grade of 45您可能會認(rèn)為這類似于許多其他語言中存在的三元運(yùn)算符。 例如,在javascript中,我們將上面的賦值寫為`var outcome = grade <50? 'failed':'passed'。 (說到可讀性,我認(rèn)為Python在這里是贏家。)
Your turn!
轉(zhuǎn)到練習(xí)筆記本,以獲得一些boolean和conditionals的實(shí)踐練習(xí)。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的3.Booleans and Conditionals的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017招行信用卡进度查询方法 到哪一步
- 下一篇: 使用tcpdump,adb进行手机抓包