2022年 11月 5日

python中的逻辑运算符

python中的逻辑运算符:and(逻辑与)、ord(逻辑或)、not(逻辑非)

1.and

1)运算规则:
a.操作对象都是布尔值:两个都是True结果才是True,只要有一个时候False结果就是False

True and True -> True
True and False -> False
False and True -> False
False and False -> False
  • 1
  • 2
  • 3
  • 4

2)应用场景:希望两个或者多个条件同时满足才做什么事情,就使用逻辑与运算。相当于生活中的并且。
练习1:写出学生是否能拿奖学金的跳进,拿奖学金的要求:绩点超过4,操评分高于85,这个两个条件同时满足

grade = 4.5

score = 90

print('是否能拿奖学金:',grade > 4 and score > 85)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.or

1)运算规则
a.操作对象都是布尔值:两个都是False结果才是False,只要有一个是True结果就是True

"""

True and True -> True

True and False -> True

False and True -> True

False and False -> False

"""

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2)应用场景:希望两个或者多个条件只要有一个满足就可以就使用逻辑或运算。相当于生活中的或者
练习1:写出学生是否能拿奖学金的跳进,拿奖学金的要求:绩点超过4,操评分高于90,这个两个条件同时满足

grade = 4.5
score = 80
print('是否能拿将奖学金:',grade > 4 or score < 90)
  • 1
  • 2
  • 3

练习3:写出判断制定的年是否是闰年的条件:
1)能被4整除但是不能被100整除
2)直接能被400整除

year = 2012

d1 = year % 4 == 0  #能被4整除的条件

d2 = year % 100 !=0 #不能被100整除的条件

d3 = year % 400 == 0 #能被400整除的条件

print('是否是闰年',(d1 and d2) or d3)

print('是否是闰年:',year % 4 == 0 and year % 100 != 0 or year %400 ==0)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

3.not

1)运算规则:True 变 False ,False 变 True

"""

not True  -> False

not True  -> True

"""

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2)应用场景:不满足某个条件就做什么,就用not.

age = 18

print('是否成年:', age >= 18)

print('使用成年:', not age < 18)
  • 1
  • 2
  • 3
  • 4
  • 5

练习:写出NUM是否不能同时被3和7整除

num = int(input('请输入一个数:'))

print('是否满足条件',not(num % 3 == 0 and num % 7 == 0))
  • 1
  • 2
  • 3

4.操作对象不是布尔的时候

逻辑运算符语法上可以操作任何数据
数据1 and 数据2 ->如果数据1的布尔值是True,结果是数据2,如果数据1的布尔值是False,结果就是数据1.
数据1 or 数据2 ->如果数据1的布尔值是True,结果是数据1;如果数据1的布尔值是False,结果是数据2
补充:数据的布尔值怎么确定 -所有为零为空的值都是False,其他数据的布尔都是True。

print(1 and 'abc')

print('abc' and 'hello')

print(0 and 'abc')

print(False and 100)

print(1 or 'abc')   #1

print(7 or 8)       #7

print(0 or 'abc')   #abc

print(not 1)      #False

print(not 0)      #True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

5.短路操作

and 的短路操作:
表达式1 and 表达式2 -> 如果表达式1 的结果是False,表达式2不会执行
or 的短路操作
表达式1 or 表达式2 ->如果表达式1 的结果是True,表达式2不会执行

def func1()
print('函数被执行')
print(True and func1())

True and func1()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6