【python从入门到实战】三. if基础及逻辑运算符
一. if基础
1.if 语法格式
if 判断条件:
条件成立
else:
条件不成立
2. if 的逻辑判断
3. if判断的案例
score = int(input("请输入你的孩子的成绩:"))
if score >= 60:
print("你孩子的成绩及格了")
else:
print("你孩子没有好好学习")
4. elif的加入
if 条件一:
满足条件一
elif 条件二:
满足条件二
elif 条件三:
满足条件三
...............
else:
其他可能
elif的一个小案例
holiday = "情人节"
if holiday == "生日":
print("蛋糕")
elif holiday == "情人节":
print("送玫瑰花")
elif holiday == "圣诞节":
print("吃苹果")
else:
print("其他节日")
5. if的嵌套连用语法及其逻辑过程
|
#坐火车事件,有票,刀不能超过30厘米
has_ticket = True
knife_length = 35if has_ticket:
print("有票,过安检")
if knife_length > 30:
print("有违规物体")
else:
print("可以上车")
else:
print("买票")
二. 逻辑运算 and or not
1. 语法【条件1 and 条件2 】,两个条件都满足才为True,其它为False。
条件1 | 条件2 | 结果 |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
年龄的范围在0-120
age = 54
if age > 0 and age <= 120:
print("年龄范围正确")
else:
print("年龄范围错误")
2. 语法【条件1 or 条件2】, 两者条件都不满足才为False,其它为True。
条件1 | 条件2 | 结果 |
T | T | T |
T | F | F |
F | T | F |
F | F | F |
#上大学,要么成绩达到450分,要么有特长
score = 444
special_skill = True
if score >= 450 or special_skill:
print("可以上大学")
else:
print("不能上大学")
3.语法【not 条件】,与条件相反
条件 | 结果 |
T | F |
F | T |
#是否为员工
is_employee = True
if not is_employee:
print("不是员工")
else:
print("是员工")
综合案例
import random print("石头-1,剪刀-2,布-3") player = int(input("选手出:")) computer = random.randint(1, 3) #随机生成1到3的整数 if ((player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1)): print("你赢了电脑") elif ((player == 1 and computer == 1) or (player == 2 and computer == 2) or (player == 3 and computer ==3)): print("平局") else: print("电脑赢了") print ("computer: %d player: %d" %(computer, player))