Home > Net >  Hollow Inverted Half Pyramid
Hollow Inverted Half Pyramid

Time:07-24

I have to print a hollow inverted pyramid:

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

Following is my code:

n = int(input())

for i in range(n,0,-1):
    if i == n:
        print(n*'*', end = '')
    if  i > 1 and i <n:
        print('*' (i-2)*' ' '*')
    else:
        print('*')
    print()

For input as 6 I am not sure why my code is printing 7 stars. If anyone could help explain what I am doing wrong or missing would be really great!

CodePudding user response:

There are two problems here:

  1. There is no need for the , end=''. You still want a newline to print after this line of stars.
  2. You used if not elif for the second condition, so the third block of code in the else will still run even if the first condition is true.

Here is the corrected code:

n = int(input())

for i in range(n, 0, -1):
    if i == n:
        print(n * "*")
    elif 1 < i < n:
        print("*"   (i - 2) * ' '   '*')
    else:
        print('*')

CodePudding user response:

If the first iteration of the loop, there are two print calls executing: the first one and the last, so that makes a total of 7 stars in that first line of output.

As the first and last case are different from the other cases, it is easier to just deal with those outside of the loop:

n = int(input())

print(n*'*')
for i in range(n - 3, -1, -1):
    print('*'   i*' '   '*')
if n > 1:
    print('*')

There is still one if here to ensure it still works correctly for n equal to 1 or even 0.

To do it without that if, you could do this:

n = int(input())

print(n*'*')
s = '*'   n*' '
for i in range(n - 2, -1, -1):
    print(s[:i]   '*')
  • Related