I have this exercise , calculates the cost of sending a small parcel. Te post office charges R5 for the first 300g, and R2 for every 100g thereafter (rounded up), up to a maximum weight of 1000g .
weight = raw_input("What are the weight of you parcel: ")
if weight <= 1000:
if weight <= 300:
cost = 5
print("You parcel cost: " + cost)
else:
cost = 5 + 2 * round((weight - 300)/ 100)
print("You parcel cost: " + cost)
else:
print("Maximum weight for amall parcel exceeded.")
print("Use large parcel service instead.")
When i execute the IDLE console , I come only the last else statements.
5 Answers 5
Cast weight to an int, weight = int(weight). Right now it's a string, which always evaluates to False when compared to 1000.
3 Comments
print statement.First, you've got indentation problems. Two, you are comparing strings to ints. Then, compare...
>>> (350 - 300) / 100
0
>>> (350 - 300) / float(100)
0.5
You should check this yourself, but round(0) = 0, and round(0.5) = 1.
Here's the code that should fix the problems
weight = int(raw_input("What are the weight of you parcel: "))
if weight <= 1000:
if weight <= 300:
cost = 5
else:
cost = 5 + 2 * round((weight - 300) / float(100))
print("Your parcel cost: {}".format(cost))
else:
print("Maximum weight for small parcel exceeded.")
print("Use large parcel service instead.")
5 Comments
350 displays 7 and 300 displays 5. repl.it/EjQN/0 weight becomes a string type on line 1, then in the if statement you compare weight to an int. Fix this by converting the user input to int
Change your first line to:
weight = int(raw_input("What are the weight of you parcel: "))
Also if you are using python3 I would change raw_input to input
5 Comments
print("You parcel cost: " + cost) you try to bring a string and float together, you need to convert the cost to a string like this: print("You parcel cost: " + str(cost))float(Use input() instead of raw_input() for integers and don't try to concatenate strings and integers.
The following code works:
weight = input("What are the weight of you parcel: enter code here")
if weight <= 1000:
if weight <= 300:
cost = 5
print("You parcel cost: " + str(cost))
else:
cost = 5 + 2 * round((weight - 300)/ float(100))
print("You parcel cost: " + str(cost))
else:
print("Maximum weight for amall parcel exceeded.")
print("Use large parcel service instead.")
5 Comments
input evaluates it.Cast variable weight to a float when doing mathematics operation by
weight=float(input())
It will solve all the problems.
Comments
Explore related questions
See similar questions with these tags.