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

Python如何将单位选择编号映射为对应缩写 避免冗余if判断

实现方案

用字典映射即可实现极简的单位匹配逻辑,无需编写多分支if判断,后续新增单位时只需更新字典键值对即可,维护成本极低。

修改后完整代码

import math

# 定义单位映射规则:输入选项对应单位缩写
unit_map = {
    "1": "cm",
    "2": "m",
    "3": "in"
}

r = float(input("What is the radius of your circle?"))
unit_input = str(input("Choose the unit of measurement\n1) centimeters\n2) meters\n3) inches"))
# 匹配单位,输入非法时默认返回unknown,可自定义默认值
unit = unit_map.get(unit_input, "unknown")
result = math.pi * r ** 2

# 用f-string简化输出,无需手动转换变量类型
print(f"The area of your circle with radius of {r} is:\n{result} {unit}")

可选优化:强制合法单位输入

如果需要避免用户输入非法选项,可以加入循环校验逻辑,直到用户输入正确的单位选项:

unit_map = {"1": "cm", "2": "m", "3": "in"}
while True:
    unit_input = str(input("Choose the unit of measurement\n1) centimeters\n2) meters\n3) inches"))
    if unit_input in unit_map:
        unit = unit_map[unit_input]
        break
    print("Invalid option, please enter 1/2/3")

内容的提问来源于stack exchange,提问作者Petr Míšek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:15:02