# Function to write Shop Receipt – Python

## Issue

Struggling to write a function to print a ‘cashier receipt’ output for a shop
It should accept 3 items, then sum them up and print out a detailed receipt with TOTAL.

``````def reciept(Item_1_name, Item_2_name, Item_3_name):
Item_1_price = 50.45
Item_2_price = 12
Item_3_price = 80.55
total = 'Total', Item_1_price + Item_2_price + Item_3_price
return Item_1_name, Item_1_price, Item_2_name, Item_2_price, Item_3_name, Item_3_price, total

reciept("Trainers", "T-Shirt", "Boots")
``````

My answer produces the output but not in the format I am looking for. This question is a basic question but I think I am getting confused. Can anyone help me understand where I am going wrong?

## Solution

Here is a proposal. First, you have to define prices for your items. You can achieve it via a dictionary

``````item_prices = {
"Trainers": 50.45,
"T-Shirt": 12,
"Boots": 80.55,
# Add any other item here
}
``````

Then, in your function, you have to retrieve the prices of the selected items. The idea is to have an undefined number of `items`, instead of having just 3

``````total_price = sum(item_prices[item] for item in items)
``````

Finally, you’d build your string, by using `\n` to create a new line and `\t` to insert blank spaces. Eventually, if you care about positioning numbers one below the others and you have items of very different length, you may pad your string with white spaces.

Here the full code (I used a `for` loop to make the computations explicit, but you may also use list comprehensions or other methods):

``````item_prices = {
"Trainers": 50.45,
"T-Shirt": 12,
"Boots": 80.55,
# Add any other item here
}

def receipt(*items):
# Create our output variables and other useful variables
total_price = 0
total_string = "TOTAL"
output_string = ""
max_item_length = max(len(item) for item in items) + 5

# Build our outputs by iterating over items
for item in items:
current_item_price = item_prices[item]  # get price
total_price += current_item_price  # sum to total
output_string += item + (' ' * (max_item_length - len(item))) + \
str(current_item_price) + '\n'  # add to output string, ensuring a fixed number of characters before price

# Add total price, still maintaining a fixed number of chars before price
output_string += total_string + (' ' * (max_item_length - len(total_string))) + str(total_price)

return output_string

print(receipt("Trainers", "T-Shirt", "Boots"))

# Prints:
#
# Trainers     50.45
# T-Shirt      12
# Boots        80.55
# TOTAL        143.0
``````

Note that `*items` is used here to get an undefinide number of arguments to the input of our function