Python学习入门基础教程(learning Python)-3.3.2 Python的关系演算

Python学习入门基础教程(learning Python)--3.3.2 Python的关系运算

如果if的condition不用布尔表达式来做条件判断而采用关系表达式,实际上关系表达式运算的结果要么是True要么是False。下面我们先了解一些有关关系运算符的基础知识,如下表所示。

Python学习入门基础教程(learning Python)-3.3.2 Python的关系演算

    做个小程序测试一下。

 

[python] view plaincopy
  1. def if_check():   
  2.     global x  
  3.     x = 100  
  4.     print(" in if_check x = ", x)  
  5.     if x > 1:  
  6.         print(" x greater than 1")  
  7.     if x == 0:  
  8.         print(" x equal to 0")  
  9.     if x < -100:  
  10.         print(" x lowe than -100")  
  11.     if x >= 100:  
  12.         print(" x greater than or equal to 100")  
  13.     if x != 0:  
  14.         print(" x not equal to 0")  
  15.       
  16. def main():  
  17.     global x  
  18.     print(" in main x = ", x)  
  19.     if_check()  
  20.   
  21. x = 12  
  22. main()  

 

    程序运行结果如下所示。

Python学习入门基础教程(learning Python)-3.3.2 Python的关系演算

    从Python程序运行结果来看,当x = 100时,x > 1 x >= 100 和x != 0这三个if语句关系运算结果为真,所以其下的打印语句执行。