美文网首页
[python]-操作列表:for循环

[python]-操作列表:for循环

作者: 阿ll | 来源:发表于2021-02-19 23:57 被阅读0次

需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环。
Python根据缩进来判断代码行与前一个代码行的关系。在for循环后面,没有缩进的代码都只执行一次,而不会重复执行。

例如:

magi = ["alic","davi","caro"]
for nma in magi:
      print(nma.title())
print("Thank you!")

对于上述代码,循环命令只有print(nma.title()),因为只有此命令进行了缩进。

python中for循环的注意事项:

  • for命令后需要有冒号,否则会报错for循环不完整;
  • 对循环命令需换行且缩进;
  • 循环后的命令不需要缩进,如果缩进了,则按for循环处理。
示例1:
##多个循环
magi = ["alic", "davi", "caro"]
for nma in magi:
    print("Hello" + nma.title() + ":")
    print("I can't wait to see your next trick," + nma + ".\n")
print("Thank you!")

输出结果如下:


image.png
示例2:
##最后一行也缩进
magi = ["alic", "davi", "caro"]
for nma in magi:
    print("Hello" + nma.title() + ":")
    print("I can't wait to see your next trick," + nma + ".")
    print("Thank you!\n")

结果:

image.png
【注】\n为换行符。

相关文章

网友评论

      本文标题:[python]-操作列表:for循环

      本文链接:https://www.haomeiwen.com/subject/eesoxltx.html