我似乎无法得到这个,我只是不了解如何在模块之间传递参数。这对我来说似乎很简单,但也许我只是没有得到它,我对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)TypeError:不可拆卸的类型:function()> INT()
有人能解释一下吗?
答案 0 :(得分:1)
有一件事是在python中不需要主要的。另一种方法,就是这样做。
你真的需要一个主?
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)
答案 1 :(得分:0)
我认为你的意思是:
CalcAndDisplayShipping(main())
这将调用main()
并将其返回值作为参数传递给CalcAndDisplayShipping()
。
答案 2 :(得分:0)
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__
,并且它不会执行主要部分。
因此,如果您希望在将此模块作为单个脚本运行时执行任何操作,则可以使用此功能。
这个条件'只有在将模块作为单个脚本运行时才满足。