栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

「Python语法结构」数据类型与运算符示例(5)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

「Python语法结构」数据类型与运算符示例(5)

比较运算符示例

功能要求

关系运算符示例

实例代码

print(1 < 3 < 5)  # 等价于1 < 3 and 3 < 5

print(3 < 5 > 2)

print(1 > 6 < 8)

print("Hello" > 'hello')  # 比较字符串大小

print([1, 2, 3] < [1, 2, 4])  # 比较列表大小

print({1, 2, 3} < {1, 2, 3, 4})  # 测试是否为子集

print({1, 2, 3} == {3, 2, 1})  # 测试两个集合是否相等

print({1, 2, 4} > {1, 2, 3})  # 集合之间的包含测试

print({1, 2, 4} < {1, 2, 3})

print({1, 2, 4} == {1, 2, 3})

print('Hello' > 3)  # 字符串和数字不能比较

运行结果

Traceback (most recent call last):

  File "E:CodePythonCodehello.py", line 11, in

    print('Hello' > 3)  # 字符串和数字不能比较

TypeError: '>' not supported between instances of 'str' and 'int'

True

True

False

False

True

True

True

False

False

False

知识说明

比较运算符一般用于数值的比较,也可用于字符的比较,常用的比较运算符如下表:

 当两个数值比较结果是正确时返回True,否则返回False。Python中字符是符号ASCII编码的,每个字符都有属于自己的编码,字符的比较本质是字符的ASCII编码比较。

Python关系运算符最大的特点是可以连用。使用关系运算符的一个最重要的前提是,操作数之间必须可比较大小。

逻辑运算符示例

功能要求

逻辑运算符演示

实例代码

print(3 > 5 and a > 3)  # 注意,此时并没有定义变量a

print(3 < 5 or a > 3)  # 3<5的值为True,不需要计算后面表达式

print(3 > 5 or a > 3)  # 3>5的值为False,所以需要计算后面表达式

运行结果

False

True

Traceback (most recent call last):

  File "E:CodePythonCodehello.py", line 3, in

    print(3 > 5 or a > 3)  # 3>5的值为False,所以需要计算后面表达式

NameError: name 'a' is not defined

知识说明

逻辑运算符and、or、not常用来连接条件表达式构成更加复杂的条件表达式,并且and和or具有惰性求值或逻辑短路的特点,当连接多个表达式时只计算必须要计算的值。

逻辑运算符包括and、or、not,具体用法 

 另外要注意的是,运算符and和or并不一定会返回True或False,而是得到最后一个被计算的表达式的值,但是运算符not一定会返回True或False。

功能要求

逻辑运算符演示

实例代码

print(3 and 5)                  #最后一个计算的表达式的值作为整个表达式的值

print(3 and 5>2)

print(3 not in [1, 2, 3] )      #逻辑非运算not

运行结果

5

True

False

计算逻辑表达式的值

功能要求

假设a为10,b为20,计算逻辑表达式的值

实例代码

print("---- a = False; b = False ----")

a = False; b = False

print(a and b, a or b, not(a))



print("---- a = True; b = False ----")

a = True; b = False

print(a and b, a or b, not(a))



print("---- a = False; b = True ----")

a = False; b = True

print(a and b, a or b)



print("---- a = True; b = True ----")

a = True; b = True

print(a and b, a or b)

运行结果

---- a = False; b = False ----

False False True

---- a = True; b = False ----

False True False

---- a = False; b = True ----

False True

---- a = True; b = True ----

True True

成员运算符示例

功能要求

成员测试运算符演示

实例代码

print(3 in [1, 2, 3])  # 测试3是否存在于列表[1, 2, 3]中

print(5 in range(1, 10, 1))  # range()是用来生成指定范围数字的内置函数

print('abc' in 'abcdefg')  # 子字符串测试

for i in (3, 5, 7):  # 循环,成员遍历

    print(i, end='t')  

运行结果

True

True

True

3 5 7

知识说明

成员运算符的作用是判断某值指定值是否存在于某一序列中,包括字符串、列表或元组。

成员运算符如下表:

 

 在成员运算中,对于成员的运算不仅包含值的大小,还包括类型的判断。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923524.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号