五、循环
本章内容运行环境:
Jupyter Notebook
本单元视频链接:https://v.youku.com/v_show/id_XNDYyNTQ1MTcyMA==.html
5.1 for 循环
for item in list_of_items:
pass
-
in
后面,是一个列表 -
for -- in ---:
不要忘记这个:
- 下一行要缩进,缩进几个字符都可以,但是要保证上下文统一
这里需要注意,在Python中,缩进
非常非常非常重要。
学过C或者MATLAB等其他编程语言的同学应该了解,一般是用{}
来把函数包裹起来,系统通过{
判定函数开始,}
判定函数结束。
但是Python是通过缩进
来判断的,所以你的缩进
必须一致。比如都用2个空格,或者都用4个空格。
nameList = ['Yangyang','Lindy','Alice','Leimei','Jack']
for eachName in nameList:
print(eachName)
# 输出:
# Yangyang
# Lindy
# Alice
# Leimei
# Jack
nameList = ['Yangyang','Lindy','Alice','Leimei','Jack']
for eachName in nameList:
print(eachName, ', Hello')
# 输出:
# Yangyang , Hello
# Lindy , Hello
# Alice , Hello
# Leimei , Hello
# Jack , Hello
看一下缩进的区别
nameList = ['Yangyang','Lindy','Alice','Leimei','Jack']
for eachName in nameList:
print(eachName)
print('Hello!')
# 输出:
# Yangyang
# Hello!
# Lindy
# Hello!
# Alice
# Hello!
# Leimei
# Hello!
# Jack
# Hello!
nameList = ['Yangyang','Lindy','Alice','Leimei','Jack']
for eachName in nameList:
print(eachName)
print('Hello!')
# 输出:
# Yangyang
# Lindy
# Alice
# Leimei
# Jack
# Hello!
range()
在上一章列表里,我们学习了可以用range()
函数生成列表
for i in range(5): # 等价于range(0,5,1)
print(i)
# 输出:
0
1
2
3
4
练习:生成一个列表[0,1,4,9,16,25,36,49....]
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
# 输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
练习:生成九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print("{}*{}={}".format(i,j,i*j),end=" ")
print("\n")
5.2 列表推导式
(大概了解就可以,现在没办法掌握,也没关系)
拿刚刚求平方的代码为例,我们原来是这么写的
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
#输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
有了列表推导式,我们可以这么写
squares = [i**2 for i in range(10)]
print(squares)
#输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
两者的输出是一样的,只是列表推导式更简洁和高效
5.3 while 循环
while expression:
pass
while
循环的内容会一直循环执行, 直到 expression 值为假(条件失效), 循环结束
count = 0
while (count < 9):
print( 'the index is:', count)
count += 1
#输出:
the index is: 0
the index is: 1
the index is: 2
the index is: 3
the index is: 4
the index is: 5
the index is: 6
the index is: 7
the index is: 8
while循环常常用于你不确定,这个循环,要循环多少次
用《Python编程:从入门到实践,7.2.2节》中的一个例子:
不管用户输入什么,系统都会重复一遍,直到用户输入“quit”,程序结束
print("Tell me something, and I will repeat it back to you:")
message = ""
while message != "quit":
message = input("Your input:")
print("Output:",message)
# 输出:
# Tell me something, and I will repeat it back to you:
# Your input:hi,I'm yangyang
# Output: hi,I'm yangyang
# Your input:quit
# Output: quit
避免无限循环
x = 1
while x <= 5:
print(x)
x += 1
如果你忘记了x += 1
,这个程序就会陷入无限循环
可以通过Ctrl+C
退出,也可以直接把软件关了。。
5.4 break 和 continue
break:停止循环(直接退出了)
举个例子:在一大堆士
中,找到土
,就结束(break)
shi_and_tu = ["士","士","士","士","士","士","士","土","士","士","士","士"]
for char in shi_and_tu:
print(char)
if char == "土":
print("我找到土啦!")
break
continue:跳过循环(本次退出,下次还来)
举个例子:未满18岁的输出,超过18岁的,就跳过(continue)
ages = [16, 15, 23, 33, 67, 8, 10, 32]
for age in ages:
if age >= 18:
continue
print(age)
print("未达到18岁,不可以买酒")
5.5 实践:输出豆瓣首页数据
【小练习】
给定整数序列, 求这个序列中子序列和的最大值
number = [-2, 11, 8, -4, -1, 16, 5, 0]
sum_n = []
for i in range(len(number)):
sum_n.append(number[i])
for j in range(i):
sum_n.append(sum(number[j:i+1]))
print(max(sum_n))
【清洗豆瓣数据】
结合【3.11节,字符串】的实践,输出豆瓣电影 Top 250,前25部电影详情
思路:
- 先去网站上,把所有内容贴下来,保存到
txt
文件中 - 读取txt文件
- 切割字符串
- 加入循环,输出前25项结果
注意:
- 注意
txt
文件的路径,要么和代码保存在一个路径下面,要么把路径写正确 -
for
循环别忘记冒号:
- 注意缩进,保持统一
参考代码:
text = open('D:/Python/html_text.txt', 'rb')
text = text.read().decode('utf-8')
movies = text.split('class="grid_view\">')[1].split('<li>') #movies此时是一个列表
for i in range(1,len(movies)):
movie = movies[i] # 把movies这个列表的值,依次取出
title = movie.split('</span>')[0].split('>')[-1]
rate = movie.split('v:average\">')[1].split('</span>')[0]
number = movie.split('star')[1].split('<span>')[1].split('</span>')[0]
quote = movie.split('inq')[1].split('>')[1].split('<')[0]
year = movie.split(' <p class="">')[1].split('<br>')[1].split(' ')[0].strip()
print("{},《{}》,豆瓣评分{},{}。推荐理由:{}".format(year,title, rate, number, quote))
请在作业的最后一行输出:
昵称:第5节课作业