Accessing list and adding them total, python solution - python

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))

Related

How to add a currency symbol to my array?

Goal:
Display my list of commission pay with a £ symbol.
Explanation of what the problem is:
When it comes to displaying the result it does not print the whole result instead it just prints the £ symbol.
What I have tried:
As you can see in the code, I have attempted to convert the array into a string (putting it into its own variable) then I added the currency symbol (£) to it and asked for commission2 to be called. However, it does not show.
OUTPUTTED:
Name Id Houses Sold Commission
£1000
ki 2 2 £
(the £1000 is just to show that the data is actually there, but for some reason when printing in the list, it is not displayed...)
OUTPUT DESIRED:
Name Id Houses Sold Commission
ki 2 2 £1000
I've been at it for hours so any help would be greatly appreciated!
Code where the error occurs:
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
My full code:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
names = []
ids = []
num_sold_houses= []
def get_single_employee_info(names, ids, num_sold_houses):
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names, ids, num_sold_houses):
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: £{total_commission}.00 (before bonus)')
print()
bonus = max(commission)
if bonus >= max(commission):
bonus = bonus*0.15
bonus = (int(max(commission)) + bonus)
commission = bonus
print("The person at the top of ranking gets: " + "£" + str(commission)+"0")
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
Change out
commission2 = ''.join(str(e) for e in commission)
to
commission2 = ["£" + str(e) for e in commission]
and remove the line under it. Your ''.join was taking 2 list elements and forcing them into a single string, which is not what you want for this logic. You want a list output for the commission2 variable so we create a list and append the stringified values to it along with the currency symbol.
Output:
Name Id Houses Sold Commission
Kevin 1 3 £1500
Stacey 2 5 £2500
Total Commission: £4000.00 (before bonus)
The person at the top of ranking gets: £2875.00
Ranking:
Stacey - 5
Kevin - 3

How can I find multiple strings in a csv file

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.

Adding and sorting elements of multidimensional list in a certain way

I am working on this
class Product:
def __init__(self, date=0, product_name=0,qty=0,supplier=0):
self.product_name = product_name
self.date = date
self.qty = qty
self.supplier= supplier
self.my_list = []
def purchase(self, date, product_name, qty, supplier_name ):
self.my_list.append([supplier_name,date,product_name,qty])
def calculation(self):
for i in self.my_list:
print(i)
choice=None
p=Product()
while True:
choice=int(input("1 for the add record\n2 For the display result.\n"))
if choice == 1:
product_name=input("Enter the product name\n")
qty = int(input("Enter the qty.\n"))
date= input("Enter the date")
supplier_name = input("Enter the supplier name.\n ")
p.purchase(date,product_name,qty, supplier_name)
elif choice == 2:
p.calculation()
after executing this i have added data like this... when we choose 2 number option i am having data like this
eg.[supplier_name, date, product_name, quantity]
[supplierA, 2019-01-01, pencil, 20]
[supplierA, 2019-01-01, pencil, 30]
[supplierA, 2018-02-02, pen, 20]
[supplierB, 2017-02-02, scale, 10]
[supplierB, 2017-10-10, scale, 20]
[supplierC, 2019-01-01, pencil,10]
[supplierC, 2019-01-01, pencil,10]
[supplierC, 2019-01-01, pencil,10]
I want to filter this data in a way that if date and product name are same, its quantity should be added. and it must be group by supplier name .I means only individual supplier's date and qty be added in
expected output is
Supplier A:
[2019-01-01, pencil, 50]
[2018-02-02, pen, 20]
Supplier B:
[2017-02-02, scale, 10]
[2017-10-10, scale, 20]
Supplier C:
[2019-01-01, pencil, 30]
i have tried with lambda and filter but could not able to make it. any idea how to make it possible?
this will work i think:
class Product:
#init
def __init__(self, date=0, product_name=0,qty=0,supplier=0):
self.product_name = product_name
self.date = date
self.qty = qty
self.supplier= supplier
#make self.my_dict
self.my_dict={}
def purchase(self, date, product_name, qty, supplier_name ):
#make a new key if needing
try:
#add the data to the list
self.my_dict[supplier_name].append([date,product_name,qty])
except:
#make a new list with data
self.my_dict[supplier_name] = [[date,product_name,qty]]
def calculation(self):
#getting keys
for i in list(self.my_dict):
#print key
print(i)
#get items
for k in self.my_dict[i]:
#print item
print(k)
choice=None
p=Product()
while True:
choice=int(input("1 for the add record\n2 For the display result.\n"))
if choice == 1:
product_name=input("Enter the product name\n")
qty = int(input("Enter the qty.\n"))
date= input("Enter the date")
supplier_name = input("Enter the supplier name.\n ")
p.purchase(date,product_name,qty, supplier_name)
elif choice == 2:
p.calculation()
you can also modify existing purchase method :
def purchase(self, date, product_name, qty, supplier_name ):
for item in self.my_list:
if item[2] == product_name and item[1] == date and item[0] == supplier_name:
item[3] = item[3] + qty
return
self.my_list.append([supplier_name,date,product_name,qty])
You could do this:
from itertools import groupby
from operator import itemgetter
def calculation(self):
# sort and group items by supplier_name, date, product_name
x = groupby(sorted(self.my_list, key=itemgetter(slice(None, 3))), itemgetter(slice(None, 3)))
# sum the quantities
y = [i + [sum(map(itemgetter(3), j))] for i, j in x]
# group items by supplier
z = [(i, list(map(itemgetter(slice(1, None)), j))) for i, j in groupby(y, itemgetter(0))]
# output
for supplier, values in z:
print("{0}:".format(supplier))
print("\n".join(map(str, values)))

How to modify the value for a key in a dictionary?

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

in python OOP How to print a list of objects with attributes and add the total of the price of each product

I'm a really begginer with python and OOP, I want to print a list of 3 objects with 3 properties each, one of the properties is the price and I want that in the end these three prices add up to give me the total money that cost the 3 products.
Here's my code:
from products import PhysicalProduct
class Checkout:
def get_total(self, product_list):
total = 0
for product in product_list:
total += product.price
return total
def print_list(self, product_list):
#print products with sku, price and the total
pass
checkout = Checkout()
product_list = [
#The properties are: "name", "sku", price
PhysicalProduct("television", "100", 100),
PhysicalProduct("radio", "101", 80),
PhysicalProduct("computer", "105", 1080),
]
print(checkout.get_total(product_list))
It should look something like this:
television: sku: 100 price: 100
radio: sku: 101 price: 80
computer: sku: 105 price 1080
total: 1260
Use the following print_list method declaration:
def print_list(self, product_list):
for product in product_list:
print(product.name, 'sku: {:0} price: {:1}'.format(product.sku, product.price))
print('total:', self.get_total(product_list))
Try this:
for product in product_list:
print(product.name +': sku: '+product.sku+' price: '+product.price)
print('total: ' + str(checkout.get_total(product_list)))
this should do the requested
Shouldn't be hard. You may not even need that second function in there but, if you want to have it, then you could do something like this:
class Checkout:
def get_total(self, product_list):
total = 0
for product in product_list:
total += product.price
return total
def print_list(self, product_list, total):
#print products with sku, price and the total
for item in product_list:
print(item.name + ": sku: " + item.sku + " price: " + str(item.price), end="")
print()
print("total: " + str(total))
checkout = Checkout()
product_list = [
#The properties are: "name", "sku", price
PhysicalProduct("television", "100", 100),
PhysicalProduct("radio", "101", 80),
PhysicalProduct("computer", "105", 1080),
]
total = checkout.get_total(product_list)
checkout.print_list(product_list, total)

Categories

Resources