-1

I'm in the process of self-teaching Python, and would love to know if there's an equivalent to end="" used with print() for a return function. For instance:

def shape(num,x):
    for col in reversed(range(num)):
            for row in range(col+1):
                print(x,end="")
            print()

Gives me the result I want, but how would I use a return function to provide me with the same results?

3 Answers3

4

Are you asking how to return a string? Here is one way, following the same form you used:

def shape(num,x):
    result = ''
    for col in reversed(range(num)):
            for row in range(col+1):
                result += x 
            result += '\n'
    return result

print (shape(4, '*'), end="")

Using += on strings is bad form, however. As you continue to improve your code, check out list comprehensions and the str.join() function.

You might end up with something like this:

    return '\n'.join('*'*(col+1) for col in reversed(range(num)))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

Print the return value:

def shape(num):
    x = 0
    for col in reversed(range(num)):
        for row in range(col+1):
           x += row 
   return x
print(shape(82))
raam86
  • 6,785
  • 2
  • 31
  • 46
0

Another way you could do this is using a generator function:

def shape(num, x):
    for col in reversed(range(num)):
        yield x * (col + 1)

for line in shape(4, '*'):
    print(line)

Note: the generator function does basically the same thing as the generator expresion Robᵩ has shown(inside the '\n'.join()), but it's worth knowing how to create a generator function for more complicated cases.

stranac
  • 26,638
  • 5
  • 25
  • 30