How to fix this (python) - python

I'm making a little application in python, but i have no idea what to do next.
#!/usr/bin/env python
print("Welcome to the store!")
price_list = [['apple', 'orange', 'grapefruit', 'bomb', 'gun'], [3, 2, 5, 15, 10]]
inventory = []
print("You can buy the following things")
print(price_list[0][0])
print(price_list[1][0], 'dollars')
print(price_list[0][1])
print(price_list[1][1], 'dollars')
print(price_list[0][2])
print(price_list[1][2], 'dollars')
print(price_list[0][3])
print(price_list[1][3], 'dollars')
print(price_list[0][4])
print(price_list[1][4], 'dollars')
budget = 20
buy = input("What would you like to buy? Type in one of the previous options to buy something You only have 20 dollars to spend though! ")
print("You bought", buy)
if budget >= 0:
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
if buy == 'orange':
print("It cost 2 dollars")
budget -= 2
inventory.append('orange')
print("Your inventory is below")
print(inventory)
if buy == 'grapefruit':
print("It cost 5 dollars")
budget -= 5
inventory.append('grapefruit')
print("Your inventory is below")
print(inventory)
if buy == 'bomb':
print("It cost 15 dollars")
budget -= 15
inventory.append('bomb')
print("Your inventory is below")
print(inventory)
if buy == 'gun':
print("It cost 10 dollars")
budget -= 10
inventory.append('gun')
print("Your inventory is below")
print(inventory)
I want to make it so i can add one thing, then be able to add another thing until i have reahed my budget, but if i use a while statement, it just keeps adding the thing i buy! help please!

Changing if budget >= 0 to while budget >= 0 is the right idea, you just have to move the request for user input into the while loop as well. That way it will ask for input, check it against the items in the shop, then if budget >= 0 it will do it again, starting with requesting more input.
#!/usr/bin/env python
print("Welcome to the store!")
setup_price_list() #pseudocode
budget = 20
while budget >= 0:
buy = input("What would you like to buy?")
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
#the rest of the if statements
print("You bought", buy)
print("Your inventory is below")
print(inventory)
Once you have got that working, I suggest you take a look at the Python Data Structure called a dictionary. It can make code like this much simpler, for example:
print("Welcome to the store!")
price_list = {'apple':3, 'orange':2, 'grapefruit':5, 'bomb':15, 'gun':10}
print("You can buy:")
for key in price_list:
item = key
price = price_list[key]
print(item, price)
budget = 20
while budget > 0:
buy = raw_input("What do you want to buy?")
price = price_list[buy] #You will get an error if you give it a key it doesn't have
budget -= price
print("You bought: ", buy)
print("It costed: $", price)
Oh and you may want to add in a check to see whether you actually have enough money left to buy the item before you buy it, else you can still buy anything as long as you aren't in debt, I'll leave that to you to figure out :)

Related

Multiple errors in my python school project [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
So, for my school project, that's due tomorrow, I was tasked with making a simple game from if statements. That is exactly what I tried doing, but whenever I run the game and try buying something else other than tomatoes, I still end up buying tomatoes. I don't know what I did wrong, so I am hoping someone can help me.
I'm really new to coding so I'm sorry if this is an annoying question or anything like that.
Here is the code:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
if input("Would you like to enter? Y/N ") == 'Y' or 'y': #go into the shop
print("You entered the shop.")
if input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'tomatoes' or 'Tomatoes' or 'tomato' or 'Tomato' or 't' or 'T': #choose to buy tomatoes
sum = int(money) - 5
print("You bought tomatoes. You have " + str(sum) + " dollars left.") #end balance if you choose tomatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'potatoes' or 'Potatoes' or 'potato' or 'Potato' or 'p' or 'P': #choose to buy potatoes
sum = int(money) - 7
print("You bought potatoes. You have " + str(sum) + " dollars left.") #end balance if you choose potatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'cucumbers' or 'Cucumbers' or 'cucumber' or 'Cucumber' or 'c' or 'C': #choose to buy cucumbers
sum = int(money) - 10
print("You bought cucumbers. You have " + str(sum) + " dollars left.") #end balance if you choose cucumbers
if input("Would you like to enter? Y/N ") != 'Y' or 'y': #don't go into the shop
print("You turned around and walked away from the shop.\n")
Thanks. Hope you can help me.
As already said, there are multiple issues with your code.
First, as already mentioned, input() == 'Y' or 'y' does not work. You need to use input().lower() == 'y', or input() in ['y','Y']. You should definately use this list method in your later checks, as it shortens your if clauses a lot.
Second, using buit in function names as a variable name is never a good idea, because you can't use the function later on.
Third, mind your indentation. You don't need to indent code more for every if statement, you can just indent it the same.
Fourth, you should not convert your money variable to int every time, as it is already int.
Fifth, you should save the result of your inputs into variables. Now, if the user types in patatoes in the first input, then there will be asked him another time what he wants to buy instead of the user being noticed that he just buyed patatoes.
I would suggest the following:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
tobuy=input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ")
if tobuy.lower() in ["tomatoes","tomato","t"]: #choose to buy tomatoes
balance = money - 5
print("You bought tomatoes. You have " + str(balance) + " dollars left.") #end balance if you choose tomatoes
elif tobuy.lower() in ["patatoes","patato","p"]: #choose to buy potatoes
balance = money - 7
print("You bought potatoes. You have " + str(balance) + " dollars left.") #end balance if you choose potatoes
elif tobuy.lower()in ["cumcumbers","cumcumber","c"]: #choose to buy cucumbers
balance = money - 10
print("You bought cucumbers. You have " + str(balance) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
In the following example, the user is asked what he wants to buy every time again, such that he can buy multiple things. Do also notice that you should change the original money variable instead of creating a new one, such that his money decreases every time he buys something.
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
print("You are at the vegetables isle.")
if input("Do you want to buy tomatoes($7)?").lower()=='y': #choose to buy tomatoes
money = money - 5
print("You bought tomatoes. You have " + str(money) + " dollars left.") #end balance if you choose tomatoes
if input("Do you want to buy potatoes ($7)").lower() == 'y': #choose to buy potatoes
money = money - 7
print("You bought potatoes. You have " + str(money) + " dollars left.") #end balance if you choose potatoes
if input("Do you want to buy cucumbers? ($10) ").lower() == 'y': #choose to buy cucumbers
money = money - 10
print("You bought cucumbers. You have " + str(money) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
from dataclasses import dataclass
from typing import List
#dataclass
class Product:
name: str
plural: str
price: int
key: chr
def __str__(self):
return f'{self.plural}, (${self.price})'
#dataclass
class Customer:
money: int
products: List[Product]
def buy(self, p: Product):
self.money -= p.price
self.products.append(p)
print(f'You bought {p.name}. You have {self.money} dollars left.')
def enter(self, s):
print("You entered the shop.")
s.vegetables_isle(self)
#dataclass
class Shop:
products: List[Product]
def vegetables_isle(self, c: Customer):
print("You are at the vegetables isle.")
print("Do you want to buy", end=' ')
for p in self.products[:-1]: print(p, end = ' ')
print(f'or {self.products[-1]}')
answer = input('choice: ')
for p in self.products:
if answer.lower() in [p.name, p.plural, p.key]:
return c.buy(p)
if __name__ == '__main__':
shop = Shop(products = [
Product(name='tomato', plural='tomatoes', price=5, key='t'),
Product(name='potato', plural='potatoes', price=7, key='p'),
Product(name='cucumber', plural='cucumbers', price=10, key='c'),
])
customer = Customer(50, products=[])
choice = input("Would you like to enter? Y/N ")
if choice.lower() == 'y':
customer.enter(shop)
else:
print("You turned around and walked away from the shop.\n")

Roulette simulation in Python

I am practicing in Python and I decided to create a simple roulette simulation with colors only for now. However, I also wanted to make it possible to bet on color. But it seems like I did something wrong, since for some reason I can't use the global variable 'balance' in one of the function. Also, I didn't come up with the idea of how to make bet a global variable. I tried to take it out so that it become the global variable with input function, however in this case it has the same issue as with balance variable.
import random
balance = 100
# user decides how much they will bet
def start():
print("Place your bet:")
bet = int(input(">"))
if bet > balance:
insufficient_funds()
else:
simulate()
# if user placed too much
def insufficient_funds():
print("Oops, your don't have enough funds to place a bet")
start()
# color choose and roulette simulation
def simulate():
print("Choose Red or for Black:")
answer = input("> ")
result = random.randint(1, 2)
if result == 1 and answer == "Red":
print("You won")
balance += bet
print(f"Your balance now {balance}")
start()
elif result == 2 and answer == "Black":
print("You won")
balance += bet
print(f"Your balance now {balance}")
start()
else:
print("You lost!")
balance -= bet
print(f"Your balance now {balance}")
start()
start()
I know it is super basic, but for now I try to make it as simple as possible to practice with python's fundamental things w/o using a lot of modules. I'd extremely appreciate if you could help me out with it.
Your code is awesome. The way python works, you have to explicitly tell it that you're going to use a global variable by using the global keyword. If you don't, it will create a new local variable within the function. Try:
import random
balance = 100
# user decides how much they will bet
def start():
global balance
print("Place your bet: ")
bet = int(input(">"))
if bet > balance:
insufficient_funds()
else:
simulate(bet)
# if user placed too much
def insufficient_funds():
print("Oops, your don't have enough funds to place a bet")
start()
# color choose and roulette simulation
def simulate(bet_amount):
global balance
print("Choose Red or for Black:")
answer = input("> ")
result = random.randint(1, 2)
if result == 1 and answer == "Red":
print("You won")
balance += bet_amount
print(f"Your balance now {balance}")
start()
elif result == 2 and answer == "Black":
print("You won")
balance += bet_amount
print(f"Your balance now {balance}")
start()
else:
print("You lost!")
balance -= bet_amount
print(f"Your balance now {balance}")
start()
start()
This is how you let Python know you're calling a global variable. To avoid variable shadowing, we can use bet in the start function, and then when we call it in the simulate function, we'll tell it that we need a bet_amount.
Your functions should isolate levels of concerns that are semantically meaningful. This would make the code easier to understand and maintain. The process can be decomposed into:
A betting phase where the user selects a pocket and bet amount
A rolling phase where the ball is rolled and falls in a random pocket
A game loop to repeatedly go through the phases and update wins & losses.
Each function should be standalone and perform its work without affecting data outside of it (i.e. no global variable). This will allow testing the "phase" functions independently before putting them together in the main loop. If you find any issue while testing these functions, you will know that there is no dependencies from external states so the problem is in the limited scope of the function itself.
Here's an example:
Rolling Phase...
from random import choice
from time import sleep
# CONSTANTS
pockets = ["00"]+[str(n) for n in range(37)]
groups = ["Red","Black","Even","Odd","Low","High"]
reds = [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36]
def roll():
print("Rolling! ... ", end="")
sleep(2)
number = choice(pockets)
N = int(number)
color = "" if N<1 else "Red" if N in reds else "Black"
oddEven = "" if N<1 else "Odd" if N%2 else "Even"
lowHigh = "" if N<1 else "Low" if N<=18 else "High"
print(number, color)
return number,color,oddEven,lowHigh
Betting Phase...
def placeBet(maxAmount):
while True:
playerChoice = input("Pocket number or group: ")
if playerChoice not in pockets + groups:
print("must chose a number (00,0,1..36)")
print("or group (Red, Black, Odd, Even, Low, High)")
else: break
while True:
betValue = input("Amount to bet: ")
try:
betValue = int(betValue)
if betValue <= maxAmount: break
print("Not enough funds")
except ValueError:
print("invalid number")
return playerChoice, betValue
Main game loop...
def playRoulette(balance=100):
while balance:
pocket, amount = placeBet(balance)
if pocket in roll():
print("You win!")
balance += amount # or balance += payBack(pocket,amount)
else:
print("You lose!")
balance -= amount
print(f"Your balance is now {balance}")
print("Game Over!")
Winning payback could be computed in a separate function if you want to make it dependent on the odds of the selected pocket (e.g. a specific number is 35 to 1; Red, Even, ... are 1 to 1 bets)
Testing
roll()
Rolling! ... 6 Black
('6', 'Black', 'Even', 'Low')
roll()
Rolling! ... 33 Black
('33', 'Black', 'Odd', 'High')
placeBet(50)
Pocket number or group: green
must chose a number (00,0,1..36)
or group (Red, Black, Odd, Even, Low, High)
Pocket number or group: 99
must chose a number (00,0,1..36)
or group (Red, Black, Odd, Even, Low, High)
Pocket number or group: Red
Amount to bet: xxx
invalid number
Amount to bet: 65
Not enough funds
Amount to bet: 24
('Red', 24)
Sample run
playRoulette()
Pocket number or group: Red
Amount to bet: 10
Rolling! ... 2 Black
You lose!
Your balance is now 90
Pocket number or group: Black
Amount to bet: 25
Rolling! ... 12 Black
You win!
Your balance is now 115
Pocket number or group: 00
Amount to bet: 120
Not enough funds
Amount to bet: 115
Rolling! ... 9 Red
You lose!
Your balance is now 0
Game Over!

How to create menu in Python with multiple if statements

I'm trying to create a menu for a POS like system. I have my gift card balances with their numbers and I'm trying to incorporate this in a menu. In the menu for example, if a user click the number '1', I want the menu to prompt the user for the gift card number in which they will need to enter the correct gift card number (giftnum1). If the user does not click on a valid number or does not enter the correct gift card, I would like the menu to ask the user to click on a valid number or if the user enters the wrong gift card number, I would like for the menu to ask the user to check the gift card number and try again. I am new at this, so I know that most of my menu code is wrong and could be corrected somehow, but I'm not sure how to do this and all other posts relating to this do not make sense with this post.
Here is my code that I have:
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
if buyitems != giftnum1:
print("You have entered an incorrect gift card number.")
elif buyitems == 2:
input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if buyitems == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
You aren't saving the result of the second input() call, so buyitems is still the same value it was before.
You probably want something like this:
if buyitems == 1:
giftcard = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcard == giftnum1:
Please try below code :
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
while loop:
giftcardno = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcardno == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
break
else:
print("You have entered an incorrect gift card number. Try again")
elif buyitems == 2:
giftcardno = input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if giftcardno == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
else:
print("You have entered an incorrect gift card number. Try ag")
else:
break
Hetal Thaker and John Gordon answers are what you are looking for. One issue that may arise though, as you have probably noticed, is that your loop becomes endless even when you select the correct gift card number. To fix that simply set your loop variable to False once an item is purchased and it will work.
I have played around with your code a bit and made some transformations using dictionaries and less hard coding. Check it out, it might help in case you have larger data of variables - you can simply put them into the 2 dictionaries and the rest will work on it's own. Note that I did not implement any logic on what happens when the user selects "Exit" as I am not sure what behavior exactly you expect from the program for that. It would also be good to add logic in case the correct gift card is entered but its balance is not enough.
gift1_balance = 100
gift2_balance = 13.50
gift3_balance = 67.40
gift1_num = 123456
gift2_num = 998765
gift3_num = 456789
gift_cards = {gift1_num: gift1_balance, gift2_num: gift2_balance, gift3_num: gift3_balance}
merch_to_sell = {"Nike Shoes": [100, 1], "Bluetooth Headphones": [67.40, 2], "Gloves": [13.50, 3]}
print("Here are your current gift cards with the current balances:")
for key, value in gift_cards.items():
print(f"${value} with the gift card number of {key}")
def item_menu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
index = 1
for key, value in merch_to_sell.items():
print(f"{index}. {key} (${value[0]:.2f})")
index += 1
print(f"{index}. Exit")
is_item_bought = False
while not is_item_bought:
item_menu()
number_of_item = int(input("Enter the number corresponding to the item that you would like to buy: "))
current_item = 0
current_price = 0
current_index = 0
get_gift_num = 0
for k, v in merch_to_sell.items():
current_item = k
current_price = v[0]
current_index = v[1]
if is_item_bought:
break
if number_of_item == current_index:
get_gift_num = int(input(f"Please enter the correct gift card to buy the {current_item}: "))
for k, v in gift_cards.items():
if get_gift_num == k and gift_cards[k] == current_price:
print(f"You have successfully entered the correct gift card to buy the {current_item}, please follow the directions to be sent a confirmation email.")
is_item_bought = True
break
if not is_item_bought:
print("You have entered an incorrect gift card number.")
If you take this code, you can refactor it and eliminate some unnecessary variables within it and optimize it even further.
Cheers!

Adding a running subtotal to a created food menu

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:

keeping a running total of the values in a dictionary

I want the user to pick an item from the shop and I want to use a loop to keep track of the prices(the value in the dictionary) to add up and keep a running total after every input from user. If the user inputs something that is not in the dictionary, it should say that it does not exist.
thanks in advance for help
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
for key, value in machine.items():
print(key,value)
print("------------------------------")
selection = input("Please choose the number of the item you would like to purchase: ")
total=0
for i in machine:
if selection=="1":
print("You chose shirt and your total is: $", machine["1.shirt: $"])
elif selection=="2":
print("You chose shirt and your total is: $", machine["2.pants: $"])
elif selection=="3":
print("You chose shirt and your total is: $", machine["3.sweater: $"])
elif selection=="4":
print("You chose shirt and your total is: $", machine["4.socks: $"])
elif selection=="5":
print("You chose shirt and your total is: $", machine["5.hat: $"])
else:
print("Your option does not exist. Your total is: ",total)
You should update the value of total every time a choice is made. See example below
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
total=0
for key, value in machine.items():
print(key,value)
print("------------------------------")
while True: # Keep Looping
selection = input("Please choose the number of the item you would like to purchase: ")
if selection=="1":
total += machine["1.shirt: $"];
print("You chose shirt and your total is: $", total)
elif selection=="2":
total += machine["2.pants: $"];
print("You chose shirt and your total is: $", total)
else:
print("Your option does not exist. Your total is: ",total)
break

Categories

Resources