我是Python的初学者,我有一个作业,要求我使用确定循环、字符串累加器和连接来打印一首歌曲。问题是,我能够以明确的循环打印出每个节(这首歌假设有 3 节歌曲,因此范围设置为 3),并且在创建每个节之前,它要求用户输入一个动物,它是声音(它的老麦克唐纳)。我完成了作业的第一部分,即在用户输入后打印出每个节,但第二部分要求将所有节(总共 3 节)连接到整首歌曲中。因此,最终的结果是将各个节组合在一起形成一首歌曲。问题是,鉴于我必须更新歌曲,然后在最后输出整首歌曲,如何使用累加器? 附件是我的代码:(注意这是python 2.7.5)
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
最佳答案
通过“累加器”,我假设您指的是连续添加到前一个字符串的模式。这可以通过运算符+=
来实现。
通过“连接”,我假设您指的是字符串运算符+
。
根据您自己的规则,您不允许使用 %
运算符。
你可以这样做:
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
等等
我相信这就是您的作业所要求的,但要意识到这会
不被视为“好的”或“Pythonic”代码。特别是字符串积累
效率低下——更喜欢列表推导式和 str.join()
。
关于python - 初学者Python : Accumulator loop function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928489/