书籍说明
书名:《Python编程:从入门到实践》(第一版)/Python Crash Course: A Hands-On, Project-Based Introduction to Programming
作者:Eric Matthes(著)/袁国忠(译)
出版社:人民邮电出版社
开发环境说明
Python Version: 3.11.2
Python IDE: PyCharm Community Edition 2022.3.3
目录
第4章 操作列表
4.1 遍历整个列表
- 需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环。
- 下面使用for循环来打印魔术师名单中的所有名字:
-
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician)
输出结果:
alice
david
carolina
4.1.1 深入地研究循环
- for循环,对列表中的每一个元素都执行循环指定的步骤,直到遍历全部元素,跳出循环,接着执行循环结束后的代码。
- 对于用于存储列表中每个值的临时变量,可指定任何名称。
4.1.2 在for循环中执行更多的操作
- 在for循环中,想包含多少行代码都可以,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。
-
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n")
输出结果:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
4.1.3 在for循环结束后执行一些操作
- 在for循环结束后面,没有缩进的代码行都只执行一次,而不会重复执行。
-
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n") print("Thank you, everyone. That was a great magic show!")
输出结果:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
4.2 避免缩进错误
4.2.1 忘记缩进
4.2.2 忘记缩进额外的代码行
4.2.3 不必要的缩进
4.2.4 循环后不必要的缩进
4.2.5 遗漏了冒号
动手试一试
4-1 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来。
修改这个for循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。
在程序末尾添加一行代码,它不在for循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子&