1

我是 python 的初学者,我有一个任务,我需要使用明确的循环、字符串累加器和连接打印出一首歌曲。问题是,我能够在一个明确的循环中打印出每个节(这首歌假设一首 3 节歌曲,因此范围设置为 3),并且在创建每个节之前,它要求用户输入一个动物,它是声音(它的老麦克唐纳)。我完成了任务的第一部分,即在用户提供输入后打印每个节,但第二部分要求将所有节(总共 3 个)连接到整首歌曲中。所以最终的结果是把单独的小节放在一首歌曲中。问题是,鉴于我必须更新歌曲然后在最后输出整首歌曲,我该如何使用累加器?附上我的代码:

def main():


    for stanza in range(3):
        animal = raw_input("What animal? ")
        animalSound = raw_input("What sound does a %s make? " %(animal))

        print
        print "\t Old MacDonald had a farm, E-I-E-I-O,"
        print "And on his farm he had a %s, E-I-E-I-O" %(animal)
        print "With a %s-%s here - " %(animalSound, animalSound)
        print "And a %s-%s there - " %(animalSound, animalSound)
        print "Here a %s there a %s" %(animalSound, animalSound)
        print "Everywhere a %s-%s" %(animalSound, animalSound)
        print "Old MacDonald had a farm, E-I-E-I-O"
        print
4

2 回答 2

2

By "accumulator", I assume you mean the pattern in which you continuously add to a previous string. This can be had with the operator +=.

By "concatenation", I assume you mean the string operator +.

By your own rules, you aren't allowed the % operator.

You might do it this way:

song = ''  # Accumulators need to start empty
for _ in range(3):  # Don't really need the stanza variable
    animal = raw_input("What animal? ")
    animalSound = raw_input("What sound does a %s make? " %(animal))

    song += "Old MacDonald had an errno. EIEIO\n"
    song += "His farm had a " + animal + " EIEIO\n"
    song += "His " + animal + "made a noise: " + animalSound + "\n"
print song

etc.

I believe this is what your assignment calls for, but realize that this would not be considered "good" or "Pythonic" code. In particular, string accumulation is inefficient -- prefer list comprehensions and str.join().

于 2013-09-21T08:10:27.987 回答
0

不是打印每一行,而是将每一行放入一个列表中。例如:

lyrics = ['\t Old MacDonald had a farm, E-I-E-I-O,', "And on his farm he had a %s, E-I-E-I-O" % animal, etc]

然后,当您打印它时,使用该str.join()方法,如下所示:

print '\n'.join(lyrics)

这将打印列表中的每个项目,并以新行 ( ) 分隔'\n'

现在,使用歌词列表,您可以将其附加到另一个包含每个节的列表中。在循环之外,可能会放一些类似的东西:

stanzas = []

然后,在循环内,执行:

stanzas.append(lyrics)

会将列表附加lyrics到另一个列表stanzas,因此在循环结束时,您将拥有三个列表stanzas。再次,要打印列表中的每个项目,请使用str.join().

于 2013-09-21T03:16:09.203 回答