Python for 循环语句

2023-06-28,,

语法:

for 变量名 in 字符串/列表:

    变量名;

说明:

for循环可以遍历任何序列的项目,如一个列表或者一个字符串

示例1:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# 遍历字符串

for ch in 'hello':

print ch;

print 'the end';

代码截图1:

运行截图1:

示例2:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# 定义列表

fruits = ['apple','pear','banana'];

# 遍历列表

for fruit in fruits:

print fruit;

print 'the end';

代码截图2:

运行截图2:

示例3:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# 定义列表

fruits = ['apple','pear','banana'];

# 遍历列表,通过序列索引迭代

for index in range(len(fruits)):

print index,fruits[index];

print 'the end';

代码截图3:

运行截图3:

查看更多技术请移步:https://ui.29mn.com

《Python for 循环语句.doc》

下载本文的Word格式文档,以方便收藏与打印。