Python中如何用列表替代冗长的if-elif条件判断?
用列表替代冗长if-elif简化单位转换器代码
我是Python编程新手(仅学习几天),目前在写一个简易单位转换器。代码里的get_unit1和get_unit2函数用了大量if-elif判断合法输入单位,功能正常但代码太啰嗦。我试过用or运算符简化条件,但写法错了导致非法输入被接收,程序崩溃;也试过用列表,但还是写出冗长的判断代码,想找正确的用列表替代冗长if-elif的方法。
原代码
def get_unit1(): while True: unit1 = input("Which unit would you like to convert from?: ") if unit1 == 'km': return unit1 elif unit1 == 'hm': return unit1 elif unit1 == 'da': return unit1 elif unit1 == 'm': return unit1 elif unit1 == 'dm': return unit1 elif unit1 == 'cm': return unit1 elif unit1 == 'mm': return unit1 elif unit1 == 'ml': return unit1 elif unit1 == 'yd': return unit1 elif unit1 == 'ft': return unit1 elif unit1 == 'in': return unit1 else: print("Wrong input, try again.") def get_unit2(): while True: unit2 = input("Which unit would you like to convert to?: ") if unit2 == 'km': return unit2 elif unit2 == 'hm': return unit2 elif unit2 == 'da': return unit2 elif unit2 == 'm': return unit2 elif unit2 == 'dm': return unit2 elif unit2 == 'cm': return unit2 elif unit2 == 'mm': return unit2 elif unit2 == 'ml': return unit2 elif unit2 == 'yd': return unit2 elif unit2 == 'ft': return unit2 elif unit2 == 'in': return unit2 else: print("Wrong input, try again.")
错误简化写法
if unit1 == 'km'or'hm'or'da'or'm'or'dm'or'cm'or'mm'or'ml'or'yd'or'ft'or'in': return unit1
正确解决方法
你的错误写法核心问题是逻辑判断逻辑错误:unit1 == 'km' or 'hm' 等价于 (unit1 == 'km') or ('hm'),而非空字符串在布尔判断中会被视为True,所以不管输入什么,这个条件永远成立,导致非法输入被放行。
1. 用列表+成员运算符简化判断
先定义合法单位的列表,再用in运算符判断输入是否在列表内,同时可以把两个重复的函数合并成一个通用函数,彻底消除冗余:
# 定义所有合法单位的列表 VALID_UNITS = ['km', 'hm', 'da', 'm', 'dm', 'cm', 'mm', 'ml', 'yd', 'ft', 'in'] def get_valid_unit(prompt): while True: unit = input(prompt) if unit in VALID_UNITS: return unit else: print("Wrong input, try again.") # 调用函数获取输入 unit1 = get_valid_unit("Which unit would you like to convert from?: ") unit2 = get_valid_unit("Which unit would you like to convert to?: ")
2. 可选优化:忽略输入大小写
如果想让程序兼容大小写输入(比如KM、Cm也能被识别),只需把输入转成小写后再判断:
def get_valid_unit(prompt): while True: unit = input(prompt).lower() # 统一转成小写 if unit in VALID_UNITS: return unit else: print("Wrong input, try again.")
内容的提问来源于stack exchange,提问作者Strider
相关产品推荐
相关产品推荐

