Python控制結構一次懂:布林邏輯and/or/not

 

Python主題強勢回歸!! 這次我們要討論的是控制結構中的布林邏輯and/or/not

在Python教學中, 當 Pythonif 條件判斷式(複習if...else條件判斷式請看這篇)變得更複雜,有超過一種狀況時,就使用 Boolean Logic 布林邏輯式。

Python 的 Boolean 運算子包含:and(和)、or(或)、not(不是)。

and 運算子包含兩個條件參數,當兩個條件都成立時,才會被評估為「True」。只要其中有一個不成立,則為「False」。【參考:Python控制結構1.布林值Boolean-True or False?

>>> bool( 1 == 1 and 2 == 2 )
True
>>> bool( 1 == 1 and 2 != 2 )
False
>>> bool( 1 < 1 and 2 >= 2 )
False
>>> bool( 1 < 1 and 2 != 2 )
False

下方 Python 程式例子為只要符合「年滿18歲」及「低消超過180元」才會輸出「welcome」的例子

age=21
money=500
if age >= 18 and money >= 180:
 print("welcome")

結果顯示如下:

>>>
welcome
>>>

Python 的 or 運算子包含兩個參數,只要其中有一個條件成立,就會被評估為「True」。兩個條件都不成立才會被判定為「False」

>>> bool( 1 == 1 or 2 == 2 )
True
>>> bool( 1 != 1 or 2 == 2 )
True
>>> bool( 1 != 1 or 2 != 2)
False

下方例子為只要符合「年滿65歲」或是「你付超過3000元」兩條件任一種,就會輸出「You'll get a Wacken Open Air 2020 ticket」的例子

age=77
money=0
if age >= 65 or money >= 3000:
 print("You'll get a Wacken Open Air 2020 ticket")

結果顯示如下:

>>>
You'll get a Megadeth concert ticket
>>>

not 運算子只有包含「一個」條件參數,條件成立(就是合乎邏輯)就會顯示為「False」。條件不成立才會被判定為「True」

>>> bool( not 1 == 1 )
False
>>> bool( not 1 != 1 )
True

下方例子為只要不符合「年滿18歲」就會顯示「未滿18歲不得進入」的例子

age=14
if not (age>=18):
 print("未滿18歲不得進入")

結果顯示如下:

>>>
未滿18歲不得進入
>>>

 

還想了解更多Python教學相關文章嗎?快到部落格首頁找找吧!!

 

 

 

其他閱讀

Python控制結構1.布林值Boolean-True or False?

 

Python控制結構2.if else條件判斷(1)

 

Python控制結構2.if else條件判斷(2)

 

Python控制結構3.布林邏輯:and,or,not

 

Python控制結構4.運算子優先順序(Operator precedence)一覽

 

Python控制結構5.while 迴圈

 

Python控制結構7.List串列與其他運算子的應用

 

Python控制結構8.List-append,insert,index,len函數

 

Python控制結構9.Range數列生成

 

Python控制結構10.for迴圈

 

Python控制結構11.實作簡單的計算機

arrow
arrow

    Java瑪奇朵 發表在 痞客邦 留言(0) 人氣()