Python程序误存字符串致max()浮点数转换报错,求解决方案
问题分析与修复
你的代码里有两个关键错误,导致无效字符串被加入列表,最终触发了float()转换失败的错误:
错误1:未利用类型检查函数的返回值
你调用了check_for_float(ipt),但完全没用到它的返回结果。这个函数已经帮你完成了输入转数字的尝试和错误提示,但你没有根据它的返回值决定是否将输入加入列表。
错误2:类型判断逻辑完全失效
这段代码的判断逻辑完全错误:
if ipt == type(float) or type(int): list.append(ipt) elif ipt == type(str): continue
input()函数返回的永远是字符串类型,不管你输入数字还是字母,ipt的类型都是stript == type(float)是在判断字符串是否等于float类,这永远是Falseor type(int)这里因为type(int)是一个类型对象,布尔值为True,所以整个if条件永远成立,不管输入什么都会执行list.append(ipt),包括'a'这种无效字符串
修复后的代码
def check_for_float(p_input): try: return float(p_input) except (ValueError, TypeError): print("Error, not a numeric input") return None # 用None明确标记无效输入 num_list = [] # 不要用list当变量名,会覆盖Python内置的list类型 while True: ipt = input("Please enter a numeric value: ") if ipt == "done": break converted_num = check_for_float(ipt) # 只有转换成功的数字才加入列表 if converted_num is not None: num_list.append(converted_num) # 空列表判断更简洁的写法 if not num_list: quit() # 列表里存的是float类型,直接调用max/min即可 mx = max(num_list) mn = min(num_list) print(f"Maximum = {mx}; Minimum = {mn}")
关键修改说明
- 变量名优化:把
list改成num_list,避免覆盖Python内置的list类型,防止后续出现奇怪的问题 - 利用类型检查结果:捕获
check_for_float的返回值,只有当转换成功(返回数字而非None)时,才将值加入列表 - 简化最值计算:现在列表里存储的是float类型的数字,不需要再用
key=float参数,直接调用max()和min()即可 - 代码风格优化:用
if not num_list代替if list == [],更符合Python的简洁写法
内容的提问来源于stack exchange,提问作者Julian Schmidt
相关产品推荐
相关产品推荐

