Exercise 27python
本節介紹True 和 False,即布爾值,無代碼less
①記憶真值表ide
Exercise 28spa
本節主要是掌握布爾代數運算code
①布爾運算,先計算括號,而後是等號、不等號等運算,再計算not,最後計算and和orci
②Python布爾操做符還包括:< 小於號input
> 大於號 it
<= 小於等於class
>= 大於等於 im
<> 不等於,將逐漸被棄用,主流是 !=
③Python布爾運算短路邏輯:任何以 False 開頭的 and 語句都會直接被處理成 False 而且不會繼續檢查後面語句了。任何包含 True 的 or 語句,只要處理到 True 這個字樣,就不會繼續向下推算,而是直接返回 True 了。不過仍是要確保整個語句都能正常處理,以方便往後理解和使用代碼。
Exercise 29
代碼
people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs."
輸出
Notes:
①本節開始引入if語句。注意if後的冒號和4個空格的縮進。
Exercise 30
代碼
people = 30 cars = 40 trucks = 15 if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We cann't decide." if trucks > cars: print "That's too many trucks." elif trucks < cars: print "Maybe we could take the trucks." else: print "We still can't decide." if people > trucks: print "Alright, let's just take the trucks." else: print "Fine, let's stay home then."
輸出
Notes:
①elif語句提供if的分支塊
②當Python遇到第一個爲True的語句塊並執行後,自動忽略後面因此elif語句,跳過整個if模塊
③當因此句塊均不符合條件時,執行else語句塊。
Exercise 31
代碼
print "You enter a dark room with two doors. Do you go through door #1 or door #2?" door = raw_input(">") if door == "1": print "There is a giant bear here eating a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input(">") if bear == "1": print "The bear eats your face off. Good job!" elif bear == "2": print "The bear eats your legs off. Good job!" else: print "Well doing %s is probably better. Bear runs away." % bear elif door == "2": print "You stare into the endless abyss at Cthulhu's retina." print "1. Blueberries." print "2. Yellow jacket clothespins." print "3. Understanding revolvers yelling melodies." insanity = raw_input("> ") if insanity == "1" or insanity == "2": print "Your body survives powered by a mind of jello. Good job!" else: print "The insanity rots your eyes into a pool of muck. Good job!" else: print "You stumble around and fall on a knife and die. Good job!"
輸出
Notes:
①if語句中能夠繼續嵌套if,引導進入不一樣的分支