如何让用户选择python打印多少行?

时间:2014-03-04 01:08:40

标签: python-3.x

我正在完成一项家庭作业,我需要这样做才能让用户选择打印的行数。这是我第一次发布在这里,所以如果我做错了,请告诉我。感谢

def verse():
    print ("Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!")


def sing(animal, sound):
    verse()
    print ("And on the farm he had a ", animal + ", Ee-igh, Ee-igh, Oh!")
    print ("With a", sound + ",", sound, "here and a" , sound + ",",sound + " there.")
    print ("Here a", sound + ", there a", sound + ", everyehere a",sound  + ",", sound + ".")
    verse()


def main():
    lines = input("Enter the amount of lines you would like to see:")
    #not sure what to put next
    sing("cow", "moo")
    print()
    sing("horse", "neigh")
    print()
    sing("pig", "oink")
    print()
    sing("goat","baa")
    print()
    sing("hen", "cluck")

main()

1 个答案:

答案 0 :(得分:0)

我会沿着这些方向做点什么:

def sing(lines):
    template='''
    Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!
    And on the farm he had a {animal}
    Ee-igh, Ee-igh, Oh!
    With a {sound}, {sound} here and a {sound}, {sound} there.
    Here a, {sound}, there a, {sound}, everywhere a, {sound}, {sound}.
    Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!'''

    verses=[("cow", "moo"),
            ("horse", "neigh"),
            ("pig", "oink"),
            ("goat","baa"),
            ("hen", "cluck")]
    li=[]        
    for n in range(0,5):        
        li.append(template.format(animal=verses[n][0], sound=verses[n][1]))   

    song=''.join(li)
    return '\n'.join(song.splitlines()[0:lines+1])         

def main():
    lines = input("Enter the amount of lines you would like to see: ")
    print(sing(int(lines)))

main()