[英]Wrong output with 0 bricks pyramid building python
我正在制作一個小腳本,根據用戶輸入的數字構建一個金字塔,然后輸出它可以達到的最大高度。
for n in range(bricks):
if (n*n)/2 <= bricks:
height = n+1
print("The height of the pyramid is:", height)
當我在里面放“0”時,它仍然把高度設為“1”,我知道這是因為+1,但如果沒有它,它會出現語法錯誤,並且在只放入“1”磚時也會顯示錯誤的高度, 有想法該怎么解決這個嗎。
謝謝
您可以設計打印,它可以在循環結束時運行
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)
如果您提取一個方法,您將擁有
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.