该程序的目标是根据输入权重计算价格。你知道吗
#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,却找不到任何帮助。你知道吗
由于python3.x不计算和转换数据类型,因此必须显式地转换为float,使用float,如
float(input("question:"))
试试这个:
这里有一些问题。主要的一点是,在赋值给
weight
之前,不要将字符串转换为浮点。您可以通过以下方式实现:你不需要在那之前设置
weight = 0.0
。它被完全覆盖了。你知道吗其他的问题是你的缩进是错误的,“计算费用”片段在函数之外。它将作为模块代码块的一部分运行。你知道吗
你在评论中的命名也不正确。你在定义函数,而不是模块。(
main
,calcAndDisplayShipping
)最后您也在调用main
,而不是返回到它。你知道吗最后,这并没有达到您的期望:
它定义了一个1元素元组,相当于
twoToSix = (2.20,)
。你需要去掉逗号来得到一个数字本身。你知道吗在python3中,
input
返回一个字符串。要获得一个float,您应该将这个调用包装在float()
。你知道吗在这里您可能会遇到另一个问题,即在编写本文时,您永远不会退出函数调用—您只会增加调用堆栈的大小。相反,您可能希望删除
calcAndDisplayShipping
末尾对main
的调用,然后在main
中使用while循环。你知道吗相关问题 更多 >
编程相关推荐