I have a problem.
I wanna add the same record but the old one will be replaced by a new one! I want both of them exist so I can see what I've done.
How do I solve the problem? Please help me!
Thank you!
my code:
initial_money = int(input('How much money do you have? '))
mr={}
add_mr={}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global mr
global rec
rec = records[0]
global amt
amt = records[1]
for r, a in mr.items():
i = 0
while (r, i) in add_mr:
i += 1
add_mr[(r, i)] = a
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
The output:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tree 87
Now you have 1174 dollars.
Output I want:
------------------- ------
tree 87
tree 87
Instead of using a dictonary such that Mr = {"ewq": 87} you could instead use a list of all of them such that Mr = [("ewq", 87), ("ewq", 87)]
This would make it so that if you have a duplicate it won't overwrite. As dictionaries can only have one per key
Edit: You would do this by replacing the first part that says mr = {} with mr = [] and then whenever you call addmr you can instead just use mr.append(value) which will add the value to the list
You actually can do this with a dict. In stead of one item per key use one list per key.
if rec not in mr:
mr[rec] = []
mr[rec].append(amt)
Such that mr = {"ewq": [87, 87]}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want to ask the user if they are members and if so, give them a 5% discount on the seats they have purchased, if they are not members, there is no discount. I also want to display that discounted price. Also, how would I go about adding up all the final prices and displaying those as well? I don't know where to start with this, any help is appreciated, thanks. There may be some formatting issues, but here is my code:
def main():
print("Your final price for Orchestra seats will be $",get_orchp())
print("Your final price for Center seats will be $",get_centerp())
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
elif member == 'n':
print('There is no discount for non-members')
return Finalorchp
return findiscorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
This is how I would resolve all of your questions:
def main():
orchp = get_orchp()
centerp = get_centerp()
print(f"Your final price for Orchestra seats will be ${orchp}")
print(f"Your final price for Center seats will be ${centerp}")
print(f'Your final price for all tickets is {orchp + centerp}')
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
Finalorchp *= .95
return Finalorchp
else:
print('There is no discount for non-members')
return Finalorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
Please note these
I change the location of the calls to your functions and set a variable to receive them
I changed the prints for the final price to an f string to receive the variables from the functions
Changed Finalorchp to the pythonic version of variable = variable * .95 right under the if member statement
Changed the else statement in get_orchp to else in the event that the user doesn't only put y or n (you could add onto this to have fault tolerance of if it isn't y or n then do something else)
Added another final price print with an f string to add the two variables that receive the 2 variables from the functions.
This code does what you want.
you can see that in the code I have returned both price and discount amount from the getorchp() function as a tuple and using which I have printed the actual price and discount in the main function. If the user is not a member the discount will be zero and in the main function, I have added both orchestra seats and center seat price and printed the total final price. This code answers all questions you have asked
def main():
orc = get_orchp()
print("Your final price for Orchestra seats will be $",orc[0], " and discount is ", orc[1])
cen = get_centerp()
print("Your final price for Center seats will be $",cen)
print("total final price", orc[0]+cen)
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
return (Findiscorchp, disc)
elif member == 'n':
print('There is no discount for non-members')
return (Finalorchp, 0)
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
I am coding a program that simulates someone making a purchase in a grocery store. I am displaying all the products and the price and I am prompting the user to input all the products they went to buy separated by commas. I want the program to check if the input is in the dictionary of product and add it to the cart with the use of a loop. Before adding it to cart the program needs to check if the input is valid, meaning if the item is in the list of products to buy. When the user selects an item to buy, I want the program to ask the user for the quantity of that item, so how many of the item they want to buy. At the samThen the program will calculate the total of all the products, then calculate the tax value, 24% of the total, and then return a subtotal that includes tax. Here is what I have so far:
def calculatetotal(slist, produce):
# for each item on the shoping list look up the cost & calculate total price
item_price = 0
subtotal = 0
VAT = 0
final_total = 0
basket = {}
for item in slist:
item_price = produce.get(item)
basket[item] = item_price
subtotal = subtotal + item_price
basket["Subtotal"] = subtotal
#calculating VAT
VAT = subtotal * 0.24
basket["VAT"] = VAT
#calculating price with tax
final_total = subtotal + VAT
basket["Total"] = final_total
# print off results
return basket
def main():
# set up grocery list with prices
produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
# process input from the user - get a shopping list
item = input("Please enter the items that you want to buy: ")
slist = []
while(item != 'stop'):
if not (item in slist):
slist.append(item)
item = input("Please enter the items that you want to buy: ")
result = calculatetotal(slist, produce)
print(result)
main()
I've gotten most of it, but the small changes that I mentioned above, I can't figure out what to do. I forgot to mention that asking for the quantity of the item and checking if the user input has to be done with a loop. Any input is very much appreciated. Please show the change of code. Thank you in advance.
In this case I would simply go for a while loop
while True:
item = input("Please enter the items that you want to buy: ")
if item == 'Stop':
break
elif item not in produce or item in slist:
# error message or whatever
else:
num = int(input("Enter Quantity"))
# other operations
I need to create a function that creates a session that accepts a "clerk's" input data about a customer's orders until the "clerk" enters the string "/". Each line of input consists of two elements: the product code and the quantity. Lines of input are formatted as follows: "{product_code},{quantity}". The function should write a file called receipt.txt that prints a summarized report of the session.
The receipt should provide a summary of all the orders made during the session and the product must only appear once if it has been ordered at least once during the session, even if it has been ordered multiple times. In other words, if a product is ordered multiple times, then it should only have one entry in the receipt that describes the sum of all of the orders made for that product. The products must appear in alphabetical order.
Here is my code right now and it prints a receipt but I don't know how to make the order appear only once and make it alphabetical order. Please help.
EDIT: Added get_property function.
def get_property(code,property):
return products[code][property]
def main():
products = {
"americano":{"name":"Americano","price":150.00},
"brewedcoffee":{"name":"Brewed Coffee","price":110.00},
"cappuccino":{"name":"Cappuccino","price":170.00},
"dalgona":{"name":"Dalgona","price":170.00},
"espresso":{"name":"Espresso","price":140.00},
"frappuccino":{"name":"Frappuccino","price":170.00},
}
orders_list = []
total = 0
while(True):
customer_order = input("Welcome to the CoffeePython POS Terminal.\nPlease enter the Product Code and the Quantity in this format - {Product Code},{Quantity}.\nEnter '/' to quit.\n")
if customer_order == "/":
break
else:
code_quantity_list = customer_order.split(",")
code = code_quantity_list[0]
quantity = code_quantity_list[1]
quantity_int = int(quantity)
if code in products:
subtotal = get_property(code,"price")*quantity_int
total += subtotal
ordered_item = dict([
('code', code),
('qty', quantity_int),
('subtotal', subtotal)
])
orders_list.append(ordered_item)
else:
print("The Product Code that you entered is invalid. Please try again.")
print("==")
print("CODE\t\t\tNAME\t\t\tQUANTITY\t\t\tSUBTOTAL")
for order in orders_list:
order_code = order['code']
order_name = products[order_code]["name"]
order_qty = order['qty']
order_subtotal = order['subtotal']
print(f"{order_code}\t\t{order_name}\t\t{order_qty}\t\t\t\t{order_subtotal}\t\t")
print(f"\nTotal:\t\t\t\t\t\t\t\t\t\t{total}")
print("==")
print("Thank you for ordering. Goodbye.")
main()
Output
==
CODE NAME QUANTITY SUBTOTAL
americano Americano 2 300.0
americano Americano 2 300.0
Total: 600.0
==
To store the orders, I would suggest you to use a dictionary with code as a key, and the price as value.
orders_list = {}
while ...:
orders_list[code] = orders_list.setdefault(code, 0) + subtotal
for product in sorted(orders_list):
subtotal = orders_list[product]
print(f"{product:<10} {subtotal}")
You need to check the saved list in orders_list and then evaluate the existing key. For sort list in the order_list by key in a dict, you can use this reference
How do I sort a list of dictionaries by a value of the dictionary?
I am adding a new method to perform check.
Also, I am not sure about your get_property() method, I changed it a bit.
def check_code(orders_list, code):
codes = []
for i in orders_list:
codes.append(i["code"])
if(code in codes):
return True, codes.index(code)
else:
return False, 0
def main():
products = {
"americano":{"name":"Americano","price":150.00},
"brewedcoffee":{"name":"Brewed Coffee","price":110.00},
"cappuccino":{"name":"Cappuccino","price":170.00},
"dalgona":{"name":"Dalgona","price":170.00},
"espresso":{"name":"Espresso","price":140.00},
"frappuccino":{"name":"Frappuccino","price":170.00},
}
orders_list = []
total = 0
while(True):
customer_order = input("Welcome to the CoffeePython POS Terminal.\nPlease enter the Product Code and the Quantity in this format - {Product Code},{Quantity}.\nEnter '/' to quit.\n")
if customer_order == "/":
break
else:
code_quantity_list = customer_order.split(",")
code = code_quantity_list[0]
quantity = code_quantity_list[1]
quantity_int = int(quantity)
if code in products:
# subtotal = get_property(code,"price")*quantity_int
subtotal = products[code]["price"] *quantity_int
check = check_code(orders_list, code)
if check[0]:
orders_list[check[1]]["subtotal"] += subtotal
orders_list[check[1]]["qty"] += quantity_int
else:
ordered_item = dict([
('code', code),
('qty', quantity_int),
('subtotal', subtotal)
])
orders_list.append(ordered_item)
total += subtotal
else:
print("The Product Code that you entered is invalid. Please try again.")
print("==")
print("CODE\t\t\tNAME\t\t\tQUANTITY\t\t\tSUBTOTAL")
orders_list = sorted(orders_list, key=lambda k: k['code'])
for order in orders_list:
order_code = order['code']
order_name = products[order_code]["name"]
order_qty = order['qty']
order_subtotal = order['subtotal']
print(f"{order_code}\t\t{order_name}\t\t{order_qty}\t\t\t\t{order_subtotal}\t\t")
print(f"\nTotal:\t\t\t\t\t\t\t\t\t\t{total}")
print("==")
print("Thank you for ordering. Goodbye.")
main()
When i test the code the item prints once and i did following:
frappuccino, 1
americano, 2
dalgona, 1
So i cannot reproduce the issue but i dont have the get_properties method either so maybe thats the issue.
As for printing the list in alphabetical order you should look to sort the list before looping and printing the reciept. You will find how you can achieve sort on a list containing dictionaries
here
I have a problem.
I want to display all my records in "view" command, but it only displays the last record.
How do I solve the problem?
Please help me , thank you!
my code:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global initial_money
initial_money += int(amt)
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
print('{name:<20s} {number:<6s}'.format(name = rec,number = amt))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Output
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
salary 100
Now you have 150 dollars.
output I want:
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
I will use a dictionary to hold them instead:
initial_money = int(input('How much money do you have? '))
mr = {}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global mr
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Test:
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
You need to make records into a list of the records you inserted. Currently you are overwriting it each time you call add.
make records an array outside your main loop
In your main loop push the results of the call to add into your array In your view function
you then need to loop over the array to view all the results.
Also for bonus, stop using global in your add function, It's considered bad form
First of all, I'm a newbie to Python. I'm just practicing.
I have made users to input a certain data into the memory by using append.
store = []
def inputData():
name = input("Name: ")
amount = input("Amount: ")
date = input("Data: ")
store.append({'name':name, 'amount':amount, 'date':date})
I want to let users be able to search the data stored in the memory.
Any hints would be really appreciated.
======================================
Here is my output code
def outputData():
print("="*30)
print("Name / Amount / Date")
print("="*30)
for d in store:
print("%(name)s %(amount)s %(date)s"%d)
def outputData(data):
print("="*30)
print("Name / Amount / Date")
print("="*30)
for person in data:
print("{name} {amount} {date}".format(**person))
Where 'data' is the dictionary where you store the values.