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: ")
Related
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
I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:
def spending(income, totals):
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif finalTotal > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
It is printing:
You saved $ -805.00 this month!
When I'd like it to print:
You overspent by $ 805.00 this month!
Any feedback would be greatly appreciated!!
Here is my code:
https://replit.com/#ashleyshubin/BudgetProgram#main.py
If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be
if finalTotal > 0:
The second if statement would be
if finalTotal < 0:
And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number
Your checks are wrong. You can do the following:
def spending(income, totals):
finalTotal = income - totals
if income > totals:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%-finalTotal, "this month!")
else:
print("You broke even this month!")
This section is where it is going wrong:
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:
if income > (income - totals):
this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.
your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals, also else never runs based on the other conditions in your code:
def spending(income, totals):
finalTotal = income - totals
if finalTotal > 0:
print("You saved $", "%.2f" % finalTotal, "this month!")
else:
print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")
you should be comparing Income with total spends.
def spending(income, totals):
finalTotal = abs(income - totals)
if totals < income:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
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()
def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
name=input("\nEnter stock name OR -999 to Quit: ")
totalpr=0
def calc():
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
global totalpr
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
load()
calc()
display()
main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
I need the main(): to call load(),calc() and display() in that order. However, the program stops after load. The output will merely loop the load without calc or print.
I have been instructed specifically to NOT place calc() and display() in the while loop block, tempting as that may be. Also note, that solves the problem but that is not the solution I am specifically looking for.
What do I need to do to make this program work properly?
OUTPUT SHOULD LOOK LIKE THIS:
Enter stock name OR -999 to Quit: APPLE
Enter number of shares: 10000
Enter purchase price: 400
Enter selling price: 800
Enter commission: 0.04
Stock Name: APPLE
Amount paid for the stock: $ 4,000,000.00
Commission paid on the purchase: $ 160,000.00
Amount the stock sold for: $ 8,000,000.00
Commission paid on the sale: $ 320,000.00
Profit (or loss if negative): $ 3,520,000.00
Enter stock name OR -999 to Quit: FACEBOOK
Enter number of shares: 10000
Enter purchase price: 5
Enter selling price: 500
Enter commission: 0.04
Stock Name: FACEBOOK
Amount paid for the stock: $ 50,000.00
Commission paid on the purchase: $ 2,000.00
Amount the stock sold for: $ 5,000,000.00
Commission paid on the sale: $ 200,000.00
Profit (or loss if negative): $ 4,748,000.00
Enter stock name OR -999 to Quit: -999
Total Profit is $ 14,260,000.00
HERE IS THE OUTPUT ERROR I AM GETTING:
====== RESTART: C:\Users\Elsa\Desktop\Homework 3, Problem 1.py ======
Enter stock name OR -999 to Quit: YAHOO!
Enter number of shares: 10000
Enter purchase price: 10
Enter selling price: 100
Enter commission: 0.04
Enter stock name OR -999 to Quit: GOOGLE
Enter number of shares: 10000
Enter purchase price: 15
Enter selling price: 150
Enter commission: 0.03
Enter stock name OR -999 to Quit: -999
Stock Name: -999
Amount paid for the stock: $ 150,000.00
Commission paid on the purchase: $ 4,500.00
Amount the stock sold for: $ 1,500,000.00
Commission paid on the sale: $ 45,000.00
Profit (or loss if negative): $ 1,300,500.00
Total Profit is $ 1,300,500.00
>>>
The first problem is that you are clobbering the variable name every time you execute the input statement. You need to assign the result of input to temporary variable and check that for equality to -999, like this:
def load():
global name
global count
global shares
global pp
global sp
global commission
count =0
while True:
s=input("Enter stock name OR -999 to Quit: ")
if s == '-999':
break
name = s
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
Now when the function returns, the value of name will be a valid stock name.
The second problem is that your teacher has apparently instructed you not to do the very thing that you need to do in order to make your program work. If you can't put the functions that you need to call inside a loop, they can only run once. In that case it is logically impossible to get a separate printout for each stock. I can't help you with that.
Based on your comment
take the calc() and display() inside the loop and move them directly into def main():
this is consistent with your expected output:
def main():
name=input("Enter stock name OR -999 to Quit: ")
count, totalpr = 0, 0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
# calculation
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
# printing
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
# next loop
name=input("\nEnter stock name OR -999 to Quit: ")
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
It seems like an exercise in refactoring - moving function together into a single function.
def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
name=input("\nEnter stock name OR -999 to Quit: ")
totalpr=0
def calc():
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
global totalpr
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
load()
calc()
display()
main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
I need the main(): to call load(),calc() and display() in that order. However, the program stops after load. The output will merely loop the load without calc or print.
I have been instructed specifically to NOT place calc() and display() in the while loop block, tempting as that may be. Also note, that solves the problem but that is not the solution I am specifically looking for.
What do I need to do to make this program work properly?
OUTPUT SHOULD LOOK LIKE THIS:
Enter stock name OR -999 to Quit: APPLE
Enter number of shares: 10000
Enter purchase price: 400
Enter selling price: 800
Enter commission: 0.04
Stock Name: APPLE
Amount paid for the stock: $ 4,000,000.00
Commission paid on the purchase: $ 160,000.00
Amount the stock sold for: $ 8,000,000.00
Commission paid on the sale: $ 320,000.00
Profit (or loss if negative): $ 3,520,000.00
Enter stock name OR -999 to Quit: FACEBOOK
Enter number of shares: 10000
Enter purchase price: 5
Enter selling price: 500
Enter commission: 0.04
Stock Name: FACEBOOK
Amount paid for the stock: $ 50,000.00
Commission paid on the purchase: $ 2,000.00
Amount the stock sold for: $ 5,000,000.00
Commission paid on the sale: $ 200,000.00
Profit (or loss if negative): $ 4,748,000.00
Enter stock name OR -999 to Quit: -999
Total Profit is $ 14,260,000.00
HERE IS THE OUTPUT I AM GETTING(THAT I DO NOT WANT):
====== RESTART: C:\Users\Elsa\Desktop\Homework 3, Problem 1.py ======
Enter stock name OR -999 to Quit: YAHOO!
Enter number of shares: 10000
Enter purchase price: 10
Enter selling price: 100
Enter commission: 0.04
Enter stock name OR -999 to Quit: GOOGLE
Enter number of shares: 10000
Enter purchase price: 15
Enter selling price: 150
Enter commission: 0.03
Enter stock name OR -999 to Quit: -999
Stock Name: -999
Amount paid for the stock: $ 150,000.00
Commission paid on the purchase: $ 4,500.00
Amount the stock sold for: $ 1,500,000.00
Commission paid on the sale: $ 45,000.00
Profit (or loss if negative): $ 1,300,500.00
Total Profit is $ 1,300,500.00
>>>
I think this is the solution (one of many) you could probably take:
def load():
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
return shares, pp, sp, commission
def calc(totalpr, shares, pp, sp, commission):
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
return (amount_paid, commission_paid_purchase, amount_sold,
commission_paid_sale, profit_loss, totalpr)
def display(name, amount_paid, commission_paid_purchase,
amount_sold, commission_paid_sale, profit_loss):
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
totalpr = 0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
shares, pp, sp, commission = load()
am_paid, com_paid_purch, am_sold, \
com_paid_sale, profit_loss, totalpr = calc(totalpr, shares, pp, sp, commission)
display(name, am_paid, com_paid_purch,
am_sold, com_paid_sale, profit_loss)
name=input("Enter stock name OR -999 to Quit: ")
return totalpr
totalpr = main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))