由于x = 79所以只有if x >= 70 and x < 80:的condition满足,故打印better,这里我们可以看出逻辑and运算符是要求and前后的布尔值都是真才能判定condition为真。
我们在看看or或逻辑运算符的实例,or要求or两边的布尔值有一个为真即判定if的conditon表达式为真,如果两边都是假,那么if的条件判断值为假。思考一下如果我们把上边的程序里的所有and都改成or,会打印几条? [python]view plaincopy
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可以不止一个。 [python]view plaincopy