第5课 布尔表达式

一、布尔类型(bool)

1、布尔类型与1/0不是一回事

  布尔类型有两个值,True和False

2、布尔表达式:

  1)关系运算符:>,<,==,!=,>=,<=

  2)注意事项:== 指两边关系等价; = 赋值; 不等于的!是英文的

3、数值的比较,比较值的大小。

>>> type(3 > 5)
<class 'bool'>
>>> 3 > 5
False
>>> 5 > 3
True
>>> 2 != 6
True
>>> 3 <> 8 # python中,不等于不能这样写
SyntaxError: invalid syntax

4、字符串的比较

  1)不是比较字符串的长度(len()):a---97,A---65

  2)比较ASCII值的大小(十进制):

  3)从第一个元素依次对比,跟元素的个数没有关系

>>> 'acb' > 'abc'  # 从第一个元素依次类推
True
>>> 'z' > 'asdfghjkl'
True

  4)== 比较的是值的大小

>>> 'abc' == 'abc'
True

5、in 与not in:在/不在== a in b----a元素是否是b序列的一个元素,如果在则为True,否则为False。

>>> str1 = 'asdfzzyyxx'
>>> 'yy' in str1
True
>>> 'k' not in str1
True

二、条件组合--逻辑关系

1、逻辑与:and

  1)and--逻辑与:a and b,只有and两边的条件都为True,则结果为True,否则结果为False。

  2)如果a == True  b要进行判断;只有当a和b同时为True时,结果才为True。

  3)如果a == False  则b不需要判断

>>> (3 > 0) and (0 > -1)
True
True
>>> True and True
True
>>> True and False
False
>>> (3 > 0) and (3 > 5)
False

 2、逻辑或:or--- a or b   or两边只要有一边为True,则结果为True;如果两边都为False,则结果为False。

  1)如果a == True,则b不需要再判断

  2)如果a == False,则b要判断:如果b == True,则结果为True;如果b == False,则结果为False。

>>> 3 < 5 or 3 > 8
True
>>> 3 > 8 or 3 < 1
False

3、不/非:not      not True == False; not False == True

>>> not (3 > 8)
True
>>> not 0 > -1
False

4、优先级:not > and > or     为了使用方便,建议使用小括号。只要能清楚表达内容即可,并不是全部都要用小括号。

>>> 3 > 1 and not 2 > 1 or 5 > 4
True
>>> (3 > 1) and not (2 > 1) or (5 > 4)
True
>>> 3 > 1 or (2 != -2) and 2 < 3
True

 

转载于:https://www.cnblogs.com/nick1998/p/9992362.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值