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

Python运费计算程序语法错误排查求助(Codecademy新手)

Python运费计算程序语法错误排查

我是Python新手,正在Codecademy平台学习,编写了一款计算运费的程序,但出现语法错误,目前卡在该错误无法推进,希望修改weight值时程序能正常运行。

原程序代码:

weight = 8

#Ground Shipping
if weight <= 2:
  print("""Price per Pound: $1.50
Flat Charge:     $20.00""")
cost_ground = weight * 1.5 +20

elif weight > 2 and <= 6:
  print("""Price per Pound: $3.00
Flat Charge:     $20.00""")
cost_ground = weight * 3 +20

elif weight > 6 and <= 10:
  print("""Price per Pound: $4.00
Flat Charge:     $20.00""")
cost_ground = weight * 4 +20

else weight > 10:
  print("""Price per Pound: $4.75
Flat Charge:     $20.00""")
cost_ground = weight * 4.75 +20

报错信息:

File "shipping.py", line 8
    elif weight > 2 and <= 6:
       ^
SyntaxError: invalid syntax

问题分析与修正方案:

  • elif条件语法错误:
    Python不允许在逻辑判断中省略重复变量,weight > 2 and <= 6 写法不合法。可改为两种形式:

    • 完整写法:weight > 2 and weight <= 6
    • 简洁链式比较:2 < weight <= 6(Python支持连续比较)
  • else语句语法错误:
    else用于处理所有前置条件不满足的情况,后面不能跟任何条件。需将else weight > 10: 修改为else:,因为前置条件已覆盖weight <=2、2<weight<=6、6<weight<=10,剩余情况自然是weight>10。

  • 缩进逻辑错误:
    原代码中cost_ground赋值未缩进,会导致无论触发哪个条件,最终都会执行最后一条赋值语句,不符合逻辑。需将每个cost_ground赋值缩进,放入对应条件的代码块内(与print语句同级缩进)。

修正后的完整代码:

weight = 8

# Ground Shipping
if weight <= 2:
    print("""Price per Pound: $1.50
Flat Charge:     $20.00""")
    cost_ground = weight * 1.5 + 20
elif 2 < weight <= 6:
    print("""Price per Pound: $3.00
Flat Charge:     $20.00""")
    cost_ground = weight * 3 + 20
elif 6 < weight <= 10:
    print("""Price per Pound: $4.00
Flat Charge:     $20.00""")
    cost_ground = weight * 4 + 20
else:
    print("""Price per Pound: $4.75
Flat Charge:     $20.00""")
    cost_ground = weight * 4.75 + 20

# 打印最终运费,方便验证结果
print(f"Total Ground Shipping Cost: ${cost_ground:.2f}")

修改weight值后,程序即可根据不同重量正常计算对应运费。

内容的提问来源于stack exchange,提问作者trickyhat9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:45:20