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("1*2…10="+str(sum))
5,结果演示:1
2…*10=362880

6.遍历字符串
1,for str in ‘abc’:
2, print(str)

结果演示:
1,a
2,b
3,c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值