# 循环_推导式_绘制棋盘_函数

1430-王同学

## for循环

#元组
for x in (10,20,30):
print(x*30)
#字符串
for y in 'abcdef':
print(y)
#字典
d = {'name':'wy','age':18,'job':'stu'}
for z in d:
print(z)
for z in d.keys():
print(z)
for z in d.values():
print(z)
for z in d.items():
print(z)


## range对象

range(start,stop,step)

#利用for循环，计算1-100之间数字的累加和；计算1-100之间偶数的累加和；计算1-100之间奇数的累加和
#方法一
sum_all=0
for i in range(1,101):
sum_all+=i
print("累加和",sum_all)
sum_all=0
for i in range(1,101,2):
sum_all+=i
print("奇数的累加和",sum_all)
sum_all=0
for i in range(2,101,2):
sum_all+=i
print("偶数的累加和",sum_all)
#方法二
sum_all = 0
sum_ou = 0
sum_ji = 0
for i in range(1,101):
sum_all+=i
if i%2 == 0:
sum_ou+=i
elif i%2 != 0:
sum_ji += i
print("1-100的累加和为{0},偶数的累加和为{1},奇数的累加和为{2}".format(sum_all,sum_ou,sum_ji))


## 嵌套循环

for i in range(5):
for j in range(5):
print(i,end='/t')
print()  #起到换行的作用

#打印九九乘法表
for m in range(1,10):
for n in range(1,m+1):
print("{0}*{1}={2}".format(m,n,(m*n)),end='/t')
print()

#用列表和字典存储信息
tb = []
r1 = dict(name='wy',salary='30000',city='bj')
r2 = dict(name='wa',salary='20000',city='ss')
r3 = dict(name='wb',salary='10000',city='rr')
tb = [r1,r2,r3]
for x in tb:
if int(x.get('salary'))>15000:
print(x)


## break 和continue

break跳出最近的一次循环
continue结束本次循环，继续下一次

while True:
a = input("请输入一个字符（输入Q或q的时候退出）：")
if a == 'q' or a == 'Q':
print("循环结束，退出")
break
else:
print(a)
#输入员工薪资，若薪资小于0则重新输入，最后打印出录入员工的数量和薪资明细
empNum = 0
salarySum = 0
salarys = []
while True:
s = input("请输入员工的薪资（按Q或qjie）")
if s.upper()=='Q':
print("录入完成，退出")
break
if float(s)<0:
continue
empNum += 1
salarys.append(float(s))
salarySum += float(s)
print("员工数{0}".format(empNum))
print("录入薪资：",salarys)
print("平均薪资{0}".format(salarySum/empNum))


## else语句

#方法一
while 条件表达式：
循环体
else:
语句块
#方法二
for i in 可迭代对象：
循环体
else:
语句块


salarySum = 0
salarys = []
for i in range(4):
s = input("请输入4名员工的薪资（按Q或q中途结束）")
if s.upper()=='Q':
print("录入完成，退出")
break
if float(s)<0:
continue

salarys.append(float(s))
salarySum += float(s)
else:
print("您已经全部录入4名员工的薪资")

print("录入薪资：",salarys)
print("平均薪资{0}".format(salarySum/4))


## 循环代码的优化

• 尽量减少循环内部不必要的计算
• 嵌套循环中，尽量减少内层循环的计算，尽可能向外提
• 局部变量查询较快，尽量使用局部变量
• 连接多个字符串，使用join()而不使用+
• 列表进行元素插入和删除，尽量在尾部操作

## zip并行迭代

names=("a","b","c","d")
ages=(18,79,56,53)
jobs = ('dd','ss','se')
for a,b,c in zip(names,ages,jobs):
print("{0}--{1}--{2}".format(a,b,c))
for i in range(3):
print("{0}--{1}--{2}".format(names[i],ages[i],jobs[i]))


## 推导式

• 列表推导式
列表推导式生成列表对象，语法如下：
[表达式 for item in 可迭代对象 if 条件判断]
>>> [x for x in range(1,5)]
[1, 2, 3, 4]
>>> [x*2 for x in range(1,5)]
[2, 4, 6, 8]
>>> y = [x*2 for x in range(1,50) if x%5==0]
>>> y
[10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> cells = [(row,col)for row in range(1,10)for col in range(1,10)]
>>> cells
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)]

• 字典推导式
{key_expression: value_expression for 表达式 in 可迭代对象}
#字典推导式
my_text = 'i love you,i love sxt,i love wy'
#统计文本中各个字符出现的次数
char_count={c:my_text.count(c) for c in my_text}
print(char_count)

#使用普通循环实现上面字典推导式
ls1 = []
for i in range(len(my_text)):
ls1.append(my_text[i])
ls2 = list(set(ls1))
for j in range(len(ls2)):
print(str(ls2[j])+":"+str(my_text.count(ls2[j])),end='/t')

• 集合推导式
b = [x for x in range(1,100) if x%9==0]
print(b)

• 生成器推导式
#生成器推导式（生成元组）一个生成器只能运行一次
gnt = (x for x in range(4))
for x in gnt: #gnt是生成器对象,生成器是可迭代的对象，只能使用一次
print(x,end=',')


## 绘制棋盘

#例子：绘制圆
'''
import turtle
t = turtle
my_colors = ("red","green","yellow","black")
t.width(4)
t.speed(0)
for i in range(10): #0,1,2,3,4
t.penup()
t.goto(0,-i*10)     #0,-100,-200,-300,-400
t.pendown()
t.color(my_colors[i%len(my_colors)])
t.circle(15+i*10)           #100,200,300,400,500

turtle.done() #程序执行完，窗口仍然在
'''
#绘制棋盘 18*18
import turtle
t = turtle
t.width(1)
t.speed(0)
for i in range(18): #0,1,2,3,4...
t.goto(i, 0)
t.goto(i,100)
t.penup()
t.goto((i+1)*10,0)
t.pendown()
t.goto((i+1)*10, 100)
t.penup()
t.goto(0,0)
t.pendown()
for j in range(19):
t.goto(0,(100/18)*j)
t.pendown()
t.goto(180,(100/18)*j)
t.penup()
turtle.done()

#(0,0)(0,100)
#(10,0)(10,100)
#(20,0)(20,100)

#(0,0)(180,0)
#(0,(100/18)*1)(180,(100/18)*1)
#(0,(100/18)*2)(180,(100/18)*2)


## 函数用法和底层分析

• 可重用的程序代码块
• 代表一个功能
(1)内置函数
(2)标准库函数
(3)第三方库函数
(4)自定义函数
def 函数名(参数列表)：
“文档字符串”
函数体/若干语句
def test01():
print("*"*10)
print("@"*10)

test01()
test01()
test01()

for i in range(10):
test01()


参数列表

• 圆括号内是形式参数列表，有多个参数则用逗号隔开
• 形式参数不需要声明类型，也不需要指定函数返回值类型
• 无参数，也必须保留空的圆括号
• 实参列表必须与形参列表一一对应

return

• 如果函数体中包含return语句，则结束函数执行并返回值
• 如果函数体中不包含return语句，则返回None值

## 形参和实参

def printMax(a,b):
if a>b:
print(a,"较大值")
else:
print(b,"较大值")
printMax(10,20)
printMax(45,96)


## 函数的注释

def printMax(a,b):
'''用于比较函数的大小，打印较大值 '''
if a>b:
print(a,"较大值")
else:
print(b,"较大值")
printMax(10,20)
printMax(45,96)
help(printMax.__doc__)


## 返回值

def add(a,b):
print("计算两个数的和：{0},{1},{2}".format(a,b,(a+b)))
return a+b
def test02():
print("a")
print("b")
return
print("hello")
def test03(x,y,z):
return [x*10,y*10,z*10]
test02()
print(test03(1,2,3))


Vieu3.3主题

Q Q 登 录