模式程序使用循环问题

时间:2016-10-08 11:27:11

标签: python python-2.7 design-patterns

我正在编写一个程序,它接受两个输入,行数和欢呼数作为输入。行数是用户想要打印出来的行数,欢呼数量的格式为1#che;是" GO"和两个欢呼是两个" GO" s ...他们就是" BUDDY"在两个相邻的GO中。并且每个新行必须缩进3个空格,而不是之前的空格。这是我提出的计划:

lines = input("Lines= ")
cheers = input("Cheers= ")
if cheers == 1:
    i = 1
    space = 0
    S = ""
    while i<=lines:
        S=S+(" "*space)+"GO \n"
        i += 1
        space+=3
    print S
else:
    n = 1
    cheer1 = "GO BUDDY "
    cheer2 = "GO"
    space = 0
    while n<= cheers:
        print (" "*space)+(cheer1*cheers)+cheer2
        space+=3
        n += 1

但问题在于,它并没有在欢呼声中打印出正确数量的GO。如何修改代码以解决此问题?这是我想要的输出格式:

This is the format of the ouput I want to get

3 个答案:

答案 0 :(得分:1)

def greet(lines, cheers):
    i = 0
    line_str = ""
    while i < cheers: # Build the line string
        i += 1
        line_str += "GO" if i == cheers else "GO BUDDY "

    i = 0 
    while i < lines: #Print each line
        print(" "*(i*3) + line_str)
        i += 1

greet(2,1)
greet(4,3)
greet(2,4)

答案 1 :(得分:1)

通常在Python中你不需要任何循环

UIBarButtonItem

答案 2 :(得分:1)

试试这个。

def greet(lines, cheers):
    for i in range (lines):
        output = (" ") * i + "Go"

        for j in range (cheers):
            if cheers == 1:
                print output
                break
            output += "Budddy Go"
        print output

希望这有帮助。