Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to print a range of results with a space between every 3 results

How can I print a range of results with a space between every three results? 

When I print something like the following:

for i in range(1,10):
    print(i)

Output I get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
2
3
4
5
6
7
8
9
10

Expected output:

1
2
3

4
5
6

7
8
9

10

>Solution :

for i in range(1, 10): # Note: 10 is excluded
    print(i)
    if i % 3 == 0:
        print('')

Should do it!

Basically, it just checks that i is modulo 3. If it is, it will just print an empty line.

Example with a more complex loop

In the case that you have a loop that goes from a to b and that you want to print an empty line every c print, you can do:

for i in range(a, b):
    print(i)
    if (i - a + 1) % c == 0:
        print("")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading