仅接受范围内的输入

我希望代码在大于 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))


眼眸繁星
浏览 129回答 3
3回答

婷婷同学_

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

梦里花落0921

while&nbsp;height<0&nbsp;and&nbsp;height>23: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print("please&nbsp;give&nbsp;input&nbsp;between&nbsp;1&nbsp;and&nbsp;22")您应该使用 if 而不是 whilefor&nbsp;i&nbsp;in&nbsp;range(height): &nbsp;&nbsp;&nbsp;&nbsp;print("&nbsp;"*(height-i)+"#"*(i+1))第一行描述了循环将执行多少次第二行将在每行中打印多少次字符串。

开心每一天1111

尝试这个while&nbsp;height&nbsp;<=&nbsp;0&nbsp;or&nbsp;height&nbsp;>=&nbsp;23: &nbsp;&nbsp;&nbsp;&nbsp;print("please&nbsp;give&nbsp;input&nbsp;between&nbsp;1&nbsp;and&nbsp;22") &nbsp;&nbsp;&nbsp;&nbsp;height&nbsp;=&nbsp;int(input("select&nbsp;height:&nbsp;"))当值为真时有效,并且数字同时小于 0 和大于 23 不能是,使用 'or' 而不是 'and'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python