Skip to main content
 首页 » 编程设计

Python嵌套if-else只执行else

2025年05月04日16softidea

我有这个练习,计算发送一个小包裹的费用。邮局对前 300 克收取 R5,此后每 100 克收取 R2(四舍五入),最大重量为 1000 克。

weight = raw_input("What are the weight of you parcel: ")     
 
if weight <= 1000: 
   if weight <= 300: 
      cost = 5 
     print("You parcel cost: " + cost) 
   else: 
      cost = 5 + 2 * round((weight - 300)/ 100) 
      print("You parcel cost: " + cost) 
else: 
    print("Maximum weight for amall parcel exceeded.") 
    print("Use large parcel service instead.") 

当我执行 IDLE 控制台时,我只会出现最后的 else 语句。

请您参考如下方法:

将 weight 转换为 int,weight = int(weight)。现在它是一个字符串,在与 1000 进行比较时始终计算为 False。