逻辑运算符
运算符 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("请输入你的工资:"))
if salary > 10000:
print ("你就买大众")
if salary >5000 and salary <10000:
print("我就买QQ")
结果:
请输入你的工资:6000
我就买QQ
if…else…结构
格式:if 条件表达式: …代码1… else: … 代码2…
执行流程:如果条件表达式成立 True。则执行if块(if体) 中的代码.否则执行else 块(else体)中的代码2
练习:
money = int (input("消费金额:"))
if money >=3000:
sex = input("性别:")
if sex == "男":
print("送女友")
else:
print("送化妆品")
else:
sex = input("性别")
if sex == "男":
print("打火机")
else:
print("送发卡")
结果:
消费金额:6000
性别:男
送女友
.if…elif…eilf…else结构
格式:if 条件表达式1: …代码 1… elif 条件表达式2: … 代码2… elif 条件表达式 3: … 代码3… … else: … 代码4…
执行流程:如果条件表达式1成立 True,执行执行if块中的 代码,执行完程序不再 执行后面的elif中的代码 块。 如果条件表达式1 不成立False,则判断条件 表达式2是否成立,如果 成立则执行代码块2 否 则继续判断条件表达式3 是否成立。依次类推。 如果所有的elif都不成 立,则执行else。
练习:
has_ticket = input("有无车票:")
if has_ticket =="有":
x =input("打开行李箱,是否有违禁品:")
if x == "有":
knife_legth = float(input("刀的长度:"))
if knife_legth > 20:
print("禁止上车")
else:
print("上车")
else:
print("上车")
else:
print("补票")
结果:
有无车票:有
打开行李箱,是否有违禁品:有
刀的长度:15
上车
while循环
格式:初始条件设置:通常是一个计数器,来 控制条件表达式是否成立。 while 条 件表达式: …代码1… …代码2… 改变计 数器的值
执行流程:如果条件表达式成立True,执行执行 循环体中的代码块,执行完循环体中 的代码后,继续判断条件表达式是否 成立,如果成立继续执行循环体。直 到条件表达式为False后程序继续往 下执行。
练习:
i=1
while i<=5:
print(4*("#"))
i+=1
i = 1
while i<=5:
if i==1 or i==5:
print(5*("#"))
i+=1
continue
print("#"+" "+"#")
i +=1
结果:
####
####
####
####
####
#####
# #
# #
# #
#####
for循环
格式:for 临时变量 in 可迭代对象: 循环 体
练习:
i=1
for i in range(5):
print(5*"*")
for i in range(1,6):
if i==1 or i==5:
print(5*"*")
else:
print("*"+" "+"*")
结果:
*****
*****
*****
*****
*****
*****
* *
* *
* *
*****