美文网首页
Python for循环的使用

Python for循环的使用

作者: 一雨成慕 | 来源:发表于2018-08-19 14:54 被阅读0次

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

相关文章

  • python 循环语句

    本次将为大家介绍Python循环语句的使用。Python中的循环语句有 for 和 while。Python循环语...

  • 14、python循环语句

    本章节将为大家介绍Python循环语句的使用。Python中的循环语句有 for 和 while。 while循环...

  • python基础知识点总结

    知识点 一 .python语言 1. 1 基础 Python中循环包括两种: 遍历循环和无限循环。遍历循环使用保留...

  • Python基础002--for、while、列表解析

    python注释以及换行符的使用、for循环和while循环、列表解析 python中的注释# --->单行注释三...

  • 循环的使用

    while循环的使用 代码块 for循环的使用 1,Python for循环可以遍历任何序列的项目,如一个列表或者...

  • for循环以及while循环

    for 循环 python中的循环:for循环、while循环// (一个操作需要重复多次执行,这个时候就考虑使用...

  • 3 Python基础

    Python基础 1.循环语句 while循环 for循环 1.1 循环语句的基本使用 1.2 综合小案例 1.3...

  • 2018年6月14日【Python学习笔记】

    一、for循环 python中循环:for循环、while循环(一个操作需要重复执行多次,这个时候就考虑使用循环)...

  • Python for循环的使用

    Python for循环的使用 (一)for循环的使用场景 1.如果我们想要某件事情重复执行具体次数的时候可以使用...

  • 2018-07-19 python循环语句

    循环的概念需要重复执行某个过程,就可以使用循环。python中的循环有for循环和while循环 1.for循环 ...

网友评论

      本文标题:Python for循环的使用

      本文链接:https://www.haomeiwen.com/subject/gjuciftx.html