在 Python 中,有多种循环语句可供使用,包括 for 循环和 while 循环。以下是它们的基本用法:for 循环
# 通过 for 循环遍历列表中的元素
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
输出:
apple
banana
cherry
# 通过 for 循环遍历字符串中的字符
for char in "hello":
print(char)
输出:
h
e
l
l
o
while 循环
# 使用 while 循环打印数字直到达到特定条件
count = 0
while count < 5:
print(count)
count += 1
输出:
0
1
2
3
4
# 使用 while 循环遍历列表中的元素
fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
输出:
apple
banana
cherry
以上是 Python 中 for 和 while 循环的基本用法。这些循环语句对于迭代列表、字符串以及执行特定条件下的重复操作非常有用。