So I'm trying to create a program that can take an order, retrieve it from stock and output the cost. When I do so I get a price of all the items chosen in stock. Any help?
import time
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
def localTime():
localtime = time.asctime(time.localtime(time.time()))
return localtime
stock = {
"I7": 2,
"Keyboard": 3,
"Mouse": 2,
"GPU": 4
}
prices = {
"I7": 250,
"Keyboard": 15,
"Mouse": 12,
"GPU": 350
}
item_p = ''
item_p = input("Please input the item you would like: ")
quantity = int(input("Please input the quantity you would like: "))
if item_p in stock:
print("X ordered a ", item_p,"at", localTime()," Which comes to a total of £", compute_bill(item_p))
else:
print("Error")
Example Output:
Please input the item you would like: Keyboard
X ordered a Keyboard at Fri Feb 9 17:16:09 2018 Which comes to a total of £ 120
I'd replace:
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
with:
def update_stock(component):
global stock
stock[component] -= quantity
def compute_bill(component):
update_stock(component)
return quantity * prices[component]
Your compute_bill function should be implemented simply like this:
def compute_bill():
return prices[item_p] * quantity
Related
The canteen in the Institute maintains has a table of prices of items, like:
Samosa: 15
Idli: 30
Maggie: 50
Dosa, 70
…
For the program you have to write, set the menu in your program by this statement (feel free to add more items).
menu = [("Samosa", 15), ("Idli", 30), ("Maggie", 50), ("Dosa", 70), ("Tea", 10), ("Coffee", 20), ("Sandwich", 35), ("ColdDrink", 25)]
Write a program to take a user's order on a terminal and compute the bill. First show the menu by printing the menu. For ordering an item, the user inputs the item number and the quantity desired (e.g. an input can be: 3 1 followed by 1 5). The program should prompt the user to order more, till he/she hits return (without any numbers) - which is the end of the order. Print a bill for this order in the form (for the input example above):
Maggie, 1, Rs 50
Samosa, 5, Rs 75
TOTAL, 6 items, Rs 125
How can I access the list and take inputs and add them?
First initialize the global variables:
bill = []
total_quantity = 0
total_price = 0
Inside the loop you will ask for the order and exit the loop if it is an empty string:
order = input("Please specify an item number and a quantity: ")
if order == "" : break
Then parse the order, by splitting the input string before and after the space:
(index_string, quantity_string) = order.split(" ")
Now access the menu variable and compute the price:
quantity = int(quantity_string)
item = menu[int(index_string)-1]
name = item[0]
unit_price = int(item[1])
price = unit_price * quantity
and update the global variables:
bill.append("%s, %d, Rs %d" % (name, quantity, price))
total_quantity += quantity
total_price += price
Finally you can print what you collected:
for string in bill :
print(string)
print("\nTOTAL, %d items, Rs %d" % (total_quantity, total_price))
This is the final code:
menu = [("Samosa", 15), ("Idli", 30), ("Maggie", 50), ("Dosa", 70), ("Tea", 10), ("Coffee", 20), ("Sandwich", 35), ("ColdDrink", 25)]
print(menu)
bill = []
total_quantity = 0
total_price = 0
while True :
order = input("Please specify an item number and a quantity: ")
if order == "" : break
(index_string, quantity_string) = order.split(" ")
quantity = int(quantity_string)
item = menu[int(index_string)-1]
name = item[0]
unit_price = int(item[1])
price = unit_price * quantity
bill.append("%s, %d, Rs %d" % (name, quantity, price))
total_quantity += quantity
total_price += price
for string in bill :
print(string)
print("\nTOTAL, %d items, Rs %d" % (total_quantity, total_price))
Is there a way to put limitations on the integer input of a dictionary? The current way I have it set up checks the whole dictionaries individual inputs after, is there a way I can set it up so it can give more instant feed back. E.g. User inputs an integer value of 6 then an error and prompt appears straight away?
def shop_dictionary(shop):
shop_dict = {}
for key in range(1, shop + 1):
shop_name = f"Shop {key}"
while True:
try:
shop_dict[shop_name] = {
"Chocolate": int(input(f"{shop_name} Chocolate Amount: ")),
"Strawberry": int(input(f"{shop_name} Strawberry Amount: ")),
"Vanilla": int(input(f"{shop_name} Vanilla Amount: ")),
}
break
except ValueError:
print(
"Invalid. Please enter an amount between 1 and 5."
)
if shop_dict[shop_name]["Chocolate"] < 1 or shop_dict[shop_name]["Chocolate"] > 5:
print("Invalid number. Please enter a number between 1 and 5.")
shop_dict[shop_name]["Chocolate"] = int(input(""))
if shop_dict[shop_name]["Strawberry"] < 1 or shop_dict[shop_name]["Strawberry"] > 5:
print("Invalid number. Please enter a number between 1 and 5.")
shop_dict[shop_name]["Strawberry"] = int(input(""))
if (
shop_dict[shop_name]["Vanilla"] < 1
or shop_dict[shop_name]["Vanilla"] > 5
):
print("Invalid number. Please enter a number between 1 and 5.")
shop_dict[shop_name]["Vanilla"] = int(input(""))
return shop_dict
Preferably I would like to know if this is possible during the input stage, is there something I could write that would do something like the following?
shop_dict[shop_name] = {
"Chocolate": integer between range of 1 to 5(input(f"{shop_name} Chocolate Amount: ")),
"Strawberry": integer between range of 1 to 5(input(f"{shop_name} Strawberry Amount: ")),
"Vanilla": integer between range of 1 to 5(input(f"{shop_name} Vanilla Amount: ")),
}
Thanks. Sorry for the noob question.
Create a helper function that doesn't return until user enters correct value.
def get_int(prompt, minn, maxx):
while True:
try:
val = int(input(prompt))
if minn <= val <= maxx:
return val
except:
pass
print(f"Invalid number. Please enter a number between {minn} and {maxx}.")
def shop_dictionary(shop):
flavors = ["Chocolate", "Strawberry", "Vanilla"]
shop_dict = {}
for key in range(1, shop + 1):
shop_name = f"Shop {key}"
shop_dict[shop_name] = {flavor: get_int(f"{shop_name} {flavor} Amount: ", 1, 5) for flavor in flavors}
return shop_dict
If you are not familiar with dictionary comprehension, the line
shop_dict[shop_name] = {flavor: get_int(f"{shop_name} {flavor} Amount: ", 1, 5) for flavor in flavors}
is the same as
shop_dict[shop_name] = {}
for flavor in flavors:
shop_dict[shop_name][flavor] = get_int(f"{shop_name} {flavor} Amount: ", 1, 5)
The code should Capture products in stock (i.e. name, price, date supplied, supplier name, quantity), Retrieve the price when name is given upon each purchase and deducts the quantity in
stock, Calculate the total price for each purchase and prints value indicating date and time of
purchase, Sends an alert when quantity reaches 5 to shopkeeper and places order to supplier.
My code right now is not looping so that I can add a number of products then be able to access them, I tried using a while loop but it is running forever. Kindly help
import datetime
class Stock:
def __init__(self, name, price, supplier, quantity,date):
self.name = name
self.price = price
self.date = date
self.supplier = supplier
self. quantity = quantity
def check_item(self, name):
for i in range(len(ls)):
if (ls[i].name == name):
return i
def sale(self):
n = int(input("How many products to sale: "))
total = 0
for j in range(n):
name = input("Enter Product name : ")
quantity = int(input("Enter quantity: "))
i = obj.check_item(name)
if i and ls[i].quantity >= quantity:
ls[i].quantity -= quantity
if ls[i].quantity < 5:
print("Low Stock! Low Stock! Order Placed")
obj.place_order(name, ls[i].supplier, quantity+10)
print("....Uncle G Shop....")
print(datetime.date.today())
print("Product Name | Quantity | Cost $")
print(ls[i].name, end=" ")
print(quantity, end=" ")
print(ls[i].price * quantity)
total += ls[i].price * quantity
print("\n")
print("Total Cost----->", "$" + total)
else:
print("Product out of stock or not enough quantity")
def purchase(self):
name = input("Enter Product name: ")
date = datetime.date.today()
i = obj.check_item(name)
if i:
ls[i].quantity += int(input("Enter quantity: "))
ls[i].price = int(input("Enter product price: "))
ls[i].date = date
else:
quantity = int(input("Enter quantity: "))
price = int(input("Enter product price: "))
supplier = input("Enter Supplier: ")
ob = Stock(name, price, supplier, quantity, date)
ls.append(ob)
def place_order(self,name, supplier, quantity):
return name, supplier, quantity
def print_products(self):
def __repr__(self):
return str(self.name) + str(self.price) + str(supplier) + str(self.quantity) + str(self.date)
return __repr__
def main(self):
print("Welcome To Uncle G Shop")
print("choose an option below")
print("\n1.Enter a Product\n2.Make a sale \n3.See all Products\n4.Exit")
option = int(input("Enter option here: "))
while True:
if option == 1:
obj.purchase()
elif option == 2:
obj.sale()
elif option == 3:
obj.print_products()
elif option == 4:
print("Have a good day")
break
else:
print("Enter a valid input!")
# A list to add Products
ls = []
# an object of Stock class
obj = Stock('', 0, 0, 0, '')
obj.main()
Your main menu doesn't have a break from the while loop for option 4.
You also need to think again about how to use your class. At present, you have multiple methods referring to a variable, ls, created outside of the class. Either treat Stock as a class to deal with individual purchase records, or to deal with stock overall. You could maintain in the class itself a list of instances of the class and offer class methods, as well as instance methods, to manage that overall stock.
so I am trying to learn python and have a csv file like this
1 product_id product_name price
2 1001 cake 15
3 1002 sprite 30
4 1003 coffee 50
5 1004 ice cream 30
6 1005 banana 10
my program is
import csv
productid=input("Enter the product ID: ")
quantity=int(input("Enter the quantity: "))
csv_file=csv.reader(open("shoppinglist.csv", "r"),delimiter=",")
for row in csv_file:
if productid==row[0]:
product_id=row[0]
product_name=row[1]
product_price=row[2]
print("\nProduct ID: {}".format(row[0]))
print("Product Name: {}".format(row[1]))
print("Product Price: {}".format(row[2]))
total=quantity*(int(product_price))
print("\nThe Total Amount Payable is: {}".format(total))
I can enter one productid at a time and get the output but i am looking for a way so that i can enter multiple productid's ad they get searched in the csv file and then the total is calculated and all the product details output.
PS: I have tried to explain my problem as best as i can but if i have made any mistake please be kind to point it out to me
my output is
Enter the product ID: 1001 Enter the quantity: 5
Product ID: 1001 Product Name: cake Product Price: 15
The Total Amount Payable is: 75
i just do not want to print the product but to search for its id in the csv file and if it exits ask the user to input the quantity for every productid entered and then print the details of the products along with the total amount.
You Need a Loop to look around to your product each time you offered a product Id
I Hope You Understand the following code.
# Author Name : Sandip Sadhukhan
import csv
def findProduct(productId):
csv_file = csv.reader(open('shoppinglist.csv', 'r'), delimiter=',')
productPrice = 0
productName = ''
isFound = False
for row in csv_file:
if productId == row[0]:
productName = row[1]
productPrice = row[2]
isFound = True
break
result = {
'isFound': isFound,
'productName': productName,
'productPrice': productPrice,
'productId': productId
}
return result
total = 0
printList = []
while(True):
productid = input("Enter a product Id: ")
result = findProduct(productid)
if not(result['isFound']):
print("Product is not found...")
continue
quantity = int(input("Enter the quantity: "))
if(quantity <= 0):
print("Please select atleast 1 quantity.")
continue
total += quantity * (int(result['productPrice']))
temp = [result['productName'], quantity, result['productPrice']]
printList.append(temp)
addMore = input("Add more Items? (Y/N) : ")
if(addMore.lower() == 'n'):
break
print("\nBill\n====\n\n[Product Name] [Product Price] [Quantity]")
for item in printList:
print("{} {} {}".format(item[0], item[2], item[1]))
print("The total Amount payable is : {}".format(total))
You can just parse your input to be the way you want. For example,
def product(id): # given product id, returns price, 0 if item does not exist
# your code goes here
id = input("Enter your product ids separated by spaces: ") # For e.g. 2 3 1
id = id.split(" ")
total = 0
for i in id:
price = product(id)
if price != 0:
quantity = print("Enter quantity of " + str(id) + ": ")
total += quantity*price
print("The total price is: " + price)
This code parses the ids so they are in an array. It then goes through each id in the array and performs your code.
You should really look into pandas, it's going to make all these kinds of operations much simpler.
I have the following code:
shoppingList = ["banana","orange","apple"]
inventory = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def calculateBill(food):
total = 0
for k in food:
total += prices[k]
return total
calculateBill(shoppingList)
The exercise tells me to complete the function following these instructions:
Don't add the price of an article in your bill if it is not in your inventory.
After you buy an article, substract one from the inventory.
I don't know how to do it and I don't know if I have any other mistakes in my code.
If it isn't clear, the value in inventory is the stock of that item, and the value in "prices" is the price.
First of all, I don't see comida defined anywhere before its use. I'll assume that by comida, you mean food.
Here is a simple solution:
def calculateBill(food):
total = 0
for k in food:
if inventory.get(k, 0) > 0:
total += prices[k] # updates total
inventory[k] = inventory[k] - 1 # updates inventory
return total
You could do the following
def calculateBill(food):
total = 0
for k in food:
if k in inventory:
if inventory[k] > 0:
total += prices[k]
inventory[k] = inventory[k] - 1
else:
print 'There are no %s in stock' % k
else:
print 'dont stock %s' % k
return total
For 1)
if k in inventory:
Will check if the key is present in your inventory dict.
For 2)
inventory[k] = inventory[k] - 1
Will substract 1 from your inventory
One flaw in this code is that it does not check that the inventory count is above 0 before allowing to buy. So
if inventory[k] > 0:
Does this.
Here's a complete solution.
class Error(Exception):
"""Base class for Exceptions in this module"""
pass
class QtyError(Error):
"""Errors related to the quantity of food products ordered"""
pass
def calculateBill(food):
def buy_item(food_item, qty=1, inv_dict=None, prices_dict=None):
get_price = lambda item,price_dct: price_dct.get(item,9999999)
if inv_dict is None:
inv_dict = inventory
if prices_dict is None:
prices_dict = prices
if inv_dict.get(food_item, 0) >= qty:
inv_dict[food_item] -= qty
return sum(get_price(food_item, prices_dict) for _ in range(qty))
else:
raise QtyError("Cannot purchase item '{0}' of quantity {1}, inventory only contains {2} of '{0}'".format(food_item, qty, inv_dict.get(food_item,0)))
total = sum(buy_item(food_item, 1, inventory, prices) for food_item in food)
return total