python-循环(loop)-for循环

for 循环

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

输出结果为


把 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')



原文地址:https://www.cnblogs.com/goodright/p/5893699.html