我已經經歷了C++,現在正在學習Python。我對這裏發生的變化有點困惑。我覺得我應該將「wt」聲明爲Real或Float,但不會接受該語法。我認爲錯誤是在我聲明模塊「calcAndDisplayShipping」的行上。python中的變量定義
該計劃的目標是根據輸入的重量來計算價格。
#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()
我得到的錯誤是... 類型錯誤:「>」
我通過我的語言的同伴搜索蟒蛇,但沒有找到「STR」和「浮動」的實例之間不支持任何幫助。
只需將wt轉換爲浮點數(float(wt))即可。如果用戶輸入非數字值,您將需要一些異常處理。 –
我認爲這適用於Python2 ... Python3爲您提供了一個字符串,即使您似乎認爲您鍵入了一個數字 –
同樣重要的是要注意Python不像C++那樣是動態類型的,因此您不需要聲明變量類型。 –