Reputation: 27
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
Upvotes: 1
Views: 64
Reputation: 54168
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
Upvotes: 1