I wanted to make a reciept that prints out in the format names:prices however its seems super hard considering I would have to loop thourugh both lists can someone help me find an solution
class CashRegister:
def __init__(self,names,prices):
self._itemCount = 0
self._totalPrice = 0.0
self._names = [names]
self._prices = [prices]
def addItem(self, names,prices):
self._names = [names]
self._prices = [prices]
def getTotal(self):
self._totalPrice = sum(self._prices)
return self._totalPrice
def getCount(self):
count = 0
for i in self._prices:
count = count 1
self._itemCount = count
def clear(self):
self._itemCount = 0
self._totalPrice = 0.0
def updatetax(self,tax):
if 1 <= tax <= 20:
self._tax_percent = tax
else: self._tax_percent = 0
def get_total_tax(self):
return self._totalPrice * self._tax_percent
def reciept(self):
# use the lists ( name and prices)
CodePudding user response:
Assuming names and prices are the same length:
for pos in range(len(names)):
print(names[pos], prices[pos])
CodePudding user response:
Since the length of "self._names" is equal to the length of "self._prices", we can use the zip function to get a generator. For example, we can "zip" together these lists to get a list of tuples:
print(list(zip([1, 2, 3], [4, 5, 6])))
We will get the following output:
[(1, 4), (2, 5), (3, 6)]
Using this function, we can write this code:
def reciept(self):
# zip together the lists and convert generator to list
zipped_up = list(zip(self._names, self._prices))
# loop through and print
for set_of_values in zipped_up:
print(f"{set_of_values[0]}: {set_of_values[1]}")
Just so you know, in the "init" function, you wrote:
self._names = [names]
self._prices = [prices]
This would have made a list of lists, which you probably didn't want, so instead you could use the asterisk operand to unpack them as:
self._names = [*names]
self._prices = [*prices]