我正在做学校作业,遇到了一些麻烦。为此,我需要使用列表和循环让用户能够将动物和声音输入到两个列表中。然后循环应该以一组的形式输出歌词,在适当的时候使用动物和声音,比如:
And on this farm he had a dog...etc and going through the song, and the next going And on this far he had a cat...etc through all animals and sounds in the list
现在它部分起作用。用户可以输入三种动物和三种声音,然后打印将运行,但只输出列表中的最后一项。我希望它打印的歌词与列表中的所有条目。我还希望用户能够用-1取消,但我尝试过的一切都没有起作用。如果有人能帮忙,那就太好了!到目前为止,我已将代码包括在下面:
for song in range (3):
animal = input("Please Input an Animal: ")
sound = input("Please Input a Sound: ")
lyrics = "Old Macdonald had a farm, E- I- E- I- O," "And on that farm he had a %s, E- I- E- I- O." "With a %s - %s here,And a %s - %s there," "Here a %s, there a %s, Everywhere a %s - %s" "Old Macdonald had a farm, E- I- E- I- O!" % (animal, sound, sound, sound, sound, sound, sound, sound, sound)
print(lyrics)
试试这个
Sunero4已经解释了为什么动物和声音变量只分配给最后一个用户条目。 我在他的答案中添加了一些格式,并在每个用户输入后添加sys.exit(0),以检查是否输入了-1,以便我们可以退出。请注意,我们使用“导入系统”来调用此模块。我不知道你是否已经在课堂上讲过了。如果不是,我建议您看看当前的课程笔记如何处理这个问题
编辑:您可以用quit()替换sys.exit(0),它也会这样做。有关sys.exit()和quit()之间差异的更多详细信息,请查看此处Python exit commands - why so many and when should each be used?
因此,这并没有像您预期的那样起作用,因为您只是重新分配动物和声音变量,而不是将它们添加到列表中。要使其工作,以便用户可以输入三种声音和动物,您可以执行以下操作:
相关问题 更多 >
编程相关推荐