for 循环
Python 中的循环有两种,分别是 while 和 for 循环。for 循环常用于遍历字符串、列表、元组、字典、集合等序列类型,逐个获取序列中的各个元素。
语法格式:
for 迭代变量 in 字符串|列表|元组|字典|集合:
代码块
迭代变量用于存放从序列类型变量中读取出来的元素,所以一般不会在循环中对迭代变量手动赋值;代码块指定是具有相同缩进格式的多行代码(和 while 一样),由于和循环结构联用,因此代码块也成为循环体。
示例:
1 add = "www.taobao.com and www.huawei.com"
2 # for循环,遍历 add 字符串
3 for a in add:
4 print(a, end="")
结果:
www.taobao.com and www.huawei.com
for 循环具体应用:
数值循环:
1 print("计算 1+2+3....+100的结果")
2 # 保存累加结果变量
3 sum = 0
4 # 逐个获取从 1 到 100 这些值,并做累加操作
5 for i in range(101):
6 sum += i
7 print(sum)
结果:
计算 1+2+3....+100的结果
5050
遍历列表:
1 list = [1, 2, 3, 4, 5, 6, 7, 8]
2 for ele in list:
3 print("ele =", ele)
结果:
ele = 1
ele = 2
ele = 3
ele = 4
ele = 5
ele = 6
ele = 7
ele = 8
遍历字典:
1 str = {'Python教程': 'https://www.runoob.com/python3/python3-tutorial.html',\
2 'Shell教程': 'https://www.runoob.com/linux/linux-shell.html',\
3 'Java教程': 'https://www.runoob.com/java/java-tutorial.html'}
4 for i in str:
5 print('i =', i)
结果:
i = Python教程
i = Shell教程
i = Java教程
遍历字典 values()、items() 方法的返回值。
示例:
1 str = {'Python教程': 'https://www.runoob.com/python3/python3-tutorial.html',\
2 'Shell教程': 'https://www.runoob.com/linux/linux-shell.html',\
3 'Java教程': 'https://www.runoob.com/java/java-tutorial.html'}
4 for i in str.items():
5 print('i =', i)
结果:
i = ('Python教程', 'https://www.runoob.com/python3/python3-tutorial.html')
i = ('Shell教程', 'https://www.runoob.com/linux/linux-shell.html')
i = ('Java教程', 'https://www.runoob.com/java/java-tutorial.html')