温馨提示×

python中for循环语句如何使用

小亿
102
2023-09-14 20:18:36
栏目: 编程语言

在Python中,for循环用于迭代一个可迭代对象(如列表、元组、字符串等)中的元素。

语法结构:

for 变量 in 可迭代对象:
# 循环体代码

示例:

  1. 遍历列表中的元素
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

输出:

apple
banana
cherry
  1. 遍历字符串中的字符
message = 'Hello, World!'
for char in message:
print(char)

输出:

H
e
l
l
o
,
W
o
r
l
d
!
  1. 使用range()函数生成一个数字序列进行迭代
for i in range(5):
print(i)

输出:

1
2
3
4

在循环体内部,可以进行任何需要重复执行的操作,例如条件判断、函数调用等。可以使用break关键字提前结束循环,或使用continue关键字跳过当前迭代。

0