python小课堂:11 Python之if/else语句
Python之if-else语句,Python语言的控制流程
🕐
语法
if 条件:
# 条件成立
else:
# 条件不成立- 条件:
bool值
score = 59
res = score < 60
# 表达式的类型: bool
print(type(res))
if res:
print('抱歉,考试不及格')定义
- if: 使用if判断,可以在当if条件为True时,执行if的子逻辑分支
- else: 但有时候,也想在if条件不为True时,执行别的子逻辑分支
- elif: 上面组合的情况 参考这里 https://www.imooc.com/code/21962
score = 59
if score < 60:
print('抱歉,考试不及格')
else:
print('恭喜你,考试及格')其它<完整用法>
score = 59
if score < 60:
print('抱歉,考试不及格')
elif score >= 90:
print('恭喜你,拿到卓越的成绩')
elif score >= 80:
print('恭喜你,拿到优秀的成绩')
else:
print('恭喜你,考试及格')上课示例
score = int(input("input your score:"))
# if score < 60:
# print('抱歉,考试不及格')
# elif score >= 90:
# print('恭喜你,拿到卓越的成绩')
# elif score >= 80:
# print('恭喜你,拿到优秀的成绩')
# else:
# print('恭喜你,考试及格')
# score < 60
# score >= 60 and score < 80
# score >= 80 and score < 90
# score >= 90
if score < 60:
print('抱歉,考试不及格')
if score >= 60 and score < 80:
print('恭喜你,拿到及格的成绩')
if score >= 80 and score < 90:
print('恭喜你,拿到优秀的成绩')
if score >= 90:
print('恭喜你,拿到卓越的成绩')
课堂练习
# 1. 学生分数 < 60 分不及格
# 2. 学生分数 >= 60 分及格
# 3. 学生分数 >= 80 分优秀
# 4. 学生分数 >= 90 分极好
# 5. 学生分数 == 100 分传说中的神话# 代码片段
res = input("请输入分数:")
score = int(res)
if score < 60 and score >= 0:
print("不及格")TAOJIE
score = 100把赋值当成比较了
res = input("请输入分数:")
score = int(res)
if score < 60 and score >= 0:
print("不及格")
if score < 80 and score >= 60:
print("及格")
if score < 90 and score >= 80:
print("优秀")
if score < 100 and score >=90:
print("极好")
if score = 100:
print("传说中的神话")ZhengMAN:
- 期望在所有条件都枚举完了,仅剩下最后一种情况,是否可以使用
else
res = input("请输入分数:")
score = int(res)
if score >= 0 and score < 60:
print('不及格')
if score >= 60 and score < 80:
print('及格')
if score >= 80 and score < 90:
print('优秀')
if score >= 90 and score < 100:
print('极好')
else:
print('传说中的分数')一些疑问
score < 60 and score >= 0哪个在左,哪个在右比较好?- 数学: [0, 60): 区间,左闭右开区间
- score ≥0 and score <60
- 有没有简单的写法?
score in range(0, 60)- 但从语法角度,没有简单写法
- 期望在所有条件都枚举完了,仅剩下最后一种情况,是否可以使用
else
# 1. 学生分数 < 60 分不及格
# 2. 学生分数 >= 60 分及格
# 3. 学生分数 >= 80 分优秀
# 4. 学生分数 >= 90 分极好
# 5. 学生分数 == 100 分传说中的神话
# [0, 100)
# 100
res = input("请输入分数:")
score = int(res)
if score >=0 and score < 100:
if score >= 0 and score < 60:
print('不及格')
if score >= 60 and score < 80:
print('及格')
if score >= 80 and score < 90:
print('优秀')
if score >= 90 and score < 100:
print('极好')
else:
print("分传说中的神话")
# 学生分数 == 100 分传说中的神话总结
- 多种情况(大于2个),只用
if解决问题 - 只有2种情况,可以用
if/else - 不要使用
if/else嵌套 - 不要使用
elif
扩展问题
range是左闭右开- 怎么解决左开,右开的场景?
- 怎么解决左闭,右闭 ?
- 如果不是整数型的区间,怎么解决?
[0, 100) -> range(0, 100)
(0, 100) -> range(-1, 100)
[0, 100] -> range(0, 101)