Python学习入门基础教程(learning Python)--3.3.3 Python逻辑关系表达式

    在if分支判断语句里的条件判断语句不一定就是一个表达式,可以是多个(布尔)表达式的组合关系运算,这里如何使用更多的关系表达式构建出一个比较复杂的条件判断呢?这里需要再了解一下逻辑运算的基础知识。逻辑关系运算有以下几种运算符.


     下面是逻辑与实例,通过例子我们了解一下and、or等逻辑运算操作机制。

    

def if_check(): 
	global x
	x = 79
	print(" in if_check x = ", x)
	if x >= 60 and x < 70:
		print(" good")
	if x >= 70 and x < 80:
		print(" better")
	if x >= 80 and x < 90:
		print(" best")
	if x >= 90 and 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()

        Python程序运行结果如下所示。


    由于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 >= 60 or x < 70:
		print(" good")
	if x >= 70 or x < 80:
		print(" better")
	if x >= 80 or x < 90:
		print(" best")
	if x >= 90 or 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 > 0 or x < 100) and (y > 0 or y < 100): 
	 z = x * y


——————————————————————————————————



原文地址:https://www.cnblogs.com/dyllove98/p/3162817.html