-1

I need a function that gives an output:

1111
    2222
        3333

This is what I got as a function:

def repeatNumber(someNumber):
    for i in range(0,someNumber):
        tabString = "\t"*i
        repeatingString = str(i+1)*4+"\n"
        finalString = tabString + repeatingString
        return finalString

But the output gives my only

1111

when I try to

print(repeatNumber(3))

at the end.

I know I have to add to a string, but I'm not quite sure what string(s) to add together...

aj2929
  • 19
  • 4

2 Answers2

0

You are returning at the first iteraion of the loop. You can keep the result in a temporary variable and return that instead. Like this:

def repeatNumber(someNumber):
    return_string = ''
    for i in range(0,someNumber):
        tabString = "\t"*i
        repeatingString = str(i+1)*4+"\n"
        finalString = tabString + repeatingString
        return_string += finalString
    return return_string
ham
  • 716
  • 5
  • 12
  • Thank you! I didn't realize to put the return_string = " " in the beginning of the function! – aj2929 Mar 14 '17 at 11:36
  • 1
    You'd be better off making a list that you join rather than using `+=` on strings http://stackoverflow.com/questions/3055477/how-slow-is-pythons-string-concatenation-vs-str-join – Chris_Rands Mar 14 '17 at 12:31
  • Never knew this! And it is faster by a margin. Makes sense to use `join`. Thanks – ham Mar 15 '17 at 06:11
0
In [9]: def repeatNumber(someNumber):
            for i in range(0,someNumber):
                tabString = "\t"*i
                repeatingString = str(i+1)*4+"\n"
                finalString = tabString + repeatingString
                print finalString

In [10]: repeatNumber(3)
1111

    2222

        3333
manvi77
  • 536
  • 1
  • 5
  • 15