I am trying to solve a homework problem where I input a price, weight, and distance to work out the total cost for a customer. The problem I have is I need to apply a discount based on how far the distance is for example 500 miles = 15% discount, but when I tried I break my code. see attached the code.
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)
I need to use the equation sum = baseprice * weight * distance * (1 - discount).
thanks in advance
CodePudding user response:
Here are the changes needed:
10%
->0.1
=
-> =- Wrong indent on one of
if
s - Remove
and
s
10%
is not a valid format, use values between 0 and 1 instead.
Since discount
is not getting added to (it is defined), =
should be used.
Since your are using elif
there is no need to add and
check.
Here is a working code:
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)
CodePudding user response:
Remove % and divide by 100 to get percentage. = have a different purpose. I don't think that is what is your requirement here. you can read about that with examples here https://www.geeksforgeeks.org/assignment-operators-in-python/
Also when you have and distance <= 500
in 1st elif and >= 500
in the 2nd condition, 1st conditional discount will be applied. This code should work:
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)