温馨提示×

python中的for循环语句怎么使用

小亿
81
2024-01-03 23:57:16
栏目: 编程语言

Python中的for循环用于遍历一个可迭代对象(如列表、元组、字符串等),并执行特定的操作。

语法格式如下:

for 变量 in 可迭代对象:
    # 执行操作

其中,变量是每次迭代中从可迭代对象中取出的一个元素,可迭代对象是要遍历的对象,操作是在每次迭代中要执行的代码块。

以下是一些for循环的使用示例:

  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. 遍历字典:
student = {"name": "Alice", "age": 18, "grade": "A"}
for key in student:
    print(key, "=", student[key])

输出:

name = Alice
age = 18
grade = A
  1. 使用range()函数进行循环:
for i in range(5):
    print(i)

输出:

0
1
2
3
4

以上是for循环的基本用法,根据具体需求,可以在循环中加入条件判断、嵌套循环等。

0