我似乎无法理解这一点,我只是不了解如何在模块之间传递参数。当然,这对我来说似乎很简单,但也许我只是不明白,我对python很陌生,但确实有编程经验。
def main():
weight = input("Enter package weight: ")
return weight
def CalcAndDisplayShipping(weight):
UNDER_SIX = 1.1
TWO_TO_SIX = 2.2
SIX_TO_TEN = 3.7
OVER_TEN = 3.8
shipping = 0.0
if weight > 10:
shipping = weight * OVER_TEN
elif weight > 6:
shipping = weight * SIX_TO_TEN
elif weight > 2:
shipping = weight * TWO_TO_SIX
else:
shipping = weight * UNDER_SIX
print ("Shipping Charge: $", shipping)
main(CalcAndDisplayShipping)
当我运行这个时,我得到:输入包重量:(num)类型错误:无序类型:function()>int()
有人能向我解释一下吗?
有一点是在python中不需要main。另一种方法是这样做。
你真的需要主菜吗?
import os
def CalcAndDisplayShipping(weight):
UNDER_SIX = 1.1
TWO_TO_SIX = 2.2
SIX_TO_TEN = 3.7
OVER_TEN = 3.8
shipping = 0.0
if weight > 10:
shipping = weight * OVER_TEN
elif weight > 6:
shipping = weight * SIX_TO_TEN
elif weight > 2:
shipping = weight * TWO_TO_SIX
else:
shipping = weight * UNDER_SIX
print ("Shipping Charge: $", shipping)
weight = float(input("Enter package weight: "))
CalcAndDisplayShipping(weight)
我认为你的意思是:
CalcAndDisplayShipping(main())
这将调用main()
并将其返回值作为参数传递给CalcAndDisplayShipping()
。
def CalcAndDisplayShipping(weight):
UNDER_SIX = 1.1
TWO_TO_SIX = 2.2
SIX_TO_TEN = 3.7
OVER_TEN = 3.8
shipping = 0.0
if weight > 10:
shipping = weight * OVER_TEN
elif weight > 6:
shipping = weight * SIX_TO_TEN
elif weight > 2:
shipping = weight * TWO_TO_SIX
else:
shipping = weight * UNDER_SIX
print ("Shipping Charge: $", shipping)
if __name__ == '__main__':
weight = float(input("Enter package weight: "))
CalcAndDisplayShipping(weight)
如果您使用python解释器运行此脚本,如python script_name.py
、__name__
变量值将为'__main__'
。
如果您要将此模块导入其他一些模块,则__name__
将不是__main__
,也不会执行主部分。
因此,如果您想在将此模块作为单独的脚本运行时执行任何操作,则可以使用此功能。
只有当您将模块作为单独的脚本运行时,这个"if条件"才满足。