for 循环

for every_letter in 'Hello world':
print(every_letter)

输出结果为

python-循环(loop)-for循环

 


把 for 循环所做的事情概括成一句话就是:于...其中的每一个元素,做...事情。

python-循环(loop)-for循环

在关键词 in 后面所对应的一定是具有“可迭代的”(iterable)或者说是像列表那样的集合形态的对象,即可以连续地提供其中的每一个元素的对象。

使用for循环创建内置函数一一range

如何打印出这样的结果?

1 + 1 = 2  
2 + 1 = 3
.
.
10 + 1 = 11
for num in range(1,11):#不包含11,因此实际范围是1~10
print(str(num)+' + 1 =',num + 1)

把 for 和 if 结合起来使用。实现这样一个程序:歌曲列表中有三首歌“Holy Diver, Thunderstruck, Rebel Rebel”,当播放到每首时,分别显示对应的歌手名字“Dio, AC/DC, David Bowie”。
songslist = ['Holy Diver','Thunderstruck','Rebel Rebel']
for song in songslist:
if song == 'Holy Diver':
print(song,' - Dio')
elif song == 'Thunderstruck':
print(song,' - AC/DC')
elif song == 'Rebel Rebel':
print(song,' - David Bowie')



 
                    
            
                

相关文章:

  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
  • 2021-12-05
  • 2021-09-21
  • 2022-01-06
猜你喜欢
  • 2021-10-18
  • 2022-12-23
  • 2021-09-20
  • 2021-08-30
  • 2021-12-29
  • 2021-12-16
  • 2022-12-23
相关资源
相似解决方案