Reputation: 95
I am running a program where it prompts the user to enter the number of items at an "express" checkout line. It then requests the price and quantity of the items from the user and prints a subtotal. Once all the items that the user enters are accounted for the program displays the TOTAL of all the subtotals. I've gotten all the way to the very last part where I need to add up the user's subtotals. Any help would be appreciated,
def main():
total = 0
while True:
item = int(input("How many different items are you buying? "))
if item in range (1, 10):
total += subtotal(item)
print("Total of this order $", format (total, ',.2f'), sep='')
break
else:
print("***Invalid number of items, please use a regular checkout line***")
break
def subtotal(item):
total = 0
for item in range(item):
unit_price = float(input("Enter the unit price of the item "))
quantity = int(input("Enter the item quantity "))
subtotal = unit_price * quantity
print("Subtotal for this item: $", format (subtotal, ',.2f'), sep='')
return subtotal
main()
Upvotes: 1
Views: 370
Reputation: 33345
The subtotal()
function reassigns the subtotal every time through the loop, discarding the previous value, so it ends up returning only the total for the last item.
Try this instead:
def subtotal(item):
total = 0
for item in range(item):
unit_price = float(input("Enter the unit price of the item "))
quantity = int(input("Enter the item quantity "))
subtotal = unit_price * quantity
print("Subtotal for this item: $", format (subtotal, ',.2f'), sep='')
total += subtotal
return total
Upvotes: 2
Reputation: 26
Your code has a big amount of errors.
You don't put spaces between function names and args. It makes a big amount of mistakes.
The correct way of use formatting is: 'string {0}'.format(variable_name)
Why you are putting the whole script into a 'main' function? This isn't C. But if you are comfy with this, ok so.
But answering the question, you can make the 'subtotal' function receive a list of products and make it return a list of the subtotal and make the rest of the mathy part in the 'main' function.
Upvotes: 0