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

Can i avoid to print new line between 2 for loops in Python

I’m trying to display a diamond shape depending on the input. Code almost worked done except ’empty new line’.

But I didn’t eliminate the empty line between 2 loops. How can I fix it? Is there something that escaped my attention?

def print_shape(n):

    for i in range(0,n):
        print('*' * (n-i), end='')
        print(' ' * (i*2), end='')
        print('*' * (n-i), end='\n')
    for k in range((n), (2 * n + 1)):
        print('*' * (k - n), end='')
        print(' ' * ((4 * n) - (2 * k)), end='')
        print('*' * (k - n), end='\n')

n = int(input('Enter a number: '))
print_shape(n)

Enter a number: 5

**********
****  ****
***    ***
**      **
*        *
          
*        *
**      **
***    ***
****  ****
**********

Need to do this one:

**********
****  ****
***    ***
**      **
*        *
*        *
**      **
***    ***
****  ****
**********


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

>Solution :

Yes, that’s very easy. Just start from n+1 instead of n in the bottom loop (it’s the one printing the unwanted newline) like so

def print_shape(n):

    for i in range(0,n):
        print('*' * (n-i), end='')
        print(' ' * (i*2), end='')
        print('*' * (n-i), end='\n')
    for k in range(n + 1, (2 * n + 1)):  # <--- here
        print('*' * (k - n), end='')
        print(' ' * ((4 * n) - (2 * k)), end='')
        print('*' * (k - n), end='\n')

n = int(input('Enter a number: '))
print_shape(n)
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