Improve this code (Receipt alike) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Improve this code (Receipt alike) (/thread-10637.html) Pages:
1
2
|
Improve this code (Receipt alike) - Leonzxd - May-29-2018 This is another question I got. It given a lists of items and price tags of them. It wanted to print out a receipt. However, I couldn't one shot print all at once... Is there any code possible to store the Inputs then print ALL at once in a proper table (Or receipt)? This is so far I managed to do: prodcodes = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'] price = [5.00, 7.00, 2.30, 1.70, 9.00, 10.50] n = len(prodcodes) print("\n\t\t\t\t\t\t\t\tMyShop\n\n\t\t\t\tProdcode\tQuantity\tPrice\tAmount(RM)") sum = 0 for i in range(n): line = str(input("Enter ProdCode (x to exit): ")) line = line.upper() if line == 'X': break eqty = int(input("Enter Quantity: ")) for i in range(n): if line == prodcodes[i]: amount = eqty * price[i] print("\n\t\t\t\t\t{0}\t\t{1}\t{2:.2f}\t{3:.2f}".format(prodcodes[i],eqty,price[i],amount)) sum = sum + amount print("\n\t\t\t\t\tTotal amount: {:.2f}".format(sum))Much thanks! This is the output I was hoping for:
RE: Improve this code (Receipt alike) - Larz60+ - May-29-2018 It's better and neater to keep all in functions. This code operation is slightly different from your original, It will continue allowing product and quantity information until you enter a quantity of 0 (or just press enter) and then will print receipt def print_heading(): print('{:^50s}'.format("MyShop")) print('Prodcode Quantity Price Amount(RM)\n') def print_receipt(entry): total = float(entry[1] * entry[2]) print('{:<16}{:<16}{:<8.2f}{:<8.2f}'.format(entry[0], entry[1], entry[2], total)) return total def my_purchases(): prodcodes = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'] prices = [5.00, 7.00, 2.30, 1.70, 9.00, 10.50] prods = [] qty = 1 while qty > 0: qty = (input("Enter Quantity: ")) if qty == '' or qty == '0': break qty = int(qty) prod = input('Product code? ') if prod in prodcodes: price = prices[prodcodes.index(prod.strip())] prods.append([prod, qty, price]) else: print('Invalid product code, try again') print_heading() total = 0 for entry in prods: total += print_receipt(entry) print('Total: ${:<8.2f}'.format(total)) if __name__ == '__main__': my_purchases() RE: Improve this code (Receipt alike) - Leonzxd - Jun-02-2018 (May-29-2018, 05:50 PM)Larz60+ Wrote: It's better and neater to keep all in functions. Wow, this is more than I expected. Thanks! I will try understand each rows of codes. RE: Improve this code (Receipt alike) - Leonzxd - Jun-22-2018 Hi sorry for this long... I could only get like this... prodcodes = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'] price = [5.00, 7.00, 2.30, 1.70, 9.00, 10.50] n = len(prodcodes) sum = 0 for a in range (n): newpcode = [] new_qty = [] newprice = [] amount = [] while True: prod = str(input("Enter ProdCode (x to exit): ")) prod = prod.upper() if prod == 'X': break elif prod in prodcodes: i = prodcodes.index(prod.upper()) #Get corresponding index qty = int(input("Enter Quantity: ")) while qty > 0: if qty == '0': break else: x = qty * price[i] newpcode.append(prod.upper()) new_qty.append(qty) newprice.append(price[i]) amount.append(x) break continue sum = sum + amount[a] print('\n\t\t\tMy Shop') print('\nProdCode\tQuantity\tPrice\tAmount (RM)') print('\n{0}\t\t{1}\t\t{2:.2f}\t {3:.2f}'.format(newpcode[a],new_qty[a],newprice[a],amount[a])) break print("\n\t\tTotal amount (RM): {:.2f}".format(sum))The output: Why am I printing one item only although I inputted 3 items?HELP! THANKS AGAIN RE: Improve this code (Receipt alike) - Larz60+ - Jun-22-2018 Is there a reason why you are avoiding functions? They make writing code so much easier to debug, and if written properly can be used over and over in same project, or new projects. When you have several reusable functions that are related, then it makes sense to containerize them into a class for even more flexibility. Go back and reexamine post 2. After each product is enetred, it's added to a list. After you have entered the last item, the list is printed. RE: Improve this code (Receipt alike) - Leonzxd - Jun-23-2018 (Jun-22-2018, 06:08 PM)Larz60+ Wrote: Is there a reason why you are avoiding functions? I am not really sure how to use function actually and the lecturer did not teach function that much... Your code is cool! But I don't think I could explain to my lecturer how I did it. So, I try to avoid using "function"... But, I would like to enter the ProdCode first then enter the Quantity. Therefore, I change to the simple ones So sorry to disappoint you, sir. Quote:Go back and reexamine post 2. After each product is entered, it's added to a list. After you have entered the last item, the list is printed. So I checked back... My careless mistake sorry. May I ask sir could explain this part? if __name__ == '__main__': my_purchases() That line I couldn't understand. Other codes I could briefly understand. Sorry... def print_heading(): print('{:^50s}'.format("MyShop")) print('Prodcode Quantity Price Amount(RM)\n') def print_receipt(entry): total = float(entry[1] * entry[2]) print('{:<16}{:<16}{:<8.2f}{:<8.2f}'.format(entry[0], entry[1], entry[2], total)) return total def my_purchases(): prodcodes = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'] prices = [5.00, 7.00, 2.30, 1.70, 9.00, 10.50] prods = [] qty = 1 #Why Qty must be 1 and somehow worked? I tried [ ] but it wouldn't work, why? while True: #Loop the inputs for both Prodcode and its Quantity prod = input('Product code (x to exit): ') prod = prod.upper() if prod == '' or prod == 'X': break elif prod in prodcodes: price = prices[prodcodes.index(prod.strip())] #Not too sure for this line, strip away all other numbers except the corressponding index? prods.append([prod, qty, price]) #There is no empty [], where could they append to? else: print('Invalid product code, try again') continue qty = (input("Enter Quantity: ")) if qty == '' or qty == '0': break qty = int(qty) print_heading() total = 0 for entry in prods: total += print_receipt(entry) print('Total: ${:<8.2f}'.format(total)) if __name__ == '__main__': #This code I couldn't understand my_purchases()These comments are the questions... Thank you and sorry once again. PS: Make some changes just for my knowledge ***Big Grin*** RE: Improve this code (Receipt alike) - wavic - Jun-23-2018 You write functions when there is repeated code. So you write it in a function and when you need it again you just call that function. Functions can take parameters and return objects. from random import randint title = 'My table' col_names = ['col_1', 'col_2', 'col_3', 'col_4'] data = [[randint(1,10000) for _ in range(4)] for _ in range(randint(1,10))] # creating the data def prow(seq): row = "{:>10}" * 4 # produces this string "{:>10}{:>10}{:>10}{:>10}" print(row.format(*seq)) def prt_all(title, columns, data): print("{:^40}".format(title)) prow(columns) print("-" * 40) for row in data: prow(row) return 4 * len(data) # returns number of the elements in the table el_num = prt_all(title, col_names, data) # you call the function passing the column names, the data and the table title print("\nThere are {} elements in the table.".format(el_num))
RE: Improve this code (Receipt alike) - Leonzxd - Jun-23-2018 (Jun-23-2018, 07:04 AM)wavic Wrote: You write functions when there is repeated code. So you write it in a function and when you need it again you just call that function. Thanks for the clarification! However, I am still confused with the code... Especially this part: if __name__ == '__main__': #This code I couldn't understand my_purchases() If I change this: if __name__ == '__main__': #This code I couldn't understand my_purchases()To this: print(my_purchases())The output will have a "None" word... May I know why?
RE: Improve this code (Receipt alike) - wavic - Jun-23-2018 Every python script can be imported as a module. When the script is running as a program, Python sets the __name__ variable to contain "__main__". So if the __name__ is equal to "__main__", the next code block is executed. In your case this is 'my_purchases' function, which runs all. If the file is imported as a module that special variable __name__ is set to the module ( imported python file ) name without the extension and the code block after the if statement is not executed. RE: Improve this code (Receipt alike) - Leonzxd - Jun-23-2018 (Jun-23-2018, 10:37 AM)wavic Wrote: Every python script can be imported as a module. Thankssssssssssss!! If any new people to python. could refers this website! Reference: https://www.webucator.com/blog/2015/03/understanding-pythons-__main__-variable/ |