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