实例说明Python中比较运算符的使用

yipeiwu_com5年前Python基础

下表列出了所有Python语言支持的比较操作符。假设变量a持有10和变量b持有20,则:

2015513120032469.jpg (585×480)

 例如:

试试下面的例子就明白了所有的Python编程语言提供的比较操作符:

#!/usr/bin/python

a = 21
b = 10
c = 0

if ( a == b ):
  print "Line 1 - a is equal to b"
else:
  print "Line 1 - a is not equal to b"

if ( a != b ):
  print "Line 2 - a is not equal to b"
else:
  print "Line 2 - a is equal to b"

if ( a <> b ):
  print "Line 3 - a is not equal to b"
else:
  print "Line 3 - a is equal to b"

if ( a < b ):
  print "Line 4 - a is less than b" 
else:
  print "Line 4 - a is not less than b"

if ( a > b ):
  print "Line 5 - a is greater than b"
else:
  print "Line 5 - a is not greater than b"

a = 5;
b = 20;
if ( a <= b ):
  print "Line 6 - a is either less than or equal to b"
else:
  print "Line 6 - a is neither less than nor equal to b"

if ( b >= a ):
  print "Line 7 - b is either greater than or equal to b"
else:
  print "Line 7 - b is neither greater than nor equal to b"

当执行上面的程序它会产生以下结果:

Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b


相关文章

python实现读取并显示图片的两种方法

在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片。本人偏爱 matpoltlib,因为它的语法更像 matlab。 一、matplo...

python中reload(module)的用法示例详解

前言 本文主要给大家介绍了关于python中reload(module)用法的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 1、Python2中可以和Pyt...

python正则表达式匹配IP代码实例

这篇文章主要介绍了python正则表达式匹配IP代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 import re re...

Python socket非阻塞模块应用示例

本文实例讲述了Python socket非阻塞模块应用。分享给大家供大家参考,具体如下: 一 服务端程序 # 导入模块 import socketserver import rand...

Python读取MRI并显示为灰度图像实例代码

Python读取MRI并显示为灰度图像实例代码

本文实例主要关于Python实现读取MRI(核磁共振成像)为numpy数组,使用imshow显示为灰度。 代码如下: import matplotlib.pyplot as plt...