第九关
知识点复习
学习用时:50min
随堂测验+上机作业:50min
随堂作业正确率:6/7
1.多路分支
elif 是 else if 的缩写代表 “否则,如果……则执行……”
一般来讲条件判断的顺序是if 后面跟的条件最先判断,elif 后的条件按照从上到下的顺序依次判断,最后再判断 else 对应的条件
练习1
1.定义一个名为 choose_destination 的函数,参数为 fuel(剩余油量),单位为升;
2.根据 fuel 计算可行驶里程(distance),假设汽车的油耗是 8 升/百公里;
3.根据 distance 进行判断,打印出最远能去的城市。如果油量哪里都不能去,打印出 先去加油站吧;
4.使用 input() 函数输入剩余油量并传入 choose_destination() 函数。
def choose_destination(fuel):
distance = fuel /8
if distance * 100 >472:
print("上海")
elif distance * 100 >435:
print("杭州")
elif distance * 100 >175:
print("南京")
else:
print("先去加油站吧")
choose_destination(int(input("请输入油量")))
2.逻辑运算
逻辑运算:与运算and、或运算 or和 非运算not
“与”运算来中任何一个条件不满足,都会导致条件语句被判定为 False;
“或”运算是只要有任意一个条件满足,if 后面的语句就能执行;
not 运算符会对输入条件的 True 和 False 取反 不满足此条件的就执行后面的语句。
if Gender == “Male” and Height >= 175:
print('高于平均男性身高')
if score >= 90 or ranking >= 5:
print('学习有进步')
#摘抄
identity = input('请输入你的身份:研究员/访客/行政/外勤/财务')
if not identity == '访客':
#等同于if identity != '访客'
print('请通过,欢迎来到实验室')
成员运算符 in:可以用 in 来判断某些字符是否存在于一个字符串中,也可以和not配合使用
print('He' in 'Hello world')
# 输出:True
print('He' not in 'Hello world')
# 输出:False
3.三元表达式
值1 条件 值2
如果满足条件 返回值1 ,否则返回值2
#求绝对值为例
x = 4
if x >= 0:
x_abs = x
else:
x_abs = -x
print(x_abs)
#------------------------------------------------------------------------------------------
#三元表达式写法
x = 4
x_abs = x if x >= 0 else -x
print(x_abs)
#求最值
score_1 = 90
score_2 = 91
score_max = score_1 if score_1 > score_2 else score_2
print(score_max)
错误备注,第一次将else后面写成了 lunch=“汉堡”
time = 11
lunch = '油泼面' if time < 12 else '汉堡'
print('中午吃' + lunch)
4.学习巩固
练习 2
def guess_password(num):
if num < 1 or num < 999999:
print("请输入 1-999999 以内的数字")
elif num == 666:
print("哼,六六六?")
elif num ==768145:
print("猜对了,玩!")
else:
print("错了,再来!")
result = int(input('你猜密码是?:'))
guess_password(result)
练习 3 算哪一年是闰年
1.能被 400 整除即为闰年(2000);
2.如果这个年份能被 4 整除,且不能被 100 整除,那它也是闰年(2020)
def check_year(year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("闰年")
else:
print("平年")
input_year = int(input('请输入年份:'))
check_year(input_year)