jacky4955 发表于 2018-8-9 10:02:57

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

  在if分支判断语句里的条件判断语句不一定就是一个表达式,可以是多个(布尔)表达式的组合关系运算,这里如何使用更多的关系表达式构建出一个比较复杂的条件判断呢?这里需要再了解一下逻辑运算的基础知识。逻辑关系运算有以下几种运算符.
http://img.blog.csdn.net/20130629161410750?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTAwMDUyOQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
  下面是逻辑与实例,通过例子我们了解一下and、or等逻辑运算操作机制。
view plaincopy
[*]  def if_check():
[*]  global x
[*]  x = 79
[*]  print(" in if_check x = ", x)
[*]  if x >= 60and x < 70:
[*]  print(&quot; good&quot;)
[*]  if x >= 70and x < 80:
[*]  print(&quot; better&quot;)
[*]  if x >= 80and x < 90:
[*]  print(&quot; best&quot;)
[*]  if x >= 90and x < 100:
[*]  print(&quot; Excellent&quot;)
[*]  if x < 60:
[*]  print(&quot; You need improve&quot;)
[*]
[*]  def main():
[*]  global x
[*]  print(&quot; in main x = &quot;, x)
[*]  if_check()
[*]
[*]  x = 12
[*]  main()
      Python程序运行结果如下所示。http://img.blog.csdn.net/20130629161551109?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTAwMDUyOQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
  由于x = 79所以只有if x >= 70 and x < 80:的condition满足,故打印better,这里我们可以看出逻辑and运算符是要求and前后的布尔值都是真才能判定condition为真。
  我们在看看or或逻辑运算符的实例,or要求or两边的布尔值有一个为真即判定if的conditon表达式为真,如果两边都是假,那么if的条件判断值为假。思考一下如果我们把上边的程序里的所有and都改成or,会打印几条?
view plaincopy
[*]  def if_check():
[*]  global x
[*]  x = 79
[*]  print(&quot; in if_check x = &quot;, x)
[*]  if x >= 60or x < 70:
[*]  print(&quot; good&quot;)
[*]  if x >= 70or x < 80:
[*]  print(&quot; better&quot;)
[*]  if x >= 80or x < 90:
[*]  print(&quot; best&quot;)
[*]  if x >= 90or x < 100:
[*]  print(&quot; Excellent&quot;)
[*]  if x < 60:
[*]  print(&quot; You need improve&quot;)
[*]
[*]  def main():
[*]  global x
[*]  print(&quot; in main x = &quot;, 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可以不止一个。
view plaincopy
[*]  if (x > 0or x < 100) and (y > 0or y < 100):
[*]  z = x * y
页: [1]
查看完整版本: Python学习入门基础教程(learning Python)--3.3.3 Python逻辑关系表达式