Python代码打印内存地址而非函数返回数据的问题求助
问题根因
你的代码出现内存地址输出、运行异常是以下几个语法和逻辑错误共同导致的:
- 输出内存地址的直接原因:打印语句中直接写了
clean_cost、total_clean_cost这两个函数名,没有加()执行函数拿到返回值。Python中直接引用函数名得到的是函数对象本身,打印时就会输出对象的内存地址,而非计算结果。 - 语法缩进错误:所有自定义函数定义前都多了一层无意义的前置缩进,Python以缩进划分代码块,顶级作用域的函数定义不能有额外缩进。
- 区间判断逻辑错误:
cleansize_selectionprog函数中判断房间数量对应折扣时,错误使用了or连接条件。比如room_qty >= 1 or room_qty <=7对所有大于等于1的输入都成立,会导致不管输入多少房间,都会命中1.0的无折扣档位,完全失去阶梯定价的作用。 - 其他语法/逻辑错误:房间数量是正整数,用
float类型接收不合理;代码末尾调用了根本不存在的main()函数,运行时会直接抛出名称错误;输入小于1的非法房间数时,递归调用判断函数后没有返回值,会得到空值导致计算失败。
修复后可运行代码
# 接收用户输入,房间数量转为整数类型,清洁类型输入统一转小写、去空格做容错 room_qty = int(input("Please enter the total number of rooms :")) cleantype = input('Please choose cleaning intensity (light or heavy) :').strip().lower() def cleantype_choiceprog(cleantype): if cleantype == "light" or cleantype == "l": return 10 elif cleantype == "heavy" or cleantype == "h": return 20 # 非法清洁类型输入默认取轻清洁档位 print("Invalid cleaning type input, default to light cleaning") return 10 def cleansize_selectionprog(room_qty): if room_qty < 1: print('Please enter a value greater than 0') return None # 用链式区间判断修正原or逻辑错误 if 1 <= room_qty <= 7: return 1.0 elif 8 <= room_qty <= 15: return 0.8 elif 16 <= room_qty <= 25: return 0.6 else: return 0.4 def clean_cost(): room_rate = cleansize_selectionprog(room_qty) if not room_rate: return 0 return cleantype_choiceprog(cleantype) * room_rate def total_clean_cost(): return clean_cost() * room_qty # 调用函数拿到计算结果后再打印 per_room_cost = clean_cost() total_cost = total_clean_cost() print(f'It will cost {per_room_cost:.2f} per room cleaned.') print(f'The total cost of cleaning this space is: {total_cost:.2f}')
关键修改说明
- 所有函数定义取消多余前置缩进,符合Python语法规范
- 打印成本时通过
()调用函数拿到计算返回值,从根源解决输出内存地址的问题 - 替换原错误的
or条件判断为正确的区间范围判断,阶梯折扣逻辑可以正常生效 - 移除不存在的
main()调用,调整房间数量输入类型为整数,避免运行时报错 - 增加简单输入容错:自动处理用户输入的大小写、前后空格问题,非法输入时给出提示而非直接崩溃
- 格式化输出保留两位小数,符合金额显示的常规习惯
内容的提问来源于stack exchange,提问作者TallSniper
相关产品推荐
相关产品推荐

