學習 Python 3 the Hard Way 第 40 課的課程。我正在盡我最大的努力來理解這個“for循環”是如何計算的?!皩τ?self.lyrics 中的行:打?。ㄐ校蔽疫€想知道如何將“行”轉換為數字,以便可以在歌詞行頂部打印行號。我的輕微修改是添加另一行“你為什么臟老鼠”,看看它是否會按預期打印。我還刪除了逗號,并按預期添加了該行class Song(): def __init__(self, lyrics): self.lyrics = lyrics---------------------------------------------------- def sing_me_a_song(self): for line in self.lyrics: print(line)----------------------------------------------------happy_bday = Song(["Happy birthday to you", "I don't want to get sued ", "Why you dirty rat", "So ill stay right there"])bulls_on_parade = Song(["They rally around tha family", "With pockets full of shells"])print("\n")happy_bday.sing_me_a_song()print("\n")bulls_on_parade.sing_me_a_song()print("\n")```
2 回答

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
我可以想到兩種方法供您執行此操作。
第一種方法是為“for”循環獲取循環計數器。第二種方法是使用范圍迭代列表或元組。
方法一:
class Song():
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
i = 0
for line in self.lyrics:
i = i + 1 # i here for first line 1 or after print for first line 0
print(str(i) + " : " + line)
方法二:
class Song():
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for i in range(0,len(self.lyrics)):
print(str(i + 1) + " : " + self.lyrics[i]) # i + 1 to start at line 1 or just i to start at line 0
添加回答
舉報
0/150
提交
取消