【发布时间】:2021-04-06 17:32:09
【问题描述】:
我正在尝试运行一个循环,在列表中打印歌词行,然后在达到可变限制量时停止。虽然我已经尝试了两种不同结果的两种方法,但都不正确。
我遇到的问题:
lyrics = ["I wanna be your endgame", "I wanna be your first string",
"I wanna be your A-Team", "I wanna be your endgame, endgame"]
lines_of_sanity = 6
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Recall the Earworm problem (3.3.5 Coding Exercise 2). The
#first time, you would still finish printing the entire list
#of lyrics after lines_of_sanity was exceeded.
#
#Revise that code so that you always stop when lines_of_sanity
#is reached. If lines_of_sanity is 6, you would print 6 lines,
#no matter how many lines are in the list. If there are fewer
#than 6 lines in the list, then you'd repeat the list until
#the number of lines is reached.
#
#For example, with the values above, you'd print:
#I wanna be your endgame
#I wanna be your first string
#I wanna be your A-Team
#I wanna be your endgame, endgame
#I wanna be your endgame
#I wanna be your first string
#MAKE IT STOP
#
#That's 6 lines: the entire list once, then the first two lines
#again to reach 6. As before, print MAKE IT STOP when you're
#done.
#
#HINT: There are multiple ways to do this: some involve a small
#change to our earlier answer, others involve a more wholesale
#rewrite. If you're stuck on one, try to think of a totally
#different way!
#Add your code here! Using the initial inputs from above, this
#should print 7 lines: all 4 lines of the list, then the first
#two lines again, then MAKE IT STOP
我的答案及其产生的结果:
counter = 0
while counter <= lines_of_sanity:
for item in (lyrics):
print(item)
counter += len(lyrics)
print("MAKE IT STOP")
我们用歌词 = ["I want to be your endgame", "I want 成为你的第一根弦”、“我想成为你的 A-Team”、“我想成为你的 endgame, endgame"], lines_of_sanity = 6. 我们希望您的代码能够 打印这个:
我想成为你的残局我想成为你的第一根弦我想成为你的 A-Team 我想成为你的残局,残局我想成为你的残局我 想成为你的第一个字符串 MAKE IT STOP
但是,它打印了这个:
我想成为你的残局我想成为你的第一根弦我想成为你的 A-Team 我想成为你的残局,残局 MAKE IT STOP
在这一点上,它似乎只是比lines_of_sanity少打印一行
或者我的第一次尝试是:
counter = 0
while counter <= lines_of_sanity:
for item in (lyrics):
print(item)
counter += 1
print("MAKE IT STOP")
这似乎将列表中的每个项目打印两次(直到超过 lines_of_sanity),这给了我 8 行
【问题讨论】: