我希望代碼在大于 23 或小于 0 時不接受輸入。它確實拒絕負(fù)值但仍然大于 23 的值。height=int(input("select height: "))while height<0 and height>23: print("please give input between 1 and 22")for i in range(height): print(" "*(height-i)+"#"*(i+1))我用谷歌搜索了一些東西,并試圖通過反復(fù)試驗來理解,但我做不到。 for i in range(height): print(" "*(height-i)+"#"*(i+1))
3 回答

婷婷同學(xué)_
TA貢獻1844條經(jīng)驗 獲得超8個贊
當(dāng)前代碼檢查是否height
同時小于0 和大于 23。相反,嘗試:
while height < 0 or height > 23: height = int(input("input height: "))#using input as well, to get new working value
至于最后幾行是如何工作的:它們創(chuàng)建了一個高度和寬度相等的“#”的 ASCII 金字塔。
第一行
for i in range(height)
只是有多少行。第二行
打印空格 -
" "*(height-i)
:例如,如果它是 6 高度金字塔的第一行,將打印 5 個空格;如果是第 2 行,將打印 4 個空格。乘法只是打印該字符x次。打印“#”s -
"#"*(i+1)
。這就像上面一樣工作,但在空格之后,并且是相反的。

夢里花落0921
TA貢獻1772條經(jīng)驗 獲得超6個贊
while height<0 and height>23: print("please give input between 1 and 22")
您應(yīng)該使用 if 而不是 while
for i in range(height): print(" "*(height-i)+"#"*(i+1))
第一行描述了循環(huán)將執(zhí)行多少次第二行將在每行中打印多少次字符串。

開心每一天1111
TA貢獻1836條經(jīng)驗 獲得超13個贊
嘗試這個
while height <= 0 or height >= 23: print("please give input between 1 and 22") height = int(input("select height: "))
當(dāng)值為真時有效,并且數(shù)字同時小于 0 和大于 23 不能是,使用 'or' 而不是 'and'
添加回答
舉報
0/150
提交
取消