0

How to achieve the below output in python with the help of range and loops functionality available in python?

  Expected output:
  0000
  1111
  2222
  3333

The below way works, but if the number needs to be printed till 100 then, 100 print statements needs to be written, the below way is a time consuming process.

Rather than writing in the below way of writing the code and achieving the output in the above way. Is there any short way to write the code and achieve the desired output?

  for i in range(4):
    print(i,end='')
    print(i,end='')
    print(i,end='')
    print(i)
AMC
  • 2,642
  • 7
  • 13
  • 35
Karthik Velu
  • 49
  • 2
  • 7

2 Answers2

2

you can use:

n = 4
for i in range(n):
    print(str(i)*n)

output:

0000
1111
2222
3333

or you can use:

print(*[e*4 for e in map(str, range(n))], sep='\n')

or:

print(*[str(e) * 4 for e in range(n)], sep='\n')

output:

0000
1111
2222
3333

for 100 prints you have to set n = 100

kederrac
  • 16,819
  • 6
  • 32
  • 55
0

If you're not sure about how many iterations, this will be executed this should work as well:

  n = int(input("Enter the number of iterations:"))
  for num in range(n):
     print(str(num)*4)

Output for n = 4:

  0000
  1111
  2222
  3333
de_classified
  • 1,927
  • 1
  • 15
  • 19