Python新手指南:如何使用for循环遍历序列

原创 冷不防 2025-02-12 08:21 46阅读 0赞

在Python中,for循环是一种常见的迭代工具,用于遍历各种序列类型。下面是一个基本的for循环遍历序列的例子:

  1. 列表(List)

    1. fruits = ['apple', 'banana', 'orange']
    2. for fruit in fruits:
    3. print(fruit)

    输出:

    1. apple
    2. banana
    3. orange
  2. 字符串(String)

    1. sentence = "Hello, world!"
    2. for char in sentence:
    3. print(char)

    输出:
    ```
    H
    e
    l
    l
    ,

w
o
r
l
d
!

  1. 3. **元组(Tuple)**:
  2. ```python
  3. colors = ('red', 'green', 'blue'))
  4. for color in colors:
  5. print(color)

输出:

  1. red
  2. green
  3. blue

以上就是Python中使用for循环遍历序列的基本操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,46人围观)

还没有评论,来说两句吧...

相关阅读