|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Vermilion 于 2017-7-12 16:49 编辑
《零基础入门学习python》第008讲个人学习笔记--了不起的分支与循环2
0.
按照100分制
90-100A
80-90 B
60-80 C
60以下 D
现在输入一个分数,判断级别
第一个程序
- score = int(input('请输入一个分数:'))
- if 100 >= score >= 90:
- print('A')
- if 90 > score >= 80:
- print('B')
- if 80 > score >= 60:
- print('C')
- if 60 > score >= 0:
- print('D')
- if score < 0 or score > 100:
- print('输入错误!')
复制代码
第二个程序
- score = int(input('请输入一个分数:'))
- if 100 >= score >= 90:
- print('A')
- else:
- if 90 > score >= 80:
- print('B')
- else:
- if 80 > score >= 60:
- print('C')
- else:
- if 60 > score >= 0:
- print('D')
- else:
- print('输入错误!')
复制代码
第三个程序
- score = int(input('请输入一个分数:'))
- if 100 >= score >= 90:
- print('A')
- elif 90 > score >= 80:
- print('B')
- elif 80 > score >= 60:
- print('C')
- elif 60 > score >= 0:
- print('D')
- else:
- print('输入错误!')
复制代码
第二个因为格式问题,所以较为繁琐
第一个由于运算步骤过多(是因为if条件句都是平行并列的,代表每一个if都要进行判断,不管第一个if上来是不是就满足了)
所以选择第三个较为合适
注:elif==C语言中的else if
1.悬挂else
即指C语言中的else和if的就近对应原则
但是python中不是这样,python中是以格式为主,格式对应的为一对
2.三元操作符
- x, y = 4, 5
- if x < y:
- small = x
- else:
- small = y
复制代码
三元操作符版:- small = x if x < y else y
复制代码
即x if 条件 else y
3.assert断言
assert后边的东西错误,直接整个程序报错崩溃
举个例子:
>>> assert 3 > 4
崩溃报错
课后习题(错的)
0.
假设有x=1,y=2, z=3 , 请问如何快速将变量的三个值互换?
x,y,z=z,y,x
1.
(x<y and [x] or [y]) [0]实现什么样的功能?
以前无三元操作符的时候当作三元操作符使用,鱼神说以后会说的
2.成员资格运算符
in,用于检查一个值是否在序列中,如果在序列中则返回true,否则false
鱼神只说了这个,但我在网上搜的时候还发现了 not in ,和in正好相反
- >>>name='小甲鱼'
- >>>'鱼' in name
- true
- >>>'肥鱼' in name
- false
复制代码
动动手
0.请把以下代码修改为三元操作符
- x, y, z = 6, 5, 4
- if x < y:
- small = x
- if z < small:
- small = z
- elif y < z:
- small = y
- else:
- small = z
复制代码 [
我的答案
- x, y, z = 6, 5, 4
- small=x if x < y else y if y<z else z
- if z <small:
- small=z
- print(small)
复制代码
鱼神的答案
- small = x if (x < y and x < z) else (y if y < z else z)
复制代码 |
评分
-
查看全部评分
|