为了账号安全,请及时绑定邮箱和手机立即绑定

仅接受范围内的输入

仅接受范围内的输入

眼眸繁星 2022-06-14 16:14:30
我希望代码在大于 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)。这就像上面一样工作,但在空格之后,并且是相反的。


查看完整回答
反对 回复 2022-06-14
?
梦里花落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))

第一行描述了循环将执行多少次第二行将在每行中打印多少次字符串。


查看完整回答
反对 回复 2022-06-14
?
开心每一天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'


查看完整回答
反对 回复 2022-06-14
  • 3 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号