Python代码报错'return outside function'问题排查与修复求助
Python道路通行费计算程序错误修复
核心错误分析
缩进错误触发'return outside function'
toll_times()函数中的while循环和return tolls语句未缩进,完全脱离函数体。Python会将return识别为全局作用域语句,直接抛出错误,必须将这部分代码缩进纳入函数定义范围内。变量未定义与逻辑漏洞
tolls.append(toll)中的toll从未定义,需先调用calculate_toll(time_str)计算当前时间的通行费,再将结果加入列表;main()函数中,tolls = toll_times是引用函数对象而非调用函数,需改为tolls = toll_times();main()里的times变量未声明,需调整逻辑:让toll_times()收集用户输入的所有有效时间,再在main()中遍历计算通行费;- 最终打印逻辑错误,需对应每个时间输出通行费,或直接打印完整的通行费列表。
- 格式规范问题
convert_to_24h函数内部分行有多余空格,不符合Python代码规范,已修正。
修正后的完整代码
# 道路通行费计算程序 def calculate_toll(time): # 将12小时制转换为分钟数(从午夜开始计算) time_24h = convert_to_24h(time) if time_24h < 7 * 60 + 30: # 12:00am-7:29am return 1.05 elif time_24h < 19 * 60 + 30: # 7:30am-7:29pm return 2.15 else: # 7:30pm-11:59pm return 1.10 def convert_to_24h(time): # 拆分时间与上午/下午标识 hour_str, minute_str = time[:-2].split(':') is_pm = time[-2:].lower() == 'pm' # 转换小时为整数 hour = int(hour_str) if is_pm and hour != 12: hour += 12 elif not is_pm and hour == 12: hour = 0 # 返回从午夜开始的总分钟数 return hour * 60 + int(minute_str) # 收集用户输入的时间,直到输入"Done" def get_user_times(): times = [] while True: time_str = input("输入12小时制时间(如7:02am),或输入'Done'结束:") if time_str.lower() == "done": break times.append(time_str) return times def main(): # 获取用户输入的所有时间 input_times = get_user_times() # 计算每个时间对应的通行费 toll_list = [calculate_toll(time) for time in input_times] # 打印结果 print("所有通行费列表:", toll_list) # 可选:逐个打印时间与对应通行费 for time, toll in zip(input_times, toll_list): print(f"时间 {time} 的通行费为 ${toll:.2f}") if __name__ == '__main__': main()
说明
- 重命名
toll_times()为get_user_times(),函数职责更清晰:仅收集用户输入的时间; - 修正所有缩进问题,确保函数内代码块正确嵌套;
- 补充清晰的打印逻辑,支持批量列表打印和逐个时间的详细输出;
- 保留原需求的所有功能:多次输入时间、按时段计算费率、结果存入列表。
内容的提问来源于stack exchange,提问作者mya wood
相关产品推荐
相关产品推荐

