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:
**********
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
**********
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.