python传递参数模块

2024-06-25 06:20:28 发布

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

我似乎不能得到这个,我只是不明白如何传递模块之间的参数。尽管这对我来说很简单,但也许我只是不明白,我对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)

运行此命令时,我得到:Enter Package weight:(num)TypeError:unorderable types:function()>;int()

有人能给我解释一下吗?你知道吗


Tags: 模块to参数maindefovershippingenter
3条回答

有一点是在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)
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__,也不会执行main部分。你知道吗

因此,如果您想在作为单个脚本运行此模块时执行任何操作,可以使用此功能。你知道吗

仅当您将模块作为单个脚本运行时,才满足此“if条件”。你知道吗

我想你的意思是:

CalcAndDisplayShipping(main())

这将调用main(),并将其返回值作为参数传递给CalcAndDisplayShipping()。你知道吗

相关问题 更多 >