目录
一、遍历列表
和所有编程语言一样,首先可以考虑 for 循环
egs = [ 'aa', 'bb', 'cc' ]
for eg in egs:
print(eg)
定义了一个列表,并定义一个 for 循环,:对于(for)列表 egs 中的每位 eg,都打印(print)元素 eg。输出结果如下:
aa
bb
cc
然后再写一个稍微复杂点的 for 循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")
注意:Python 根据缩进来判断代码行与程序其他部分的关系
输出结果如下:
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!
在 for 循环后面,没有缩进的代码都只执行一次。
二、创建数值列表
列表非常适合用于存储数值集合,而 Python 提供了很多工具&#