python for循环案例-Python循环语句for的实际运用方法案例

Python循环语句for的实际运用方法案例

for循环

for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个二元素以此访问一遍)。

1、for循环使用情景

我们想要某个操作重复执行且循环次数已知是可以使用for循环;

所有否循环均可以用while实现。

2、语法格式

for i in 一组值: #一组值可以是除数字以外的基本类型要执行的操作

3、for循环操作实例

for循环可遍历除数字以外的数据基本类型,如字符串,元组,列表,集合,字典,文件等。我们还可以通过序列索引进行遍历。具体操作如下所示:

①for循环遍历字符串

#for循环遍历字符串

str='abc'

for i instr:

print(i)

结果如下:

a

b

c

②for循环遍历元组

tup1=(31,29,31,30,31,30,31,31,30,31,30,31)

for i in tup1:

print(i,end=' ') #end=' ' 不换行

结果如下:

31 29 31 30 31 30 31 31 30 31 30 31

③for循环遍历列表

Fruits=['apple','orange','banana','grape']forfruit in Fruits:

print(fruit)

结果如下:

apple

orange

banana

grape

④for循环遍历集合

set1={'lisi',180,60,99}for i inset1:

print(i)

结果如下:

lisi99

180

60

⑤for 循环遍历字典

注意:Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

dict1={'name':'lisi','height':180,'weight':60,'score':99}for k,v indict1.items(): #遍历字典dict1中的键值对

print(k,'--->',v)

print('--------------')for k indict1.keys(): #遍历字典dict1中所有的键

print(k)

print('--------------')for v indict1.values(): #遍历字典dict1中所有的值

print(v)

结果如下:

name--->lisi

height---> 180weight---> 60score---> 99

--------------name

height

weight

score--------------lisi180

60

99

⑥遍历文件

for content in open("1.txt"): #当前目录下的1.txt

print(content)

结果如下:

朝辞白帝彩云间,千里江陵一日还。

两岸猿声啼不住,轻舟已过万重山。

⑦for循环实现1到9连乘

sum = 1

for i in list(range(1,10)): #range序列含左不含右

sum*=i

print("1*2...*9 =",sum)

结果如下:1*2...*9 = 362880

⑧除以上之外,我们还可以通过序列索引进行遍历

range的用法: range(5)——>1个参数,从0开始到5不包含5(即含左不含右);range(5,15)——>2个参数,从5开始到15不包含15;range(5,55,5)——>3个参数,从5开始到55不包含55,最后的参数5是步长。

下面实例我们使用内置函数len()和range();函数len()返回列表的长度,即元素个数。range返回一个整数序列。

fruits = ['banana','apple','mango','grape']for index inrange(len(fruits)):

print('当前水果 :', fruits[index])

结果如下:

当前水果 : banana

当前水果 : apple

当前水果 : mango

当前水果 : grape

原文链接:https://blog.csdn.net/python6_quanzhan/article/details/106362766

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值