kayahankaya
kayahankaya

Reputation: 33

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:

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


Upvotes: 2

Views: 66

Answers (2)

Kaøsc
Kaøsc

Reputation: 117

Try this

def print_shape(n):

  for i in range(0,n):
    print('*' * (n-i), end='')
    print(' ' * (i*2), end='')
    if i == n-1:
      print('*' * (n-i), end='')
    else:
      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')
      
print_shape(5)

Upvotes: 1

vidstige
vidstige

Reputation: 13079

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)

Upvotes: 2

Related Questions