python3项目没有给我我想要的结果

2024-05-29 05:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过Codecademy学习Python,在“Sal's shipping”项目中遇到了一个奇怪的结果

我想让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))

Tags: the代码returnifisatshippingprint
1条回答
网友
1楼 · 发布于 2024-05-29 05:38:26

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))

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

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

相关问题 更多 >

    热门问题