【发布时间】:2021-01-03 14:54:27
【问题描述】:
我在 pycharm 中弄乱了 while 和 for 循环以更好地理解它们,并且我创建了一个操作音乐播放器的模型游戏,其中涉及我一直在学习和研究的一些功能和循环。前任。您可以输入诸如“随机播放”之类的命令,然后从歌曲列表中随机播放一首歌曲。
问题是“下一个”命令不起作用。我无法从列表中播放“下一首”歌曲。本质上,我希望命令在每次输入时循环播放歌曲列表。但无论我如何使用“下一首”功能,它仍然只返回列表中的第一首歌曲。
我尝试将 next() 函数移到代码的其他部分,但它仍然不起作用。您建议我在代码中进行哪些更改以使“下一个”命令起作用?
import random
import itertools
command = ""
player_on = False
paused = False
songs = iter([
"Baby One More Time",
"Hands Up",
"I Believe in a Thing Called Love",
"Unchained Melody",
"Come On Eileen",
"I Want It That Way"
])
next_song = next(songs, "end of playlist")
while True:
command = input("What do you want to do?: ").lower()
if command == "play":
if player_on and not paused:
print("Player is already on.")
paused = False
elif player_on and paused:
paused = False
print("un-paused")
else:
player_on = True
paused = False
print("Playing.")
elif command == "pause":
if paused and player_on:
paused = True
print("player already paused.")
elif player_on and not paused:
print(". . .")
paused = True
else:
print("Turn player on first.")
elif command == "shuffle":
if player_on:
print("Shuffles . . .")
print(random.choice(songs))
else:
print("Turn player on first")
elif command == "next":
if player_on:
paused = False
print(f"Next song: {next_song}")
else:
print("Turn player on first.")
elif command == "quit":
if not player_on:
print("Player is already off.")
else:
player_on = False
break
else:
print("I don't understand that command.")
【问题讨论】:
-
您将
next_song设置为一个常数值。next的输出是 iterable 中的下一个值,所以它每次只查询一次列表。 -
在您提供的代码中,您只在循环之前调用了一次
next()。稍后获取next_song的值不会再次自动运行next()。你必须每次都运行它。
标签: python loops iterator next