Having problems computing total value - python

im making a food ordering system but im having trouble with multiple order of the same item but in different sizes. I have put "fs,fm,fl" with a value of 0 so that it would be my basis as a counter for each sizes of my fries, i also have used "total" to add up every value of each sizes. After i put "2" large fries and "2" medium fries, My "total" and "fs+fm,+fl" is different from each other.
i expected my total and the added value to be the same but they are different. Is there an error with my computation? Is there any alternative/faster way to calculate the total value of different sizes? here is my code (it is unfinished)
food = ["Burger", "Fries", "Hotdog", "Sundae", "Coke Float"]
cart = []
cost = []
total = 0
fs = 0
fm = 0
fl = 0
def menu():
print(f"\t\t\t\t{'MENU'}")
collection = [["\nCode", " Description", " Size", " Price"],
[" 2", " Fries", " S/M/L", " 20/35/50"]]
for a in collection:
for b in a:
print(b, end=' ')
print()
menu()
first = True
def ordering():
print("\nPlease select the CODE of the food you want to order")
while first == True:
global total
global fs
global fm
global fl
order = input("Type the code you want to order: \n")
#fries
if order == ("2"):
print("You have selected \n")
print("\n", food[1], "\n")
size = input("What size do you want? S/M/L: ")
if size == "s" or size == "S":
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 20
total = total * i
fs = i * 20
print(fs)
elif size == "M" or size == "m":
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 35
total = total * i
fm = i * 35
print(fm)
elif size == "l" or size == 'L':
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 50
total = total * i
fl = i * 50
print(fl)
else:
print("Invalid size")
#cart.append(food[1])
#cost.append(price[1])
try_again = input("\nWould you like to add more? (Y/N):").lower()
if try_again != ("y"):
break
else:
print("\nInvalid input. Please put only the CODE of the item\n")
ordering()
def inside_cart():
while first == True:
print(' ')
print(' ')
print("The inside of your cart are currently:")
print(cart)
print(fs + fm + fl,total)
suggestion = input("would you like to order more? Y/N: ").lower()
if suggestion.lower() == "y":
ordering()
print("\nOkay, proceeding to payment....\n")
break
inside_cart()

I think the error originates in the price calculations:
total = total + 20
total = total * i
fs = i * 20
If you order two small fries this works fine the first time, as total becomes 20 and then 40 to account for it being two items. However, once you order the large fries you first add 50 for a total price of 90, and then multiply it by two for a price of 180, which should be 140.
To fix this, just change the total calculation to this:
total += i * price
Now you will add to the total only the price of the items ordered. As a rule of thumb, you should probably not multiply an accumulated value unless you're sure that's what needs to be done.
For the fs/fm/fl there seems to be an issue present too, as doing multiple orders for the same size will make the value stored in the variable only count the price of the last order of this size. If you for instance ordered small fries and then 1 small fries, fs would only be 20 when it should be 100. To fix that, you can apply an analogous change:
fs += i * 20
So make sure next time that each calculation is done separately, and try to imagine when some orders have already been done, how it would affect the values you are trying to calculate next.
On a different note, you may want to work on creating a table of sorts to store the different prices for items and sizes, as this code will quickly grow out of control for more items and be a nightmare to maintain.
Hope this helps!

Related

Need to find an equation that will not allow user input to exceed 100 if user enters 90 for scoreEarned and 20 for scoreShift output will still be 100

I'm stuck on the elif statement I don't know how I would be able to have the input for example scoreEarned = 90 and scoreShift =20 which equals 110 just be a 100 as a max for the output. Like the max score that can be obtained is 100 but if the user got extra points over the 100, how could it still just return 100 as the maximum score?
#Message display description
print("This program reads exam/homework scores and reports your overall course grade.")
#Space
print()
#Title for Midterm 1
print("Midterm 1:")
#funtion that asks user for input to use
def totalPoint():
#Asking user for weight of assignment
weight = int(input("Weight (0-100)? "))
#Asking user for score earned on assignment, max score is 100
scoreEarned = int(input("Score earned? "))
#variable for bottom half of fraction
outOf = 100
#prompting user to input 1 for yes and 2 for no
yesOrNo = int(input("Were scores shifted (1=yes, 2=no)? "))
#if statement for if there is a score shift
if(yesOrNo == 1):
#prompt user for shift amount
scoreShift = int(input("Shift amount? "))
#if statement that will check user input
if(scoreShift > 0 and scoreShift + scoreEarned <= 100):
#add score earned and score shift
newTotalPoint = scoreEarned + scoreShift
#display new total points
print("Total points = ",newTotalPoint,"/",outOf)
#elif statement if the combined total of the score shift and earned are more than 100
elif(scoreShift > 0 and scoreShift + scoreEarned > 100):
#Need to have a maximum of 100 for total points including the shift
print("This is where I am stuck.")
#else there is no shift score
else:
#Print the score earned out of 100
print("Total points = ",scoreEarned,"/",outOf)
totalPoint()
Just put print(100).
Like this:
elif(scoreShift > 0 and scoreShift + scoreEarned > 100):
#Need to have a maximum of 100 for total points including the shift
print("Total points = 100")
Another more consise/pythonic way to accomplish this is to use the python built-in min() function as follows
scoreEarned = min(100, scoreEarned + scoreShift)
print("Total points = ",scoreEarned,"/",outOf)
min will return the smaller value of the two parameters passed to it. If scoreEarned + scoreShift is greater than your cap value of 100, min will return 100, otherwise it will return the original sum.
Just replace print("This is where I am stuck.") with the logical output at this stage that matters print("You exceeded the maximum score and will receive 100 points ")
This is what I deduced from your question. That's what you want to do, right?

Wrong total price in Python calculation program that sums the cost of parcels with different weights

Working on a python program that asks a user for the amount of parcels to send and the weight of the parcels, the program then multiplies a fixed cost to each parcel depending on the weight given a number of intervals. Problem I face is that whenever I execute my code I get the wrong total cost when I type in the values as seen in the image. It should sum up to $1109 but I get $1262 instead.
image description
My code:
max_2 = 30
between_2_6 = 28
between_6_12 = 25
over_12 = 23
i=0 #Variable for calcuclation
total_price=0 #Start value of total price
parcel=float(input("How many parcels do you want to send? "))
while i<parcel: #While loop which applies for i<input value from value
i+=1 #Add 1 to i för att reduce repetitions
weight = float(input("How much does your parcel weigh " +str(i)+ "?: ")) #weight with decimals
if weight <= 2:
price=weight*max_2
elif (weight > 2 or weight <= 6):
price=weight*between_2_6
elif (weight > 6 or weight <= 12):
price=weight*between_6_12
elif weight > 12:
price=weight*over_12
total_price+=price #total_price=sum of all prices for respective parcel
print(str(total_price)+"USD")
Below is the correct working program. It gives the output you expected. The only changes i made are in the elif conditions. First i have used and instead of or. Secondly note the parenthesis(although not necessary in this case) around individual conditions.
max_2 = 30
between_2_6 = 28
between_6_12 = 25
over_12 = 23
i=0 #Variable for calcuclation
total_price=0 #Start value of total price
parcel=float(input("How many parcels do you want to send? "))
while i<parcel: #While loop which applies for i<input value from value
i+=1 #Add 1 to i för att reduce repetitions
weight = float(input("How much does your parcel weigh " +str(i)+ "?: ")) #weight with decimals
if weight <= 2:
price=weight*max_2
elif ((weight > 2) and (weight <= 6)): #and is used instead of or. Also note the parenthesis around the individual conditions
price=weight*between_2_6
elif ((weight > 6) and (weight <= 12)): #and is used instead of or. Also note the parenthesis around the individual conditions
price=weight*between_6_12
elif weight > 12:
price=weight*over_12
total_price+=price #total_price=sum of all prices for respective parcel
print(str(total_price)+"USD")
Note: The parenthesis around the individual conditions are not necessary in this case. But i like to keep them there. You can remove them if you want.

Anyone know how to receive different inputs inside a loop and add them together in a list

Basically, I am trying to make this menu for a project and I need to make it loop. What I am having difficulty on is trying to take input into a list in a loop. I want the program to add up the totals of every order that is taken and put them into a list. I then want the program to add up this list and give me the final total cost of the order. How would I make it so that I can use a list in a loop without it deleting what was previously inputted in there. For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25. Thanks for the help!
choice = (input("How many people are you ordering for? To quit the program simply type quit."))
while choice != 'quit':
if Beverage == "yes" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries - 1 + KetchupNumber
elif Beverage == "no" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "yes" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "no" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
print("Your total cost is", Total_Cost)
print("You ordered a", SandwichType, "Sandwich,", BeverageType, "Beverage,", FriesType, "Fries,", "and", KetchupType, "Ketchup Packets." )
finalcost = [0]
finalcost.append(Total_Cost)
totaloffinalcost = sum(finalcost)
choice = (input("If you would like to quit then type quit or type anything to continue"))
print("The final cost is", totaloffinalcost)
Apart from the fact that a lot can be done to improve and make this much efficient, the answer to your query:
OP: For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25.
That happens because on each iteration inside the while loop just before taking the sum, you're initialing a list:
finalcost = [0]
Take this outside the while loop:
finalcost = [0]
while choice != 'quit':
# rest of the code

Trying to use loops and add to a variable

I want to create a while loop to prompt the user if they would like to enter a living cost. The user would input 'y' for yes and the loop would proceed.
I this loop I would like to add up all the living expense entered and once the loop ends to store to the total amount in total_living.
Example would be
l_cost = input('Enter living cost? y or n ')
while l_cost != 'n' (loop for living cost)
totat_living = (keeps adding until I say all done
l_cost = input('Enter living cost? y or n ')
Other while and for loops for different scenarios
total_exp = total_living + total_credit + total_debt ect ect
I just need a little help with this as to how to add up multiple values and then maintaining the total value for the loop that I am in.
If someone could point me to an example of a function or loop that is similar or tell me where to look that would be great!
You may try using while as below:
flag = input ("wish to enter cost; y or n" )
total=0
While flag != 'n':.
cost = int(input ("enter cost: "))
total = total + cost
flag = input("more ?? Y or n")
print(total)
total_cost = 0.0
prompt = 'Enter a living cost? y or n: '
answer = input(prompt)
while answer.lower() != 'n':
cost = input('Enter your cost: ')
total_cost = total_cost + float(cost)
answer = input(prompt)
print('Total cost is $' + str(total_cost))
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Note
Try to convert this example to your problem.

Python Sentinel controlled loop

I was wondering if anyone could help point me in the right direction! I'm a beginner and I'm totally lost. I'm trying to make a Sentinel controlled loop that asks the user to "enter the amount of check" and then ask "how many patrons for this check". After it asks the user then enters it until they type -1.
once user is done inputting it is suppose to calculate the total,tip,tax of each check with an 18% tip for anything under 8 patrons and 20%tip for anything over 9 and a tax rate of 8%.
and then it should add up the Grand totals.
ex: check 1 = 100$
check 2 = 300
check 3 = 20
Total checks = $420
I'm not asking for someone to do it for me but just if you could point me in the right direction, this is all i have so far and im stuck.
As of right now the code is horrible and doesn't really work.
I completed it in Raptor and it worked perfectly I just don't know how to convert it to python
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
check = 0
print ("Enter -1 when you are done")
check = int(input('Enter the amount of the check:'))
while check !=(-1):
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
tip = 0
tax = 0
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
total = check + tax + tip
sum1 = sum1 + check
sum2 = sum2 + tip
sum3 = sum3 + patron
sum4 = sum4 + tax
sum5 = sum5 + total
print ("Grand totals:")
print ("Total input check = $" + str(sum1))
print ("Total number of patrons = " + str(sum3))
print ("Total Tip = $" +str(sum2))
print ("Total Tax = $" +str(sum4))
print ("Total Bill = $" +str(sum5))
Your code runs fine, but you have some logic problems.
It appears you're planning to deal with multiple checks at the same time. You'll probably want to use a list for that, and append checks and patrons to it until check is -1 (and don't append the last set of values!).
I think the real issue you're having is that to leave the loop, check must be equal to -1.
If you follow that a bit further down, you continue to work with check, which we now know is -1, regardless of what happened previously in the loop (check is overwritten every time).
When you get to these lines, then you have a real problem:
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
# This is the same, we know check == -1
if patron <= 8:
tip = (-1 * .18)
elif patron >= 9:
tip = (-1 * .20)
At this point you probably won't be able to do anything interesting with your program.
EDIT: A bit more help
Here's an example of what I'm talking about with appending to a list:
checks = []
while True:
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
# here's our sentinal
if check == -1:
break
checks.append((patron, check))
print(checks)
# do something interesting with checks...
EDIT: Dealing with cents
Right now you're parsing input as int's. That's OK, except that an input of "3.10" will be truncated to 3. Probably not what you want.
Float's could be a solution, but can bring in other problems. I'd suggest dealing with cents internally. You might assume the input string is in $ (or € or whatever). To get cents, just multiply by 100 ($3.00 == 300¢). Then internally you can continue to work with ints.
This program should get you started. If you need help, definitely use the comments below the answer.
def main():
amounts, patrons = [], []
print('Enter a negative number when you are done.')
while True:
amount = get_int('Enter the amount of the check: ')
if amount < 0:
break
amounts.append(amount)
patrons.append(get_int('Enter the number of patrons: '))
tips, taxs = [], []
for count, (amount, patron) in enumerate(zip(amounts, patrons), 1):
tips.append(amount * (.20 if patron > 8 else .18))
taxs.append(amount * .08)
print('Event', count)
print('=' * 40)
print(' Amount:', amount)
print(' Patron:', patron)
print(' Tip: ', tips[-1])
print(' Tax: ', taxs[-1])
print()
print('Grand Totals:')
print(' Total amount:', sum(amounts))
print(' Total patron:', sum(patrons))
print(' Total tip: ', sum(tips))
print(' Total tax: ', sum(taxs))
print(' Total bill: ', sum(amounts + tips + taxs))
def get_int(prompt):
while True:
try:
return int(input(prompt))
except (ValueError, EOFError):
print('Please enter a number.')
if __name__ == '__main__':
main()

Categories

Resources