user14407659
user14407659

Reputation:

How to print an inverted pyramid?

These are what I'm currently working with:

row = int(input('Enter number of rows required: '))

for i in range(row,0,-1):
    for j in range(row-i):
        print('*', end='') 
    
    for j in range(2*i-1):
        print('0',end='')
    print()

And this is the current output:

0000000
*00000
**000
***0

I can't figure out what to change to have the correct output

Upvotes: 1

Views: 152

Answers (2)

Epsi95
Epsi95

Reputation: 9047

you can use f-string and siple nth number from the formula a + (n-1)*d

row = int(input('Enter number of rows required: '))

for i in range(row):
    print(f'{"*"*(i+1)}{"0"*(2*(row-i-1) - 1)}{"*"*(i+1)}')

Upvotes: 0

AKX
AKX

Reputation: 168913

Add another asterisk-printing loop before printing a newline.

row = 4
for i in range(row, 0, -1):
    for j in range(row - i):
        print('*', end='')

    for j in range(2 * i - 1):
        print('0', end='')

    for j in range(row - i):
        print('*', end='')

    print()

prints out

0000000
*00000*
**000**
***0***

(For a more Pythonic solution, you could just

row = 4
full_width = 2 * row - 1
for i in range(row, 0, -1):
    row_zeroes = (2 * i - 1)
    print(("0" * row_zeroes).center(full_width, '*'))

but I suspect that's not the point of this exercise.)

Upvotes: 2

Related Questions