I have made a program that adds up the orders of a fast food menu. I need to add a running subtotal after I have made an order. As I am a python novice, I am not quite sure what to do. I also need to make sure my order dictionary is modified, but am unsure how to do so.
I thought about making a loop with a range to keep the total but I do not want a range as I want the program to be able to take as many orders as possible.
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
bcount = 0
fcount = 0
dcount = 0
while True:
print("Please make a selection:")
print("1. Burger = $5.00")
print("2. Fries = $3.50")
print("3. Drink = $1.00")
print("4. Quit")
choice = int(input('Please order: '))
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
elif choice == 2:
amount = int(input("Enter number of Fries: "))
fcount += amount
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
dcount += amount
elif choice == 4:
sub = (bcount * 5.00) + (fcount * 3.50) + (dcount * 1.00)
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(bcount))
print('Number of Fries: {0}'.format(fcount))
print('Number of Drinks: {0}'.format(dcount))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
The expected result is after each order, the program would give me a running subtotal.
Example: after an order of a burger is entered would look like:
Your subtotal is: $5.00
Then the next order is an order of fries and a drink
Your subtotal is: $9.50 (adding the burger from the previous order)
One way to do this is to add a variable called subtotal in the beginning called subtotal. Attached one example for the burger that can be applied to the rest. I agree with previous commenter regarding reset of variables instead of break.
subtotal=0
bcount = 0
fcount = 0
dcount = 0
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
subtotal+=(amount*5)
print("Your total is: ",subtotal)
I assume, for option 1 - 3, you need to show the subtotal and for option 4 you need to show the full report.
I have updated the code as following:
added calculate_sub_total method.
displayed subtotal for option 1-3.
separated the if-elif-else to two partitions.
Used the menu dictionary to fetch prices for items both in sub total calculation and in displaying the menu.
Used the order dictionary to keep track of the number of items as intended. Removed bcount, dcount, fcount variables as they are not needed anymore.
Updated code:
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
def calculate_sub_total():
return (order["burger"] * menu["burger"]) + \
(order["fries"] * menu["fries"]) + \
(order["drink"] * menu["drink"])
while True:
print("Please make a selection:")
print("1. Burger = ${}".format(menu["burger"]))
print("2. Fries = ${}".format(menu["fries"]))
print("3. Drink = ${}".format(menu["drink"]))
print("4. Quit")
choice = int(input('Please order: '))
show_subtotal = False
if choice == 1:
amount = int(input("Enter number of Burgers: "))
order["burger"] += amount
show_subtotal = True
elif choice == 2:
amount = int(input("Enter number of Fries: "))
order["fries"] += amount
show_subtotal = True
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
order["drink"] += amount
show_subtotal = True
sub = calculate_sub_total()
if show_subtotal:
print('Subtotal: {:0.2f}'.format(sub))
if choice == 4:
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(order["burger"]))
print('Number of Fries: {0}'.format(order["fries"]))
print('Number of Drinks: {0}'.format(order["drink"]))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
Output:
Related
Here is what ive done:
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
I want to display an invoice at the end once the user has completed there order showing there total price.
This is some of my code for just the drinks, same type of code used for cheeseburger etc. :
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink = int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
break
You can use something like this:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
price = 5
quantitydrink = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
print(f"Your total cost is {price}!")
break
So the base price is 5 for the delivery and if you pick cola it adds the price of the cola multiplied by the amount you purchase to the price variable.
The += operator is best for this.
Changes:
price = 5 #added this on line 8 because the delivery cost is 5 so that is the base price
quantitydrink = 0 #added this on line 9 so you can add the amount to it later in the code
quantitydrink += int(input("How many would you like?\n")) # changed this in line 26 to add the amount you are ordering to the initial value.
price += 1 * quantitydrink # added this in line 36 to calculate the price based on how many colas you are ordering and the base price
print(f"Your total cost is {price}!") #added this at line 37 to print the final price of the order
hope this helps!
FINAL CODE WITH ALL FIXES:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
finished = False
food =["cheeseburger", "smallchips", "drink", "delivery"]
prices =[2.50, 1.50, 1, 5]
x=0
price = 5
quantitydrink = 0
quantityburger = 0
quantitychips = 0
quantitydelivery = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
name = input("What is your name?\n")
print("\nHello " + name + "\n")
while finished == False:
try:
burgerselect = input("Please select which burger:\n")
if burgerselect == "cheeseburger":
quantityburger += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if burgerselect != "cheeseburger":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 2.5 * quantityburger
try:
chipselect = input("Please select what size chips:\n")
if chipselect == "small":
quantitychips += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if chipselect != "small":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1.50 * quantitychips
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
deliveryselect=input('Would you like delivery? \n Yes: Delivery\n No: No delivery \n \n')
if deliveryselect=='Yes'or deliveryselect=='yes':
print('Thank You\n')
if price <= 30:
price += 5
elif price > 30:
price += 0
finished == True
break
elif deliveryselect =='No' or deliveryselect=='no':
print('Thank you\n')
finished == True
break
print(f"Your total cost is {price}!")
So I ran into trouble with this code again with output. Basically, there are some key features I need it to print, but whenever I manage to get it to print one thing it completely messes up the rest of the printing. So for example, I need it to print Roll # 1 (1 - 3) was (whatever number) not Roll (whatever number) if that makes sense. But I also need it to only max out to 3 rolls. This is where my second issue comes in; whenever I try to code it to subtract the bet from the bank when a user doesn't match any rolls, it counts my subtraction as a fourth roll and screws up the math. So instead of Roll #1 through #3 its now up to Roll #4
My third problem is, I need to the program to continue looping until the user enters 0 (zero) to end the script or the bank amount reaches 0 (zero).
You should redesign your program. First of all, you are generating new results for each condition check at
if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
Your code is not properly indented.
[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
And so on...
Have a function that simulates a single dice roll, like:
def roll():
return random.randint(1, 6)
And handle the rest in your main function like:
prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
A couple changes get the result you want
Pass the roll count to the rollDice function
Add an else to the bottom of the if block to check 0 bank
Here is the updated code:
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet # no match
if bank == 0:
print('You have no money left. Thanks for playing!')
exit()
Output
You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!
I'm trying to get this For loop to repeat itself for an amount equal to "totalNumStudents"
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
However, the code never gets to this loop and restarts from the beginning.
Here is the first half of the code including the loop.
freshman = 0
sophomore = 0
junior = 0
senior = 0
test_score = 0
totalTestScores = 0
totalNumStudents = freshman + sophomore + junior + senior
# Start a while loop.
while True:
# Display the menu of choices.
print("\nPress '1' to enter a student")
print("Press '2' to quit the program")
print("NOTE: Pressing 2 will calculate your inputs.\n")
# Prompt to enter a choice.
choice = input("Enter your choice: ")
# If the choice is 1.
if choice == '1':
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
# Otherwise, display an error message.
else:
print("Invalid test score! Test score " +
"must be between 0 and 100.")
# Calculate total test scores
totalTestScores = totalTestScores + test_score
What am I missing here?
Since you add up before get those numbers, your totalNumStudents is all always zero. You should put the add up statement after you get the numbers:
...
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
# add up here
totalNumStudents = freshman + sophomore + junior + senior
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
...
BTW since your while True loop only runs once, you don't need the loop. Just remove it.
It's a beginner python program where we are given a menu and user gets to choose which item from 1-5 and 6 to exit. If they choose 6, it would terminate the code, don't ask any other questions and do not show the bill.
I thought placing it at the "elif choice == 6" would work but then it ends the whole code without considering the other previous choices
def get_inputs():
'''get input of each of the burger choices of the user and how much did they want'''
count = 0
quantity1 =quantity2=quantity3=quantity4=quantity5 = 0
flag = True
while flag:
check_choice = True
while check_choice:
try:
choices=int(input("Enter kind of burger you want(1-5 or 6 to exit): ").strip())
if choices <=0:
print("Enter a positive integer!")
else:
check_choice = False
except:
print("Enter valid numeric value")
check_quantity = True
while check_quantity and choices != 6:
try:
quantity = int(input("Enter quantity of burgers wanted: "))
if quantity <=0:
print("Enter a positive integer!")
else:
count +=1
check_quantity = False
except:
print("Enter valid numeric value")
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
flag = False
check_staff = True
while check_staff and count !=0:
try:
tax = int(input("Are you a student? (1 for yea/0 for no)"))
check_staff = False
except:
print("Enter 1 or 0 only")
return quantity1,quantity2,quantity3,quantity4,quantity5,tax
def compute_bill(quantity1,quantity2,quantity3,quantity4,quantity5,tax):
'''calculate the total amount of the burgers and the total price of the purchase'''
total_amount = tax_amount = subtotal = 0.0
student_tax = 0
subtotal = (quantity1 * DA_PRICE) + (quantity2 * BC_PRICE) + (quantity3 * MS_PRICE) + (quantity4 * WB_PRICE) + (quantity5 * DCB_PRICE)
if(tax == 0):
tax = float(STAFF_TAX)
tax_amount = subtotal *(tax/100)
total_amount = subtotal + tax_amount
elif(tax == 1):
total_amount = subtotal+student_tax
return tax_amount, total_amount, subtotal
Expected: when starting the program and pressing 6, it will terminated without asking any other questions and also without showing the bill
Expected: code would get user's input and then when pressing 6, it will continue on to comput_bill function and compute/print the bill
Actual results: when pressing 6 at the beginning, in get_inputs, in the return statement, the local variable "tax" is referenced before assignment
You can just do the loop and when you get a 6 you exit the loop. If there has been no inputs, then skip the student check and the bill calculation.
This is much cleaner than trying to use flag variables to check whether you should print.
Using sys.exit. Is quite a brutal way to terminate your program. It's usually best to delegate the decision to terminate to the outermost functions in your application. It's also better to let the program terminate naturally by reaching the end of the program.
You might use sys.exit for things like incorrect command line arguments.
# example prices.
unitprices = {
1: 7.89, # DA_PRICE
2: 11.00, # BC_PRICE
3: 9.50,
4: 15.85,
5: 21.00
}
STAFF_TAX = 0.2
def calcbill(units, istaxable, unitprices=unitprices, taxrate=STAFF_TAX):
subtotal = 0
for u in units:
subtotal += unitprices[u]
if istaxable:
tax_amount = subtotal * (taxrate / 100)
else:
tax_amount = 0
return (subtotal + tax_amount, tax_amount)
entries = []
print("Enter kind of burger you want(1-5 or 6 to exit): ")
while True:
try:
choice = int(input("what is the next burger? "))
if choice == 6:
break
elif 0 < choice < 6:
entries.append(choice)
else:
print('invalid choice')
except:
print('not a number')
if entries:
while True:
s = input('Are you a student? ').lower()
if s in ('y', 'yes', 'true'):
isstudent = True
break
elif s in ('n', 'no', 'false'):
isstudent = False
break
else:
print('not a valid value')
total, tax = calcbill(entries, not isstudent)
print(f'the bill was ${total:.2f} which includes ${tax:.2f} tax')
As far as I understood from the expected output, you want to exit the code in the following scenarios:-
(1) At the beginning of the code, when there is no value in the kind of the burger, just exit the code, without prompting the user to input again.
(2) After saving some values in the burger count, if the user pressed 6, then also it should not ask the user for the price calculation logic.
If my understanding is right, then you should update your code in the following manner:-
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
check_choices = False
flag = False
import sys
sys.exit()
And the output is as follows:-
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 2
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 4
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$
My current code works but when the option menu appears, and i select an option, its supposed to repeat from the selection again, however my code restarts from the start where it asks to enter a number rather than entering an option.
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
So it means that I need to reposition my code within the while loop, or take the input stage to a different position?
You need a nested loop
(tried to change your original code as little as possible) I changed it to include your options menu within a while loop (in addition to another break statement outside the while loop, to make sure the program doesn't repeat itself (unless you want it to...)).
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
choice = -1 # new
while(choice != 0): # new
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
break # new
keep in mind this COULD be a good deal more robust, and there exists no functionality for handling options selected outside the ones specified (though should someone enter a 5 or something it will just repeat)
Sometimes I find it cleaner to have your cope loop forever with while True and to break out of it as necessary. I also try to reduce nesting where possible, and I don't like to use exception handling for a valid input choice. Here's a slightly reworked example:
amount = 0
total = 0
while True:
n = input("Enter a number: ")
if n == "":
break
amount = amount+1
total = total + int(n)
average = total/amount
while True:
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break