for 迭代变量 in 字符串|列表|元组|字典|集合:
代码块
图 1 for 循环语句的执行流程图
add = "http://task.lmcjl.com/python/" #for循环,遍历 add 字符串 for ch in add: print(ch,end="")运行结果为:
http://task.lmcjl.com/python/
可以看到,使用 for 循环遍历 add 字符串的过程中,迭代变量 ch 会先后被赋值为 add 字符串中的每个字符,并代入循环体中使用。只不过例子中的循环体比较简单,只有一行输出语句。print("计算 1+2+...+100 的结果为:") #保存累加结果的变量 result = 0 #逐个获取从 1 到 100 这些值,并做累加操作 for i in range(101): result += i print(result)运行结果为:
计算 1+2+...+100 的结果为:
5050
my_list = [1,2,3,4,5] for ele in my_list: print('ele =', ele)程序执行结果为:
ele = 1
ele = 2
ele = 3
ele = 4
ele = 5
my_dic = {'python教程':"http://task.lmcjl.com/python/",\ 'shell教程':"http://task.lmcjl.com/shell/",\ 'java教程':"http://task.lmcjl.com/java/"} for ele in my_dic: print('ele =', ele)程序执行结果为:
ele = python教程
ele = shell教程
ele = java教程
my_dic = {'python教程':"http://task.lmcjl.com/python/",\ 'shell教程':"http://task.lmcjl.com/shell/",\ 'java教程':"http://task.lmcjl.com/java/"} for ele in my_dic.items(): print('ele =', ele)程序执行结果为:
ele = ('python教程', 'http://task.lmcjl.com/python/')
ele = ('shell教程', 'http://task.lmcjl.com/shell/')
ele = ('java教程', 'http://task.lmcjl.com/java/')
本文链接:http://task.lmcjl.com/news/9451.html