Python for 循环语句

语法:

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

    变量名;

说明:

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

示例1:

#!/usr/bin/python

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


# 遍历字符串

for ch in 'hello':

print ch;


print 'the end';

代码截图1:

Python for 循环语句

运行截图1:

Python for 循环语句

示例2:

#!/usr/bin/python

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


# 定义列表

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


# 遍历列表

for fruit in fruits:

print fruit;


print 'the end';

代码截图2:

Python for 循环语句

运行截图2:

Python for 循环语句

示例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:

Python for 循环语句

运行截图3:

Python for 循环语句

Python for 循环语句查看更多技术请移步:https://ui.29mn.com