Python实现停车场收费计算的代码无法正常运行,该如何修复?
车辆停车费计算程序问题修复
原代码存在的核心问题
- while循环逻辑错误:
while True为死循环,未设置break跳出逻辑,且while对应的else块仅在循环正常结束时触发,原代码永远无法执行到停车时间输入、费用计算的逻辑 - 缩进语法错误:
elif time_spent > 3块的缩进层级与上层if time_spent <=3不匹配,运行会直接报语法错误 - 命名不规范:使用Python内置关键字
type作为变量名,会覆盖内置函数功能 - 校验逻辑缺失:仅校验了车辆类型大于3的异常,未处理输入小于1的异常;未考虑跨天停车的场景,离开时间早于进入时间时会计算出负的停车时长
- 标志位
flag逻辑混乱:每次循环开始都会重置flag=0,即使用户选择n退出也没有终止程序的逻辑
修复后完整可运行代码
print (" ***** A PROGRAM TO CALCULATE PARKING CHARGES OF A VEHICLE ***** ") print ('*' * 100) print ("\tChoose the type of a vehicle you have by pressing the corresponding number.") # 替换内置关键字type为自定义变量名vehicle_type vehicle_type = int(input("\t1.cars \n\t2.Truck/bus. \n\t3.Scooter/Cycle/Motor cycle.\n>>> ")) while True: # 同时校验小于1和大于3的异常输入 if vehicle_type < 1 or vehicle_type > 3: print ("The type of vehicle selected is not supported") choice = input ("\nWould you wish to continue? (y/n) \n\t>>> ") if choice.lower() != 'y': # 直接终止程序 exit() else: vehicle_type = int(input("\t1.cars \n\t2.Truck/bus. \n\t3.Scooter/Cycle/Motor cycle.\n>>> ")) else: # 选择合法则跳出循环 break # 停车时间输入逻辑 in_hrs = int(input("Enter the time of entrance (HH) : ")) in_min = int(input("Enter the time of entrance (MM) : ")) out_hrs = int(input("Enter the time of Leaving (HH) : ")) out_min = int(input("Enter the time of leaving (MM) : ")) time_spent = (out_hrs + (out_min/60)) - (in_hrs + (in_min/60)) # 处理跨天停车场景 if time_spent < 0: time_spent += 24 # 费用计算逻辑,修正缩进,新增保留两位小数优化展示效果 if time_spent <= 3: if vehicle_type == 1: print(f"Your charges are : {round(time_spent * 10,2)} £.") elif vehicle_type == 2: print(f"Your charges are : {round(time_spent * 20,2)} £.") elif vehicle_type == 3: print(f"Your charges are : {round(time_spent * 5,2)} £.") elif time_spent > 3: if vehicle_type == 1: print (f"Your charges are : {round(time_spent * 20,2)} £.") elif vehicle_type == 2: print (f"Your charges are : {round(time_spent * 30,2)} £.") elif vehicle_type == 3: print (f"Your charges are : {round(time_spent * 10,2)} £.") print('*' * 100)
内容的提问来源于stack exchange,提问作者Jamal Makame
相关产品推荐
相关产品推荐

