Python中的for循环可以通过以下方式进行编写:

  1. 遍历列表:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)
  1. 遍历字符串:
my_string = 'Hello World'
for char in my_string:
    print(char)
  1. 遍历字典:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
    print(key, value)
  1. 遍历范围:
for i in range(10):
    print(i)

其中,range()函数可以指定范围的起始值、结束值和步长。例如:

for i in range(1, 10, 2):
    print(i)

输出结果为:

1
3
5
7
9
Python For循环详解:列表、字符串、字典、范围遍历

原文地址: https://www.cveoy.top/t/topic/owKW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录