You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 04:48:03