You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编程:如何获取用户输入选择金字塔的对应形状

代码问题修正

  • 首先修复合法形状集合的定义错误:原代码把三个形状写在同一个字符串里,导致匹配逻辑完全失效,需要拆分为集合的三个独立元素
  • 补充高度参数的输入校验逻辑,确保获取到的是合法正整数
  • 把输入逻辑封装为函数,避免return语句在全局作用域报错
def get_user_input():
    # 校验形状输入
    allowed_shapes = {"pyramid", "square", "triangle"}
    while True:
        try:
            shape = input("shape?: ").strip()
            if shape in allowed_shapes:
                break
        except EOFError:
            return None, None
    
    # 校验高度输入
    while True:
        try:
            height = int(input("height?: ").strip())
            if height > 0:
                break
            print("高度必须是大于0的正整数")
        except ValueError:
            print("请输入合法的整数高度")
        except EOFError:
            return None, None
    
    return shape, height

# 调用样例
shape, height = get_user_input()
if shape and height:
    print(f"获取参数成功:形状{shape},高度{height}")

内容的提问来源于stack exchange,提问作者Lesego Makweya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:42:03