Python for循环的使用
(一)for循环的使用场景
1.如果我们想要某件事情重复执行具体次数的时候可以使用for循环。
2.for循环主要用来遍历、循环、序列、集合、字典,文件、甚至是自定义类或函数。
(二)for循环操作列表实例演示
使用for循环对列表进行遍历元素、修改元素、删除元素、统计列表中元素的个数。
1.for循环用来遍历整个列表
1,#for循环主要用来遍历、循环、序列、集合、字典
2,Fruits=['apple','orange','banana','grape']
3,for fruit in Fruits:
4, print(fruit)
5,print("结束遍历")
结果演示:
1, apple
2, orange
3, banana
4, grape
2.for循环用来修改列表中的元素
1,#for循环主要用来遍历、循环、序列、集合、字典
2,#把banana改为Apple
3,Fruits=['apple','orange','banana','grape']
4,for i in range(len(Fruits)):
5,if Fruits[i]=='banana':
6,Fruits[i]='apple'
7,print(Fruits)
1,结果演示:['apple', 'orange', 'apple', 'grape']
3.for循环用来删除列表中的元素
1,Fruits=['apple','orange','banana','grape']
2,for i in Fruits:
3,if i=='banana':
4, Fruits.remove(i)
5,print(Fruits)
6,结果演示:['apple', 'orange', 'grape']
4.for循环统计列表中某一元素的个数
1,#统计apple的个数
2,Fruits=['apple','orange','banana','grape','apple']
3,count=0
4,for i in Fruits:
5, if i=='apple':
6, count+=1
7,print("Fruits列表中apple的个数="+str(count)+"个")
8,结果演示:Fruits列表中apple的个数=2个
注:列表某一数据统计还可以使用Fruit.count(object)
5.for循环实现1到9相乘
1,sum=1
2,for i in list(range(1,10)):
3, sum=i
4,print("12...10="+str(sum))
5,结果演示:12...*10=362880
6.遍历字符串
1,for str in 'abc':
2, print(str)
结果演示:
1,a
2,b
3,c