Python 3项目没有给我我想要的结果

时间:2019-03-11 20:17:33

标签: python python-3.x

我正在通过Codecademy学习Python,并且在“ Sal的运输”项目中遇到了奇怪的结果。

我想让python做的是告诉我哪种运输方法最便宜。这是一个代码示例:

print(cost_ground_shipping(4.8))
print(cheapest_shipping(4.8))

这给了我:

34.4
Premium shipping is the cheapest at $125
问题是,溢价运费显然并不便宜,为125美元,而陆运价格为34.4美元。

对不起,代码很乱。在教程视频中,那个家伙使用了本课程中没有讲到的特定技术,这使我很烦,所以我忽略了它,因为我不想完全重写我的代码。

任何答案都很感激:)

这是完整的代码:

def cost_ground_shipping(weight):
  if weight <= 2:
    return weight * 1.5 + 20
  elif 6 >= weight:
    return weight * 3. + 20
  elif 10 >= weight:
    return weight * 4. + 20
  else:
    return weight * 4.75 + 20

cost_premium_shipping = 125

def cost_drone_shipping(weight):
  if weight <= 2:
    return weight * 4.5
  if 6 >= weight > 2:
    return weight * 9.
  if 10 >= weight > 6:
    return weight * 12.
  if weight > 10:
    return weight * 14.25 + 20

def cheapest_shipping(weight):
  if str(cost_ground_shipping(weight)) < str(cost_premium_shipping) and str(cost_ground_shipping(weight)) < str(cost_drone_shipping(weight)):
    return "Ground shipping is the cheapest at $" + str(cost_ground_shipping(weight))
  if str(cost_premium_shipping) < str(cost_ground_shipping(weight)) and str(cost_premium_shipping) < str(cost_drone_shipping(weight)):
    return "Premium shipping is the cheapest at $" + str(cost_premium_shipping)
  if str(cost_drone_shipping(weight)) < str(cost_ground_shipping(weight)) and str(cost_drone_shipping(weight)) < str(cost_premium_shipping):
    return "Drone shipping is the cheapest at $" + str(cost_drone_shipping(weight))

print(cost_ground_shipping(4.8))
print(cheapest_shipping(4.8))

1 个答案:

答案 0 :(得分:1)

Jonathan,欢迎来到Stack Overflow。 在Python中,与大多数编程语言类似,字符串也具有可比性和有序性(即不等式运算符具有含义)。

def cheapest_shipping(weight):
  if str(cost_ground_shipping(weight)) < str(cost_premium_shipping)..
  ..
  if str(cost_premium_shipping) < str(cost_ground_shipping(weight))

您在这里无意中执行了字符串比较,即您正在比较STRING“ 34.4”与“ 125”。计算机将字符串解释为字符序列,并顺序比较字符的ASCII码。由于“ 1”的ASCII码为49,“ 3”的ASCII码为51,因此“ 1”小于“ 3”,因此“ 125” <“ 34.4”。这就是为什么您得到“错误”答案的原因。

要比较数字时,请省略str转换函数。要打印数字时,请保留str函数。