Python制作化学术语查询工具 修复查询时输出全部定义的问题
问题原因
- 未存储用户输入:
input("What would you like to know?\n")的返回值没有赋值给变量,用户输入的查询内容直接被丢弃,没有参与后续判断。 - 判断逻辑错误:Python中非空字符串的布尔值恒为
True,你写的if "VolumeUnits":这类判断等价于直接写if True:,所有分支都会触发,因此会打印全部定义。
优化后实现方案
推荐用字典存储术语和对应释义,后续增删术语只需要修改字典内容即可,不需要添加大量if判断,维护成本更低,完整代码如下:
# 用字典存储术语-释义映射,后续新增词条直接在这里添加即可 glossary = { "Imperial": "英制单位,包含gal、cup、汤匙、茶匙、夸脱、盎司、品脱等容积单位", # 你原代码缺失Imperial的定义,可根据需求修改释义 "VolumeUnits": "gal, cup, table spoons, teaspoons, quart, ounces, pints", "MetricSystem": "基于米作为基准,采用10的幂次进位的单位体系", "PreFixes": """kilo hecto deka base deci centi mili""", "Mass": "物体所含物质的量,基本单位是千克", "Weight": "重力对质量的作用力", "Volume": "长度×宽度×高度", "Random": "1升 = 1立方分米,1毫升 = 1立方厘米", "Time": "基本单位是秒", "Temperature": "常用单位摄氏度、开尔文", "SigFig": "可以置信测量的最后一位数值", "Chemistry": "研究物质及其性质、反应的学科", "Matter": "任何占有空间且具有质量的事物" } # 获取并存储用户输入 query = input("你想查询哪个术语的定义?\n") # 判断查询内容是否在词表中,存在则打印释义,不存在则提示 if query in glossary: print(glossary[query]) else: print("你查询的术语暂未收录")
如果你一定要沿用原有的变量+if判断的写法,修改方式如下:
# 保留你原来的变量定义 VolumeUnits = "gal, cup, table spoons, teaspoons, quart, ounces, pints" MetricSystem = "Based on the meter, really just a stick, Based on powers of 10" PreFixes = """kilo hecto deka base deci centi mili""" Mass = "the amount of matter in an object, base unit is kilograms" Weight = "the pull of gravity on a mass" Volume = "lenght x width x height" Random = "1L - dm^3. 1ml - cm^3" Time = "base is seconds" Temperature = "Celsius, kelvin" SigFig = "the last number that can be measured with confidence" Chemistry = "the study of matter and its properties and reactions" Matter = "anything that takes up space and has mass" Imperial = "英制单位的定义内容" # 你原代码缺失了Imperial变量的定义,需要先补全 # 存储用户输入 query = input("What would you like to know?\n") # 把判断改成匹配用户输入的内容,用elif避免无效判断 if query == "Imperial": print(Imperial) elif query == "VolumeUnits": print(VolumeUnits) elif query == "MetricSystem": print(MetricSystem) elif query == "PreFixes": print(PreFixes) elif query == "Mass": print(Mass) elif query == "Weight": print(Weight) elif query == "Volume": print(Volume) elif query == "Random": print(Random) elif query == "Time": print(Time) elif query == "Temperature": print(Temperature) elif query == "SigFig": print(SigFig) elif query == "Chemistry": print(Chemistry) elif query == "Matter": print(Matter) else: print("未查询到对应术语")
内容的提问来源于stack exchange,提问作者PetaByte
相关产品推荐
相关产品推荐

