在 Python 中,可以使用 `for` 循環語句來迭代遍歷可迭代對象(如列表、元組、字符串等)中的元素。`for` 循環的基本語法如下:
for item in iterable:
# 執行語句塊
其中,`item` 是一個臨時變量,用于迭代遍歷 `iterable` 中的每個元素。在每次迭代中,執行位于 `for` 循環內部的語句塊。
下面是一些 `for` 循環的示例:
1. 遍歷列表:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 輸出:
# apple
# banana
# cherry
2. 遍歷字符串:
message = "Hello, World!"
for char in message:
print(char)
# 輸出:
# H
# e
# l
# l
# o
# ,
#
# W
# o
# r
# l
# d
# !
3. 遍歷字典的鍵或值:
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in person:
print(key)
# 輸出:
# name
# age
# city
for value in person.values():
print(value)
# 輸出:
# Alice
# 25
# New York
4. 使用 `range()` 函數生成數字序列:
for i in range(5):
print(i)
# 輸出:
# 0
# 1
# 2
# 3
# 4
在 `for` 循環中,還可以使用 `break` 關鍵字跳出循環,以及 `continue` 關鍵字跳過當前迭代,進入下一次迭代。
注意,在 Python 中的 `for` 循環更多地被用于遍歷可迭代對象,而不是根據索引進行迭代。如果需要根據索引進行循環,可以使用 `range()` 函數生成索引序列,并通過索引訪問元素。