1. 程式人生 > >Python基礎知識(五)

Python基礎知識(五)

邏輯

邏輯術語

在 python 中我們會用到下面的術語(字元或者詞彙)來定義事物的真(True)或者假(False)。計算機的邏輯就是在程式的某個位置檢查這些字元或者變數組合在一起表達的結果是真是假。

and 與
or 或
not 非
!= (not equal) 不等於
== (equal) 等於
= (greater-than-equal) 大於等於
<= (less-than-equal) 小於等於
True 真
False 假

真值表

我們將使用下面這些字元來建立你需要記住的真值表:

NOT	        TRUE
not False	True
not True	False
OR	        TRUE?
True or False	True
True or True	True
False or True	True
False or False	False
AND	        TRUE
True and False	False
True and True	True
False and True	False
False and False	False
NOT OR	                TRUE
not (True or False)	False
not (True or True)	False
not (False or True)	False
not (False or False)	True
NOT AND	                TRUE
not (True and False)	True
not (True and True)	False
not (False and True)	True
not (False and False)	True
!=	TRUE
1 != 0	True
1 != 1	False
0 != 1	True
0 != 0	False
==	TRUE
1 == 0	False
1 == 1	True
0 == 1	False
0 == 0	True

布林邏輯表示式

先為下面的每一個邏輯問題寫出你認為的答案,每一題的答案要麼為True要麼為False。寫完以後,你需要將python執行起來,把這些邏輯語句輸入進去,確認你寫的答案是否正確。

True and True
False and True
1 == 1 and 2 == 1
"test" == "test"
1 == 1 or 2 != 1
True and 1 == 1
False and 0 != 0
True or 1 == 1
"test" == "testing"
1 != 0 and 2 == 1
"test" != "testing"
"test" == 1
not (True and False)
not (1 == 1 and 0 != 1)
not (10 == 1 or 1000 == 1000)
not (1 != 10 or 3 == 4)
not ("testing" == "testing" and "Zed" == "Cool Guy")
1 == 1 and (not ("testing" == 1 or 1 == 0))
"chunky" == "bacon" and (not (3 == 4 or 3 == 3))
3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))

結果

True
False
False
True
True
True
False
True
False
False
True
False
True
False
False
False
True
True
False
False

所有的布林邏輯表示式都可以用下面的簡單流程得到結果:

  • 找到相等判斷的部分 (== 或者 !=),將其改寫為其最終值 (True 或 False)。
  • 找到括號裡的 and/or,先算出它們的值。
  • 找到每一個not,算出他們反過來的值。
  • 找到剩下的 and/or,解出它們的值。
  • 等你都做完後,剩下的結果應該就是 True 或者 False 了。

常見問題
Q: 為什麼and 返回 "test"以及and 返回 1 而不是 True?

python和很多語言可以返回布林表示式中的一個運算元,而不僅僅是真或假。這意味著如果你計算False and 1 你會得到表示式的第一個運算元 (False) ,但是如果你計算True and 1的時候,你得到它的第二個運算元(1)。試一試吧。

Q:!=和 <>有什麼不同嗎?

Python已經宣告贊成使用!=而棄用<>所以儘量使用!=吧。其他的應該沒有區別了。

Q:有沒有捷徑去判斷布林表示式的值?

有的。任何的and表示式包含一個False結果就是False,任何or表示式有一個True結果就是True,你就可以在此處得到結果,但要確保你能處理整個表示式,因為後面這是一個很有用的技能。

IF 語句

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.")

結果

Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

常見問題
Q: +=表示什麼意思?

程式碼x += 1和x = x + 1 實現的是一樣的功能,但是可以少輸入一些字元。你可以稱之為“增量”操作符。-= 也是相同的。

Else 和 If

把下面這段寫下來,並讓它執行起來:

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 can'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.")

結果

We should take the cars.
Maybe we could take the trucks.
Alright, let's just take the trucks.

常見問題
Q: 如果多個elif塊為真,會怎樣?

Python的啟動和執行只會針對第一個為真的程式碼塊,所以你說的那種情況,只會執行第一塊。

巢狀if elif

print ("You enter a dark room with two doors.  Do you go through door #1 or door #2?")

door = input("> ")

if door == "1":
    print ("There's a giant bear here eating a cheese cake.  What do you do?")
    print ("1. Take the cake.")
    print ("2. Scream at the bear.")

    bear = 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 = 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!")

結果

You enter a dark room with two doors.  Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.  What do you do?
1. Take the cake.
2. Scream at the bear.
> 1
The bear eats your face off.  Good job!
You enter a dark room with two doors.  Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.  What do you do?
1. Take the cake.
2. Scream at the bear.
> 2
The bear eats your legs off.  Good job!
You enter a dark room with two doors.  Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 1
Your body survives powered by a mind of jello.  Good job!

You enter a dark room with two doors.  Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 3
The insanity rots your eyes into a pool of muck.  Good job!

常見問題

Q: 可以用if-else替換elif 嗎?

某些情況下可以, 但是這個也依賴於每一個if/else是怎麼寫的 。這也意味著, Python會檢查每個if-else的組合,而不是隻檢查if-elif-else組合中的第一個為假的分支,嘗試用兩種方式多編寫一些程式碼,以找出他們的不同點。

Q:我怎麼知道一個數字是在一個數字範圍之間?

有兩種方法: 一種經典的方式是使用0 < x < 10 或者 1 <= x < 10,另一中方式是使用x in range(1, 10)。

Q: 怎樣才能在if-elif-else程式碼塊中增加更多的選擇?

為每一個可能的選擇增加一個elif 程式碼塊。