编写 for 循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。然而,选择描述单个列表元素的有意义的名称大有帮助。
# 临时变量名称案例for cat in cats:for dog in dogs:for item in list_of_items:
在for循环中执行更多的操作
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.
在for循环结束后执行一些操作
在 for 循环后面,没有缩进的代码都只执行一次,而不会重复执行。
# for循环结束后执行案例
magicians =['alice','david','carlolina']for magician in magicians:print(magician.title()+", that was a great trick!")print("I can't wait to see you next trick, "+ magician.title()+".\n")print("Thank you, enveryone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see you next trick, Alice.
David, that was a great trick!
I can't wait to see you next trick, David.
Carlolina, that was a great trick!
I can't wait to see you next trick, Carlolina.
Thank you, enveryone. That was a great magic show!
练习
# 1.比萨# 想出至少三种喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来# 修改这个for循环,使其打印包含比萨名称的句子,对于每种比萨都显示一行输出,如“I like pizza”# 在程序末尾添加一行代码,不在for循环里,指出你有多喜欢比萨,输出应包含对每种比萨的消息,还有一个总结性句子,如“I reall love pizza”
pizzas =['chess pizza','beef pizza','corn pizza','pepperoni pizza']for pizza in pizzas:print(pizza)print("#"*20)for pizza in pizzas:print("I like "+ pizza.title()+"!")print("\nI reall love pizza!")
chess pizza
beef pizza
corn pizza
pepperoni pizza
####################
I like Chess Pizza!
I like Beef Pizza!
I like Corn Pizza!
I like Pepperoni Pizza!
I reall love pizza!
# 2.动物# 想出至少3种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来# 修改这个程序,使每种动物都打印一个句子,如“A dog would make a great pet”。# 在程序末尾添加一行代码,指出这些动物的共同之处,如:“Any of these animals would make a great pet!”
animals =['goat','sheep','lamb']for animal in animals:print(animal)print("A "+ animal.title()+" would make a great pet.")print("\nAny of these animals would make a great pet!")
goat
A Goat would make a great pet.
sheep
A Sheep would make a great pet.
lamb
A Lamb would make a great pet.
Any of these animals would make a great pet!