Posts: 27
Threads: 4
Joined: May 2018
May-29-2018, 01:55 PM
(This post was last modified: May-29-2018, 01:56 PM by Leonzxd.)
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:
Output: MyShop
Prodcode Quantity Price Amount(RM)
AAA 2 5.00 10.00
DDD 4 1.70 6.80
EEE 1 9.00 9.00
Total amount: 25.80
Posts: 12,031
Threads: 485
Joined: Sep 2016
May-29-2018, 05:50 PM
(This post was last modified: May-29-2018, 05:50 PM by Larz60+.)
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()
Posts: 27
Threads: 4
Joined: May 2018
(May-29-2018, 05:50 PM)Larz60+ Wrote: 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()
Wow, this is more than I expected.
Thanks!
I will try understand each rows of codes.
Posts: 27
Threads: 4
Joined: May 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:
Output: Enter ProdCode (x to exit): bbb
Enter Quantity: 2
Enter ProdCode (x to exit): ddd
Enter Quantity: 4
Enter ProdCode (x to exit): eee
Enter Quantity: 1
Enter ProdCode (x to exit): x
My Shop
ProdCode Quantity Price Amount (RM)
BBB 2 7.00 14.00
Total amount (RM): 14.00
Why am I printing one item only although I inputted 3 items?
HELP!
THANKS AGAIN
Posts: 12,031
Threads: 485
Joined: Sep 2016
Jun-22-2018, 06:08 PM
(This post was last modified: Jun-22-2018, 06:08 PM by Larz60+.)
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.
Posts: 27
Threads: 4
Joined: May 2018
Jun-23-2018, 05:52 AM
(This post was last modified: Jun-23-2018, 05:52 AM by Leonzxd.)
(Jun-22-2018, 06:08 PM)Larz60+ Wrote: 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 entered, it's added to a list. After you have entered the last item, the list is printed.
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***
Posts: 2,953
Threads: 48
Joined: Sep 2016
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)) Output: My table
col_1 col_2 col_3 col_4
----------------------------------------
5717 3373 9148 2651
95 1318 7566 2413
There are 8 elements in the table.
Posts: 27
Threads: 4
Joined: May 2018
Jun-23-2018, 07:50 AM
(This post was last modified: Jun-23-2018, 08:00 AM by Leonzxd.)
(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.
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)) Output: My table
col_1 col_2 col_3 col_4
----------------------------------------
5717 3373 9148 2651
95 1318 7566 2413
There are 8 elements in the table.
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...
Output: Product code (x to exit): aaa
Enter Quantity: 2
Product code (x to exit): x
MyShop
Prodcode Quantity Price Amount(RM)
AAA 1 5.00 5.00
Total: $5.00
None
May I know why?
Posts: 2,953
Threads: 48
Joined: Sep 2016
Jun-23-2018, 10:37 AM
(This post was last modified: Jun-23-2018, 10:38 AM by wavic.)
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.
Posts: 27
Threads: 4
Joined: May 2018
(Jun-23-2018, 10:37 AM)wavic Wrote: 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.
Thankssssssssssss!!
If any new people to python. could refers this website!
Reference: https://www.webucator.com/blog/2015/03/u...-variable/
|