Peng~666

DAY-3(二补):

在列表基础上开始学习for循环:

  1. for循环基本用法

# 命名约定举例:
# for cat in cats:
# for dog in dogs:
# for item in list_of_items:

magicians = ['alice','david','carolina']
for magician in magicians:
    print (magician)
# 将输出:
# alice
# david
# carolina
  1. for循环中执行更多操作

magicians = ['alice','david','carolina']
for magician in magicians:
    print (f"{magician.title()},that was a great tricks!")
    print (f"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 tricks!
# I can't wait to see your next trick, Alice.

# David,that was a great tricks!
# I can't wait to see your next trick, David.

# Carolina,that was a great tricks!
# I can't wait to see your next trick, Carolina.

# Thank you, everyone. That was a great magic show!

# 使用 for 循环处理数据,是一种对数据集执行整体操作的不错方式。例如,你可能使用 for 循环来初始化游戏——遍历角色列表,将每个角色都显示到屏幕上;然后在循环后面添加一些代码,在屏幕上绘制所有角色后显示一个 Play Now 按钮。
  1. 小练习:

# 练习:想出至少三种有共同特征的动物,将其名称存储在一个列表中,再使用 for 循环将每种动物的名称打印出来
pets = ['cat','dog','chick','sheep','cow']
for pet in pets:
    print (f"A {pet.title()} would make a great pet.")
print ("Any of these animals would make a great pet!")
# 将输出:A Cat would make a great pet.
# A Dog would make a great pet.
# A Chick would make a great pet.
# A Sheep would make a great pet.
# A Cow would make a great pet.
# Any of these animals would make a great pet!

评论区