逻辑运算
在程序开发中,有判断条件时,会需要同时判断多个条件
只有多个条件都满足时,才运行后续程序,就要运用到逻辑运算符
Python 中的逻辑运算符包括:与and/或or/非not三种
1.and
条件一 and 条件二
与/并且
2.or
条件一 or 条件二
或/或者
3.not
and 示例:年龄判断
age = int(input('输入年龄:'))
if age >= 0 and age <=120:
print("corret")
else:
print("error")
or 示例: 成绩是否合格(有一个分数大于等于60即为合格)
score1 = int(input("输入成绩:"))
score2 = int(input("输入成绩:"))
if score1 >= 60 or score2 >=60:
print("及格!")
else:
print("不及格!")
not 示例三:判断是否为本校学生
Student = True
if not Student:
print("非本校学生,请勿入内!")
else:
print("欢迎回到学校!")
elif
在if和else另外,增加一些不同的条件,条件不同,需要执行的代码也不同,就是用elif。
tips:
示例:
job = input("请输入职业:")
if job == "学生":
print("上学!")
elif job == "医生":
print("救死扶伤!")
else:
print("各司其职!")
if嵌套
在之前的条件满足时,在增加额外的判断
示例:乘车入站时的检查:
#乘客有车票
has_ticket = True
#安检检查刀的长度
knife_length = int(input("输入刀的长度:"))
#首先判断有车票,有车票才能安检检查
if has_ticket:
print("车票检查通过,准备安检")
#车票检查通过后,检查刀的长度是否大于20公分
if knife_length >=20:
print("安检未通过!刀具有 %d 公分长"%knife_length)
else:
print("安检通过")
else:
print("车票检查不通过!")