逻辑运算符
运算符 and
逻辑表达式 x and y
布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算
实例 x = False y = True b = x and y print(b) # False
值。
运算符or
逻辑表达式 x or y
布尔"或" - 如果 x 是 True,它返回 True,否则它返回 y 的计算值。
实例 x = True y = False b = x or y print(b) # True
运算符not
逻辑表达式 not x
布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。
实例 x = True b = not x print(b) # False x = True b1 = not x print(b1) # False
优先级为是not>and>or。可以添加()来提升优先级。
print(True and False or not False and False) 短路逻辑: a and b and c and d 如果a为False 则后面所有的and 均不再执行,直接返回a的值。 a or b or c or d 如果a为True 则后面所有的or 均不在执行。直接返回a的值。
例子
- and
# print(True and False or not False )
#
# a=0
# b=1
# c=2
# d=3
# b1=a and b and c and d
# print(b1)
#
结果:
True
0
- or
a=10
b=11
c=12
d=13
b2=a or b or c or d
print(b2)
结果:
10
流程控制
当我们走路的时候遇到了十字路口,我们会停下来选择要走的方向,同样我们 Python程序遇到‘十字路口’的时候,能不能根据不同的情况择不同的方向呢?例 如让我们的Python程序根据不同的时间打印“早上好”或者“晚上好”。 这就用到了Python中的流程控制语句。
if结构
格式:if 条件表达式: …代码…
执行流程:如果条件表达式成立 True。则执行if块(if体) 中的代码.否则执行else 块(else体)中的代码2
练习:
salary = int(input("请输入你的工资:"))