python中的变量定义

2024-09-26 17:50:31 发布

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

我已经通过C++,现在正在学习Python。我对这里的变量有点困惑。我觉得应该声明“wt”为Real或Float,但它不接受这种语法。我想错误就在我声明模块“calcAndDisplayShipping”的那一行。你知道吗

该程序的目标是根据输入权重计算价格。你知道吗

#main module
def main():

    #local variables
    weight = 0.0

    #get package weight
    weight = input("Enter the weight of your package: ")

    #call module to calculate and display shipping charges
    calcAndDisplayShipping (weight)

#module for calculating and displaying shipping charge
def calcAndDisplayShipping (wt):

    #named constants for rates
    underTwo = 1.10
    twoToSix = 2.20,
    sixToTen = 3.70
    overTen= 3.80

    #Local Variable
    shipping = 0.0

    #calculate charges
    if wt > 10.0:
        shipping = wt * overTen
    elif wt > 6.0:
        shipping = wt * sixToTen
    elif wt > 2.0:
        shipping = wt * twoToSix
    else:
        shipping = wt * underTwo

    #display shipping charge
    print ("Shipping charge for this package is: $", shipping)

    #return to main
    main()

我得到的错误是。。。 TypeError:“str”和“float”的实例之间不支持“>;”

我在我的语言同伴中搜索python,却找不到任何帮助。你知道吗


Tags: andto声明packageformaindef错误
3条回答

由于python3.x不计算和转换数据类型,因此必须显式地转换为float,使用float,如float(input("question:"))

试试这个:

def main():
    weight = 0.0
    weight = float(input("Enter the weight of your package: "))
    #call module to calculate and display shipping charges
    calcAndDisplayShipping (weight)

#module for calculating and displaying shipping charge
def calcAndDisplayShipping (wt):

    #named constants for rates
    underTwo = 1.10
    twoToSix = 2.20,
    sixToTen = 3.70
    overTen= 3.80

    #Local Variable
    shipping = 0.0

    #calculate charges
    if wt > 10.0:
        shipping = wt * overTen
    elif wt > 6.0:
        shipping = wt * sixToTen
    elif wt > 2.0:
        shipping = wt * twoToSix
    else:
        shipping = wt * underTwo
    #display shipping charge
    print ("Shipping charge for this package is: $", shipping)

#return to main
main()

这里有一些问题。主要的一点是,在赋值给weight之前,不要将字符串转换为浮点。您可以通过以下方式实现:

weight = float(input(...

你不需要在那之前设置weight = 0.0。它被完全覆盖了。你知道吗

其他的问题是你的缩进是错误的,“计算费用”片段在函数之外。它将作为模块代码块的一部分运行。你知道吗

你在评论中的命名也不正确。你在定义函数,而不是模块。(maincalcAndDisplayShipping)最后您也在调用main,而不是返回到它。你知道吗

最后,这并没有达到您的期望:

twoToSix = 2.20,

它定义了一个1元素元组,相当于twoToSix = (2.20,)。你需要去掉逗号来得到一个数字本身。你知道吗

在python3中,input返回一个字符串。要获得一个float,您应该将这个调用包装在float()。你知道吗

weight = input("Enter the weight of your package: ")

在这里您可能会遇到另一个问题,即在编写本文时,您永远不会退出函数调用—您只会增加调用堆栈的大小。相反,您可能希望删除calcAndDisplayShipping末尾对main的调用,然后在main中使用while循环。你知道吗

def main():

    #local variables
    weight = 0.0

    while True:
        #get package weight
        weight = float(input("Enter the weight of your package: "))

        #call module to calculate and display shipping charges
        calcAndDisplayShipping(weight)

相关问题 更多 >

    热门问题