前置疑问
Q1 双分支与三元运算符之间的转换? Q2 python循环代码如果简洁优化?
学习内容
1、三种选择结构 2、循环结构 3、break、continue、else关键字 4、推导式生成序列
学习产出
1、选择结构
1.1 单分支结构
>>> if 3:
print("ok")
ok
>>> if a = 3:
SyntaxError: invalid syntax
python中条件语句不能用赋值符"="
1.2 双分支结构
>>> a = 56
>>>
>>> if a > 60:
print("good")
else:
print("bad")
bad
1.3 多分支结构
>>> grade = 80
>>> if grade >= 90:
print("A")
elif grade >= 80 and grade < 90:
print("B")
elif grade >= 70 and grade < 80:
print("C")
elif grade >= 60 and grade < 70:
print("D")
else:
print("E")
B
#另外一种写法
score = int(input("请输入一个0~100区间的数字:"))
degree = "ABCDE"
num = 0
if score > 100 or score < 0:
print("输入错误!")
else:
num = score // 10
if num < 6:num = 5
print("分数为{0}, 对应等级为{1}".format(score, degree[9 - num]))
请输入一个0~100区间的数字:46
分数为46, 对应等级为E
A1
1.4 三元运算符
条件为真执行A if 条件表达式 else 条件为假执行B
s = input("please input a number: ")
if int(s) < 10:
print("good")
else:
print("false")
# 三元运算符的测试
print("good" if int(s) < 10 else "false")
2、循环
循环流程图
>>> num = 0
>>> sum = 0
>>> while num <= 100:
sum = sum + num
num +=1
>>> print("所有的和为{0}".format(sum))
所有的和为5050
- for循环 用处很多
for 变量 in 迭代对象 对象:列表、元组、字典、集合、迭代器iterator 生成器函数 generator、 文件对象
>>> a1 = [6,5,4,3,2,1]
>>> for i in a1:
print(i)
6
5
4
3
2
1
>>>
>>> a2 = ("t","u","p","l","e")
>>> for i in a2:
print(i)
t
u
p
l
e
>>>
>>> a3 = {6,5,4,3,2,1} #观察集合遍历和元组遍历的区别
>>> for i in a3:
print(i)
1
2
3
4
5
6
>>> for i in a4:
print(i)
p
e
u
l
t
>>> a5 = {'name':'xiaoming','age':20,'job':'programmer'}
>>> for i in a5:
print(i)
name
age
job
>>> for i in a5.values():
print(i)
xiaoming
20
programmer
>>> for i in a5.items():
print(i)
('name', 'xiaoming')
('age', 20)
('job', 'programmer')
>>> num = 0
>>> sum = 0
>>> for i in range(101):
sum = sum + num
num += 1
>>> print("所有100和为:{0} ".format(sum))
所有100和为:5050
#打印九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print("{0}*{1}={2}".format(i,j,(i*j)), end="\t")
print()
>>> r1 = dict(name="xiaoming",age=20, salary=30000, city="A")
>>> r2 = dict(name="xiaohong",age=20, salary=20000, city="B")
>>> r3 = dict(name="xiaogang",age=20, salary=15000, city="C")
>>>
>>> L1 = [r1,r2,r3]
>>>
>>> for i in L1:
if i.get("salary") > 15000:
print(i)
{'name': 'xiaoming', 'age': 20, 'salary': 30000, 'city': 'A'}
{'name': 'xiaohong', 'age': 20, 'salary': 20000, 'city': 'B'}
break、continue语句 break用来结束整个循环 continue 结束当前这一次循环
while True:
a = input("请输入一个字符(Q或者q退出):")
if a == "Q" or a == "q":
print("!!!exit")
break;
else:
print(a)
#打印10以内的奇数
for i in range(11):
if i % 2 == 0:
continue
else:
print(i)
- else语句
在python中else 还能与for 或者while一起搭配使用,循环正常结束执行else语句,若循环被break中断则不执行else语句,下面是输入员工薪水的代码:
employee = 0
salaryNum = 0
salary = []
for i in range(4):
s = input("please input salary(Q or q is exit):")
if s == "Q" or s == "q":
print("ok-ok-ok")
break
if float(s) < 0:
continue
employee += 1
salary.append(float(s))
salaryNum = salaryNum + float(s)
else:
print("已完成4名员工的薪资输入!!!")
print("员工人数{0}".format(employee))
print("录入薪资:",salary)
print("平均薪资{0}".format(salaryNum / employee))
A2
- 循环代码优化三个基本准则
减少循环内部的不必要运算 嵌套循环时,处于内部循环的运算,能外面写,就写在外面 局部变量使用较快 相关拼接字符串或者插入列表和删除,都要考虑效率。比如字符拼接join() 效率比 + 好
import time
start = time.time()
for i in range(1000):
result = []
for j in range(100000):
result.append(i*1000 + j * 100)
end = time.time()
print("耗时:{0}".format((end - start)))
#优化
start = time.time()
for i in range(1000):
result = []
m = i * 1000
for j in range(100000):
result.append(m + j * 100)
end = time.time()
print("耗时:{0}".format((end - start)))
- zip()进行迭代
zip()可以一次性对多个序列同时处理,迭代长度取最小的序列长度
>>> names = ("xiaoming","xiaohong","xiaogang","xiaoyang")
>>> ages = (18,19,20,21)
>>> jobs = ("teacher","programmer","student")
>>> for name, age, job in zip(names,ages,jobs):
print("{0}-{1}-{2}".format(name,age,job))
xiaoming-18-teacher
xiaohong-19-programmer
xiaogang-20-student
- 各种序列推导式
列表推导式 [表达式 for item in 可迭代对象]
>>> [i for i in range(1,5)]
[1, 2, 3, 4]
>>> [i for i in range(2,10) if(i % 2 != 0)]
[3, 5, 7, 9]
- 字典推导式
{key:value for item in 可迭代对象}
>>> my_text = 'i love python, i love java, i love machine learning'
>>> char_count = {c:my_text.count(c) for c in my_text}
>>> char_count
{'i': 5, ' ': 9, 'l': 4, 'o': 4, 'v': 4, 'e': 5, 'p': 1, 'y': 1, 't': 1, 'h': 2, 'n': 4, ',': 2, 'j': 1, 'a': 4, 'm': 1, 'c': 1, 'r': 1, 'g': 1}
>>> {i for i in range(100) if i % 2 == 0 and i % 3 == 0}
{0, 96, 66, 36, 6, 72, 42, 12, 78, 48, 18, 84, 54, 24, 90, 60, 30}
- 生成推导式(元组无推导式)
生成的对象是一次性的,用完之后就没有了
>>> (i for i in range(100) if i % 2 == 0 and i % 3 == 0)
<generator object <genexpr> at 0x0000017115EE3C10>
>>> generator1 = (i for i in range(100) if i % 2 == 0 and i % 3 == 0)
>>> for i in generator1:
print(i,end=" ")
0 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96
>>> for i in generator1:
print(i,end=" ")
>>>
>
今日代码
import turtle
my_colors = ("red","green","yellow","black")
turtle.width(5)
turtle.speed(1)
for i in range(10):
turtle.penup()
turtle.goto(0, -i*10)
turtle.pendown()
turtle.color(my_colors[i%len(my_colors)])
turtle.circle(i*10)
turtle.done()
import turtle
t = turtle.Pen()
t.width = 5
width = 30
num = 18
t.speed(0)
x1 = [(-300,300),(-300+width*num,300)]
y1 = [(-300,300),(-300,300-width*num)]
#划横线时 |x.end - x.start|长度不变, y坐标变
for i in range(19):
t.penup()
t.goto(-300,300 - 30 * i)
t.pendown()
t.goto(240,300 - 30 * i)
#划竖线时,x坐标变 |y.end - y.start长度不变
for i in range(19):
t.penup()
t.goto(-300 + 30 * i,300)
t.pendown()
t.goto(-300 + 30 * i,-240)
t.hideturtle()
turtle.done()
|