一、功能
for 循环提供了python中最强大的循环结构(for循环是一种迭代循环机制,而while循环是条件循环,迭代即重复相同的逻辑操作,每次操作都是基于上一次的结果,而进行的)
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
二、语法
for循环的一般格式如下:
for iter_var in iterable:
suite_to_repeat
注解:每次循环, iter_var 迭代变量被设置为可迭代对象(序列, 迭代器, 或者是其他支持迭代的对 象)的当前元素, 提供给 suite_to_repeat 语句块使用.
python for循环实例
msg="hello egon 666"
for i in (msg):
print(i)
name_list=['alex','eric','rain','xxx']
#通过序列项迭代
for i in name_list:
print(i)
#通过序列索引迭代
for i in range(len(name_list)):
print('index is %s,name is %s' %(i,name_list[i]))
#基于enumerate的项和索引
for i,name in enumerate(name_list,2):
print('index is %s,name is %s' %(i,name))
三、小节
for循环为迭代循环
可遍历序列成员(字符串,列表,元组)
可遍历任何可迭代对象(字典,文件等)
可以用在列表解析和生成器表达式中
break,continue,else在for中用法与while中一致
网友评论