第 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)从第一个元素依次对比,跟元素的个数没有关系

扫描二维码关注公众号,回复: 4182062 查看本文章
>>> '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

猜你喜欢

转载自www.cnblogs.com/nick1998/p/9992362.html