Python Shipping Calculator Using IF Statements - python

I am trying to make a Shipping calculator in python by using IF Statements.
The application should calculate the total cost of an order including shipping. I am stuck at a point where python just won't run my code at all. I have a feeling I'm close but I do not know what is wrong with what I'm inputting because python won't return any errors. please someone just steer me in the right direction.
Instructions:
Create a program that calculates the total cost of an order including shipping.
When your program is run it should ...
Print the name of the program "Shipping Calculator"
Prompt the user to type in the Cost of Items Ordered
If the user enters a number that’s less than zero, display an error message and give the user a chance to enter the number again.
(note: if you know loops/iterations, OK to use here, but if not, just a simple one-time check with an if statement will be OK here.)
For example: if the cost is less than zero, print an error message and then re-ask once for the input.
Use the following table to calculate shipping cost:
Cost of Items
Shipping cost
<30
5.95
30.00-49.99
7.95
50.00-74.99
9.95
>75.00
FREE
Print the Shipping cost and Total Cost to ship the item
End the program with an exit greeting of your choice (e.g. Thank you for using our shipping calculator!)
Example 1:
=================
Shipping Calculator
=================
Cost of items ordered: 49.99
Shipping cost: 7.95
Total cost: 57.94
Thank you for using our shipping calculator!
Example 2:
=================
Shipping Calculator
=================
Cost of items ordered: -65.50
You must enter a positive number. Please try again.
Cost of items ordered: 65.50
Shipping cost: 9.95
Total cost: 75.45
Thank you for using our shipping calculator!
Here is the code I have written out so far:
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
main()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
return subtotal
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")

First, I will put the code here then explain all the changes I made (your original attempt was very close, just a few tweaks):
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping(subtotal)
calc_total(subtotal,shipping)
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
while subtotal <= 0:
print("You must enter a positive number. Please try again.")
subtotal = float(input("Cost of Items Ordered: $"))
return subtotal
def calc_shipping(subtotal):
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
return shipping
def calc_total(subtotal,shipping):
total = subtotal + shipping
print("Total Cost: $" + str(round(total,2)))
print("Thank you for using our shipping calculator!")
main()
As #Devang Sanghani mentioned, you should call your main() outside of your function so that it will run
For your calc_subtotal() function, use a while loop to keep taking in user input until given a valid number. Make sure you move your return subtotal outside of this loop so that it will only return it once this number is valid.
In your calc_shipping() function, make sure you take in subtotal as a parameter since you are using it in your function. Make sure you also return shipping.
Similarly, in your calc_total() function, take in both subtotal and shipping as parameters since they are used in your function.
Given these changes, update your main() function accordingly.
I hope these changes made sense! Please let me know if you need any further help or clarification :)

Adding to the above answers, also consider the case where the price can be a few cents, so this line should change:
if subtotal >= 0 and subtotal <= 29.99: # changed from 1 to 0

So there seem to be 2 errors:
You forgot to call the main function
You indented the return statement in calc_subtotal() so it returns the value only if the subtotal <= 0
The correct code might be:
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
calc_subtotal() # Re asking for the input in case of invalid input
else:
return subtotal # returning subtotal in case of valid input
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 0 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
main() # Calling main

Related

Is there a way to use two format codes in an fstring in Python?

I'm building a basic program to calculate taxes in the UK. The code looks like this:
income = int(input("Income: "))
taxable = income - 12570
if income < 12_571:
print(f"You pay no tax.
Your income is £{income:.2f}")
elif income < 50_271:
afterTax = taxable * 0.8
realIncome = afterTax + 12570
print(f"You pay 20% tax.
Your income is £{realIncome:.2f}")
elif income < 150_000:
afterTax = taxable * 0.6
realIncome = afterTax + 12570
print(f"You pay 40% tax.
Your income is £{realIncome:.2f}")
else:
afterTax = taxable * 0.55
realIncome = afterTax + 12570
print(f"You pay 45% tax.
Your income is £{realIncome:.2f}")
`
When I run it, I get this:
Income: 3555555555555555532 You pay 45% tax. Your income is £1955555555555561472.00
The problem is I either format it to have 2 decimal places with :.2f, or to have comas with :,. Is there a way to do both?

How to get the code to display amount of the discount & the total amount of the purchase after the discount & including the giftwrapping if needed

baseballs cost $1.99 each
Develop a Python program that prompts the user to enter the number of baseballs purchased
In addition the program should ask the user if they want giftwrapping and if so add another $2.00 to the order.
I simply want my output to prompt the amount of the discount
(if any) and the total amount of the purchase after the discount and
including the giftwrapping if needed. But I don't know what code is needed to display that output? so I need someone to show me what code it is?
Quantity Discount
0 - 9 0%
10 - 50 5%
51 or more 10%
baseballs = int(input("Enter the number of baseballs purchased: "))
if(baseballs>0):
if baseballs<=9:
disc = baseballs*0.00
elif baseballs<=50:
disc = baseballs*0.05
elif baseballs>=51:
disc=baseballs*0.10
print("Discount : ",disc)
gift_wrapping = input("Do you want gift wrapping?: ")
print(baseballs + " " + "baseballs purchased" )
print(gift_wrapping)
Something like this maybe? Not 100% sure what you're asking:
Do let me know if you want comments on the code.
price = 1.99
baseballs = int(input("Enter the number of baseballs purchased: "))
if(baseballs>0):
if 0 <= baseballs <= 9:
disc = baseballs*0.00
elif 9 <= baseballs <= 50:
disc = baseballs*0.05
elif baseballs <= 51:
disc=baseballs*0.10
print("Discount : ",disc)
gift_wrapping = input("Do you want gift wrapping?: ")
if gift_wrapping == "yes" or "y" or "Yes":
total = (baseballs * price) - disc + 2
else:
total = (baseballs * price) - disc
print(str(baseballs) + " " + "baseballs purchased" )
if disc != 0:
total_disc = total-(baseballs*price)
print("Discount: "+str(total_disc))
print("Total price "+str(total))

Loop function for a check out program in python

My teacher wants this code to run on a loop but I am not sure how to do that. Can anyone help me please?
ask = input("Enter only one name of the item bought like Potatoes, Ham, AppleJuice, or Gatorade: ")
if ask == "potatoes":
def potatoes (quantity, price=5.99):
total = quantity * price
while True:
if quantity > 15:
print("Congratulations, you are eligible for 11% discount")
totalWithDiscount = total - (0.08 * total)
print("your total with 8% discount and no tax: $", totalWithDiscount)
print("Visit us soon!!")
return (0.879 * totalWithDiscount) + totalWithDiscount
else:
print("sorry, you are not eligible for 11% discount")
print("your total with 11% discount and no tax: $", total)
return (0.879 * total) + total
print("Sorry, you are only eligible for discount, if you buy more than 15 Lbs. of Potatoes. ")
print("Total without discount and no Tax $", total)
print("Your Total with Tax: 5.29% is $", tax3)
print("Thank you, for being Walmart' Valuable Shopper.")
print("Visit us soon!!")
potatoes(int(input("Enter the quantity of Potatoes you bought : ")), 8.99)
Your code is very wrong and it will not run, but I have an idea of what you are trying to do, so this will work
def potatoes (quantity, price=5.99):
total = quantity * price
if quantity > 15:
print("Congratulations, you are eligible for 11% discount")
totalWithDiscount = total - (0.08 * total)
print("your total with 8% discount and no tax: $", totalWithDiscount)
print("Visit us soon!!")
return (0.879 * totalWithDiscount) + totalWithDiscount
else:
print("sorry, you are not eligible for 11% discount")
print("your total with 11% discount and no tax: $", total)
tax3 = (0.879 * total) + total
print("Sorry, you are only eligible for discount, if you buy more than 15 Lbs. of Potatoes. ")
print("Total without discount and no Tax $", total)
print("Your Total with Tax: 5.29% is $", tax3)
print("Thank you, for being Walmart' Valuable Shopper.")
print("Visit us soon!!")
while True:
ask = input("Enter only one name of the item bought like Potatoes, Ham, AppleJuice, or Gatorade: ")
if ask == "potatoes":
number_of_potatoes = int(input("Enter the quantity of Potatoes you bought : "))
potatoes(number_of_potatoes, 8.99)
else:
print('Thank you visiting')
break
Your code is a little bit confusing but i hope this is what you intended for.
1.I moved the function definition out of the loop, and it is inside the loop that you call it so the code inside the function can be reused as many times as you need!
2.I also changed the loop condition for when the user inserts "no" so there's an end to it, but change for whatever you want
3.About the return statement it's important to remember that when it's executed the function that it is within ends and return the designated value, everything after it won't be executed, that's why i moved it to the end.
4.And finally there's a variable tax3 that isn't being defined anywhere in your code, maybe you didn't put it here or maybe you just forgot about it, so you need to fix it or delete it so the code works. Hope i understood your question, good programming!
def potatoes (quantity, price=5.99):
total = quantity * price
if quantity > 15:
print("Congratulations, you are eligible for 11% discount")
totalWithDiscount = total - (0.08 * total)
print("your total with 8% discount and no tax: $", totalWithDiscount)
print("Visit us soon!!")
return (0.879 * totalWithDiscount) + totalWithDiscount
else:
print("sorry, you are not eligible for 11% discount")
print("your total with 11% discount and no tax: $", total)
print("Sorry, you are only eligible for discount, if you buy more than 15 Lbs. of Potatoes. ")
print("Total without discount and no Tax $", total)
print("Your Total with Tax: 5.29% is $", tax3)
print("Thank you, for being Walmart' Valuable Shopper.")
print("Visit us soon!!")
return (0.879 * total) + total
ask = input("Enter only one name of the item bought like Potatoes, Ham, AppleJuice, or Gatorade: ")
while(ask != "no"):
if ask == "potatoes":
potatoes(int(input("Enter the quantity of Potatoes you bought : ")), 8.99)
ask = input("Enter only one name of the item bought like Potatoes, Ham, AppleJuice, or Gatorade: ")

How to display certian output while print the result?

Below is the code I use.
# display a welcome message
print("===============================================================")
print("Shipping Calculator")
print("===============================================================")
while True:
# get input from the user
cost_of_items = float(input("Cost of items ordered: "))
# make sure input is a positive number
if cost_of_items < 0:
print("You must enter a positive number. Please try again.")
continue
# to do: get shipping cost(one given for example)
if cost_of_items < 30:
shipping_cost = 5.95
if 30.00 < cost_of_items < 49.99:
shipping_cost = 7.95
if 50.00 < cost_of_items < 74.99:
shipping_cost = 9.95
if cost_of_items > 75:
shipping_cost = 0
# To do: calculate total cost: total_cost
total_cost = cost_of_items + shipping_cost
# to do: display in output, print shipping cost, print total cost
print(shipping_cost,total_cost)
# to do: make your program more interesting, ask user how many item like to ship,
num_of_items = float(input("Number of items to ship: "))
# and caclutate the cost of shipping based on total cost
total_shipping_cost = shipping_cost*num_of_items
final_total_cost = cost_of_items + total_shipping_cost
print(total_shipping_cost, final_total_cost)
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("===============================================================")
if choice.lower() != "y":
break
print("Bye!")
Here is the output I get:
enter image description here
but I want the output to display like:
enter image description here
How can I do that? to put some description before the output? like Number of items to ship: X, Total Shipping cost: XX
You are attempting to create a multi-line string. That can simply be done with "\n"
Example:
# String containing newline characters
line_str = "I'm learning Python.\nI refer to TechBeamers.com tutorials.\nIt is the most
popular site for Python programmers."
That should make it appear like:
"I'm learning Python.
I refer to TechBeamers.com tutorials.
It is the most
popular site for Python programmers."
need to add the newline character to the end of your prints:
\n
Don't forget to print the name of each variable alongside the value of each variable.
print('Shipping Cost: ' + str(shipping_cost) + '\n', 'Total Cost: ' + str(total_cost))
...
print('Total Shipping Cost: ' + str(total_shipping_cost) + '\n', 'Final Shipping Cost: ' + str(final_total_cost))
You need to write some text manually that you want to print as follows
# display a welcome message
print("===============================================================")
print("Shipping Calculator")
print("===============================================================")
while True:
# get input from the user
cost_of_items = float(input("Cost of items ordered: "))
# make sure input is a positive number
if cost_of_items < 0:
print("You must enter a positive number. Please try again.")
continue
# to do: get shipping cost(one given for example)
if cost_of_items < 30:
shipping_cost = 5.95
if 30.00 < cost_of_items < 49.99:
shipping_cost = 7.95
if 50.00 < cost_of_items < 74.99:
shipping_cost = 9.95
if cost_of_items > 75:
shipping_cost = 0
# To do: calculate total cost: total_cost
total_cost = cost_of_items + shipping_cost
# to do: display in output, print shipping cost, print total cost
print("Shipping cost:", shipping_cost)
print("Total cost:", total_cost)
# to do: make your program more interesting, ask user how many item like to ship,
num_of_items = float(input("Number of items to ship: "))
# and caclutate the cost of shipping based on total cost
total_shipping_cost = shipping_cost*num_of_items
final_total_cost = cost_of_items + total_shipping_cost
print("Total Shipping cost:", total_shipping_cost)
print("Final total cost:", final_total_cost)
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("===============================================================")
if choice.lower() != "n":
break
print("Bye!")

Python 3 if statement recognition

The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed << proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
I fixed it, the first if statement used << when it should have used <.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed < proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()

Categories