I have the following code:
Full code listing: https://repl.it/JSUN/1
I am looking, for teaching purposes, to obtaining the best method/solution for two things:
Q1. working with currency variables, such as the ones stored in the basket list below
basket=[['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]
In the checkout sub, the intention is to add the COSTS for the corresponding item together.
So if the basket contained the items above, the required output would be £900+£1020+£700 =£2620
I have tried various things like converting to integer, which obviously doesn't work and I imagine that some sort of string manipulation may be the only way forward (which seems unnecessarily complex). A language like VB.Net has a currency data type which would make this task considerably simpler. What would be the pythonic way of solving this?
Q2. For looping through the entire basket to produce all items in the basket on checkout, and not just the first 2
I tried this, which didn't work:
for items in basket:
print("Your total bill is:", basket[items][1])
items=items+1
and this, also erroneous:
for i in len(basket):
print("Your total bill is:", basket[i][1])
Error:
TypeError: 'int' object is not iterable
Both questions are linked, as they both pertain to the checkout() sub, in which the addition of all the currency variables in the basket list is the objective!
Q1:
Given that it is only for a basic teaching purpose, you could just strip out the pound sign (assuming consistent representation):
def extract_cost(money_in_pounds):
return int(money_in_pounds[1:])
basket = [['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]
total_cost = 0
for items in basket:
total_cost = total_cost + extract_cost(items[1])
print(total_cost)
Without writing another function
basket = [['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]
total_cost = 0
for items in basket:
# items[1] selects the cost
# items[1][1:] selects the sub-string of that cost from the 1st index to the end, i.e. remove the currency notation
# int() then converts it into an integer
cost_in_pounds = int(items[1][1:])
total_cost = total_cost + cost_in_pounds
print(total_cost)
More concise code (Suggested by Jon Clements below)
total_cost = sum(int(cost[1:]) for item_name, cost in basket)
Q2:
items
is not the index, it is the content of the list, so items itself is the inner list:
for items in basket:
print("Your total bill is:", items[1])