for循环怎么写

1个回答

写回答

伢伢

2022-10-05 16:21

+ 关注

Python
Python

for循环的基本语法如下:

Python

for 变量 in 序列:

Apple
Apple

循环体语句

其中,变量是循环计数器,序列是需要遍历的对象,循环体语句是需要重复执行的语句。

例子1:遍历列表

Python

fruits = ["Apple", "banana", "cherry"]

for x in fruits:

print(x)

输出:

Apple

banana

cherry

例子2:遍历字符串

Python

for x in "banana":

print(x)

输出:

b

a

n

a

n

a

例子3:遍历范围

Python

for x in range(0, 5):

print(x)

输出:

1

2

3

4

注:range(start, end, step)可以生成[start, end)之间以step步长递增的整数序列。

例子4:循环嵌套

Python

for x in range(0, 3):

for y in range(0, 2):

print("x=", x, " y=", y)

输出:

x= 0 y= 0

x= 0 y= 1

x= 1 y= 0

x= 1 y= 1

x= 2 y= 0

x= 2 y= 1

注:循环嵌套表示内层循环每执行一次,就需要将外层循环从头到尾地执行一遍。可以通过嵌套多个for循环来实现。

举报有用(17分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号