How to get these strings by using return instead of print?

def createSteps(stepCount):
    if stepCount==1:
        for i in reversed(range(1,stepCount+1)):
            print(" "*(( i * 2) - 2), end = '')
            print('+-+')
            print(" " * ((i * 2) - 2), end = '')
            print('| |')
            print(" " * ((i * 2) - 2), end = '')
            print('+-+')
    elif stepCount != 0:
        print(" " * ((stepCount * 2) - 2), end = '')
        print('+-+')
   
        for i in reversed(range(1, stepCount + 1)):
            print(" " * ((i * 2) - 2), end = '')
            print('| |')
            print(" " * ((i * 2) - 4), end = '')
            if i == 1:
                print('+-+')
            else:
                print('+-+-+')

I tried to get the output by using return instead of using print,

for i in reversed(range(1,stepCount+1)):

    a = (" "*(( i * 2) - 2))
    b = ('+-+')
    c = (" " * ((i * 2) - 2))
    d = ('| |')
    e = (" " * ((i * 2) - 2))
    f = ('+-+')
    g = a + b + c + d + e + f
return str(g)

However, the error appears: SyntaxError: 'return' outside function

1 answer

  • answered 2021-04-08 03:28 Tim Roberts

    Your indentation is inconsistent. Your function must look like this. Note that g is already a string, you don't have to convert it. Also note that you will need to insert the newlines, since you are no longer using print to get that effect.

    def createSteps(stepCount):
        g = []
        for i in range(stepCount,1,-1):
            a = " "*(( i * 2) - 2)
            b = '+-+'
            c = " " * ((i * 2) - 2)
            d = '| |'
            e = " " * ((i * 2) - 2)
            f = '+-+'
            g.extend( [a + b, c + d, e + f] )
        return '\n'.join(g)