We were asked to print the following output:
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 7 7 7 7 8 8 8 9 9 10
I understand that it would require two loops so I tired this:
a = int(input()) i = a f = 1 while i>0: for j in range(i): print(f,end=' ') f += 1 i -= 1 print('r')
With this I am getting the desired output, but as soon as I remove the last line of print(‘r’) the output becomes something like this:
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 7 7 7 7 8 8 8 9 9 10
The desired output also comes out when I used print(‘ ‘) instead of print(‘r’), I don’t understand why this is happening?
Ps: I am a noob coder, starting my freshman year, so please go easy on me, if the formatting is not up to the mark, or the code looks bulky.
Advertisement
Answer
Probably not helping you so much but the following code produces the expected output:
a = 10 for i, j in enumerate(range(a, 0, -1), 1): print(*[i] * j) # Output: 1 1 1 1 1 1 1 1 1 1 # i=1, j=10 2 2 2 2 2 2 2 2 2 # i=2, j=9 3 3 3 3 3 3 3 3 # i=3, j=8 4 4 4 4 4 4 4 # i=4, j=7 5 5 5 5 5 5 # i=5, j=6 6 6 6 6 6 # i=6, j=5 7 7 7 7 # i=7, j=4 8 8 8 # i=8, j=3 9 9 # i=9, j=2 10 # i=10, j=1
The two important parameters here are sep
(when you print a list) and end
as argument of print
. Let’s try to use it:
a = 10 for i, j in enumerate(range(a, 0, -1), 1): print(*[i] * j, sep='-', end='nn') # Output: 1-1-1-1-1-1-1-1-1-1 2-2-2-2-2-2-2-2-2 3-3-3-3-3-3-3-3 4-4-4-4-4-4-4 5-5-5-5-5-5 6-6-6-6-6 7-7-7-7 8-8-8 9-9 10
Update
Step by step:
# i=3; j=8 >>> print([i]) [3] >>> print([i] * j) [3, 3, 3, 3, 3, 3, 3, 3] # print takes an arbitrary number of positional arguments. # So '*' unpack the list as positional arguments (like *args, **kwargs) # Each one will be printed and separated by sep keyword (default is ' ') >>> print(*[i] * j)