我正在嘗試解決一個家庭作業問題,我輸入價格、重量和距離來計算客戶的總成本。我遇到的問題是我需要根據距離的距離應用折扣,例如 500 英里 = 15% 的折扣,但是當我嘗試時我破壞了我的代碼。見附上的代碼。
base = float(input("How much is the base price?: "))
weight = float(input("What is the weight?: "))
distance = float(input("What is the distance?: "))
if distance <250:
discount = 0% # no discount
elif distance >= 250 and distance <= 500:
discount = 10% # 10 % discount
elif distance >= 500 and distance <= 1000:
discount = 15% # 15% discount
elif distance >= 1000 and distance <= 2000:
discount = 20% # 20% discount
elif distance >= 2000 and distance <= 3000:
discount = 35 % # 35% discount
elif distance >= 3000:
discount = 50% # 50% discount
sum = base * weight * distance *(1 - discount)
print("The shipping cost is: ",sum)
我需要使用等式 sum = baseprice * weight * distance * (1 - discount)。
提前致謝
uj5u.com熱心網友回復:
以下是所需的更改:
10%->0.1=-> =ifs之一上的錯誤縮進- 洗掉
and_
10%不是有效格式,請改用 0 到 1 之間的值。
由于discount未添加到(已定義),=因此應使用。
由于您正在使用elif,因此無需添加and檢查。
這是一個作業代碼:
base = float(input("How much is the base price?: "))
weight = float(input("What is the weight?: "))
distance = float(input("What is the distance?: "))
if distance <250:
discount = 0 # no discount
elif distance >= 250:
discount = 0.1 # 10 % discount
elif distance >= 500:
discount = 0.15 # 15% discount
elif distance >= 1000:
discount = 0.20 # 20% discount
elif distance >= 2000:
discount = 0.35 # 35% discount
elif distance >= 3000:
discount = 0.5 # 50% discount
sum = base * weight * distance *(1 - discount)
print("The shipping cost is: ",sum)
uj5u.com熱心網友回復:
洗掉 % 并除以 100 以獲得百分比。 = 有不同的目的。我不認為這是你在這里的要求。您可以在此處通過示例閱讀有關此內容的資訊https://www.geeksforgeeks.org/assignment-operators-in-python/
此外,當您and distance <= 500在第 2 個條件下使用第一個 elifand >= 500時,將應用第一個條件折扣。此代碼應該可以作業:
base = float(input("How much is the base price?: "))
weight = float(input("What is the weight?: "))
distance = float(input("What is the distance?: "))
# discout = 0
if distance < 250:
discount = 0 # no discount
elif distance >= 250 and distance < 500:
discount = 10 # 10 % discount
elif distance >= 500 and distance < 1000:
discount = 15 # 15% discount
elif distance >= 1000 and distance < 2000:
discount = 20 # 20% discount
elif distance >= 2000 and distance < 3000:
discount = 35 # 35% discount
elif distance >= 3000:
discount = 50 # 50% discount
total = base * weight * distance * (1 - (discount/100))
print("The shipping cost is: ",total)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451581.html
標籤:Python python-3.x
上一篇:如何將一個熊貓資料框中的多列合并為一個系列?[復制]
下一篇:嘗試使用通配符*過濾列
