0

I am trying to create the following:

88888888
7777777
666666

.. and so on

Below is the code that I have written:

i = 8
for a in range(i):
    for b in range(i):
        print (str(i))
    i = i - 1

with this code, I am getting the numbers on a new line. I want all the 8s on one line, all the 7s on one line, etc.

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • I'd suggest taking a look at the documentation for the `print` function, and in particular the `end` parameter to that function. – Mark Dickinson Jan 13 '16 at 17:04
  • 1
    You could just build a string in the loop and then print it at the end. If you're interested, this is a one liner that will do what you're looking for `'\n'.join(str(i)*i for i in range(1,9))[::-1]` – Morgan Thrapp Jan 13 '16 at 17:05
  • Possible duplicate of [Print in one line dynamically](http://stackoverflow.com/questions/3249524/print-in-one-line-dynamically) – Łukasz Rogalski Jan 13 '16 at 17:10
  • @Rogalski That's not what OP wanted for output, they want it joined with new lines. – Morgan Thrapp Jan 13 '16 at 17:10

2 Answers2

4

One particularly short wait you can get the desired result is

for i in range(8, 0, -1):
    print(str(i) * i)

range(8, 0, -1) gives you the sequence of numbers equivalent to [8, 7, 6, 5, 4, 3, 2, 1]. You convert the number into a string, and multiplying a string by an integer i repeats it it i times. So for example, the number 8 gets converted to a string '8' and '8' * 8 = '88888888'. print() ends with a newline by default, giving us the result:

88888888
7777777
666666
55555
4444
333
22
1
beigel
  • 1,190
  • 8
  • 14
2

Sorry to bother with my silly question. However with few hit and trials i found the answer. Please ignore my question.

i= 8
for a in range(i):
    for b in range(i):
            print (i, end=' ')
    print(" ")
    i = i - 1
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • 2
    Good job! It's nice to see someone answer their own question. Keep at it! – temporary_user_name Jan 13 '16 at 17:18
  • The last `print()` can be without arguments, the last `i = i - 1` can be thrown away. The print in the loop should print `a`, and the first range should loop backward. Or you can use the while-loop with the last `i = i -1`. – pepr Jan 13 '16 at 18:06