简体   繁体   中英

Wrong output with 0 bricks pyramid building python

I'm making a small script that builds a pyramid out of the users input number, it then outputs the maximum height it can go to.

 for n in range(bricks):
     if (n*n)/2 <= bricks:
         height = n+1
     print("The height of the pyramid is:", height)

When I put "0" in it still puts height of "1", I get that's because of the +1 but without that there it will give a syntax error, and will also display the wrong height when putting just "1" brick in, any ideas on how to fix this.

Thanks

You may desindent the print, it may run at the end of the loop

bricks= 0
height = 0
for n in range(bricks):
    if (n*n)/2 <= bricks:
        height = n+1
print("The height of the pyramid is:", height)

If you extract a method, you'll have

def get_height(bricks):
    height = 0
    for n in range(bricks):
        if (n * n) / 2 <= bricks:
            height = n + 1
    return height

for b in range(10):
    print("The height of the pyramid is:", get_height(b), 'for nb_bricks=', b)
The height of the pyramid is: 0 for nb_bricks= 0
The height of the pyramid is: 1 for nb_bricks= 1
The height of the pyramid is: 2 for nb_bricks= 2
The height of the pyramid is: 3 for nb_bricks= 3
The height of the pyramid is: 3 for nb_bricks= 4
The height of the pyramid is: 4 for nb_bricks= 5
The height of the pyramid is: 4 for nb_bricks= 6
The height of the pyramid is: 4 for nb_bricks= 7
The height of the pyramid is: 5 for nb_bricks= 8
The height of the pyramid is: 5 for nb_bricks= 9

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM