我希望代码在大于 23 或小于 0 时不接受输入。它确实拒绝负值但仍然大于 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))我用谷歌搜索了一些东西,并试图通过反复试验来理解,但我做不到。 for i in range(height): print(" "*(height-i)+"#"*(i+1))
3 回答

婷婷同学_
TA贡献1844条经验 获得超8个赞
当前代码检查是否height
同时小于0 和大于 23。相反,尝试:
while height < 0 or height > 23: height = int(input("input height: "))#using input as well, to get new working value
至于最后几行是如何工作的:它们创建了一个高度和宽度相等的“#”的 ASCII 金字塔。
第一行
for i in range(height)
只是有多少行。第二行
打印空格 -
" "*(height-i)
:例如,如果它是 6 高度金字塔的第一行,将打印 5 个空格;如果是第 2 行,将打印 4 个空格。乘法只是打印该字符x次。打印“#”s -
"#"*(i+1)
。这就像上面一样工作,但在空格之后,并且是相反的。

梦里花落0921
TA贡献1772条经验 获得超6个赞
while height<0 and height>23: print("please give input between 1 and 22")
您应该使用 if 而不是 while
for i in range(height): print(" "*(height-i)+"#"*(i+1))
第一行描述了循环将执行多少次第二行将在每行中打印多少次字符串。

开心每一天1111
TA贡献1836条经验 获得超13个赞
尝试这个
while height <= 0 or height >= 23: print("please give input between 1 and 22") height = int(input("select height: "))
当值为真时有效,并且数字同时小于 0 和大于 23 不能是,使用 'or' 而不是 'and'
添加回答
举报
0/150
提交
取消