在if分支判斷語句裏的條件判斷語句不一定就是一個表達式,可以是多個(布爾)表達式的組合關係運算,這裏如何使用更多的關係表達式構建出一個比較複雜的條件判斷呢?這裏需要再瞭解一下邏輯運算的基礎知識。邏輯關係運算有以下幾種運算符.
下面是邏輯與實例,通過例子我們瞭解一下and、or等邏輯運算操作機制。
def if_check():
global x
x = 79
print(" in if_check x = ", x)
if x >= 60and x < 70:
print(" good")
if x >= 70and x < 80:
print(" better")
if x >= 80and x < 90:
print(" best")
if x >= 90and x < 100:
print(" Excellent")
if x < 60:
print(" You need improve")
def main():
global x
print(" in main x = ", x)
if_check()
x = 12
main()
由於x = 79所以只有if x >= 70 and x < 80:的condition滿足,故打印better,這裏我們可以看出邏輯and運算符是要求and前後的布爾值都是真才能判定condition爲真。
我們在看看or或邏輯運算符的實例,or要求or兩邊的布爾值有一個爲真即判定if的conditon表達式爲真,如果兩邊都是假,那麼if的條件判斷值爲假。思考一下如果我們把上邊的程序裏的所有and都改成or,會打印幾條?
def if_check():
global x
x = 79
print(" in if_check x = ", x)
if x >= 60or x < 70:
print(" good")
if x >= 70or x < 80:
print(" better")
if x >= 80or x < 90:
print(" best")
if x >= 90or x < 100:
print(" Excellent")
if x < 60:
print(" You need improve")
def main():
global x
print(" in main x = ", x)
if_check()
x = 12
main()
good和better被打印出來可以理解(79 >= 60, 79 > = 70都爲真),但爲何best和Excellent也被打印出來了呢?
當x = 79時,x >= 80爲假,但x < 90卻是爲真,兩者做邏輯或運算其綜合表達式的值爲真。同理,if x >= 90 or x < 100:裏有79 < 100爲真,故if的條件判斷語句(x >= 90 or x < 100)爲真。
最後需要說明一點的是,在if裏and和or可以不止一個。
if (x > 0or x < 100) and (y > 0or y < 100):
z = x * y