Python-在新函数中引用已定义的函数

时间:2018-08-16 11:31:02

标签: python

我正在尝试自学Python,并在练习中定义了3个函数(RootGridc_ground_shippingprem_ground_shipping),每个函数返回一个整数以表示不同的运输费用一定重量包装的方法。

我现在正在尝试定义一个新函数,该函数将返回最便宜的运输方法。

我写了以下内容:

drone_shipping

我收到错误消息:

def cheap_shipping(weight):
  if c_ground_shipping < prem_ground_shipping and c_ground_shipping < drone_shipping:
    return "The cheapest shipping method for your package is Ground Shipping. This will cost you £" + str(c_ground_shipping) + " to ship."
  elif prem_ground_shipping < drone_shipping:
    return "The cheapest shipping method for your package is Premium Ground Shipping. This will cost you £" + str(prem_ground_shipping) + " to ship."
  else:
    return "The cheapest shipping method for your package is Drone Shipping. 
This will cost you £" + str(drone_shipping) + " to ship."

print (cheap_shipping(4.8))

我认为这是因为我指的是这个新功能中的预定义功能,但是尽管几次尝试都没有成功,但是我不确定如何更正此功能。如果有人可以建议我将不胜感激!

如果需要,请使用以下三个已定义函数之一的示例Traceback (most recent call last): File "script.py", line 43, in <module> print (cheap_shipping(4.8)) File "script.py", line 36, in cheap_shipping if c_ground_shipping < prem_ground_shipping and c_ground_shipping < drone_shipping: TypeError: unorderable types: function() < int()

c_ground_shipping

1 个答案:

答案 0 :(得分:0)

我认为问题是,您正在尝试比较函数,而不是函数返回的结果。例如

g_flat_charge = 20

def c_ground_shipping(weight):
  if weight > 10:
    return weight * 4.75 + g_flat_charge
  elif weight > 6:
    return weight * 4 + g_flat_charge
  elif weight > 2:
    return weight * 3 + g_flat_charge
  else:
    return weight * 1.5 + g_flat_charge

应为:

if c_ground_shipping < prem_ground_shipping and c_ground_shipping < drone_shipping: