Reputation: 33
I'm quite new to programming.
My problem is that my if statement is getting an IndexError. So I put my if statement into another cell and tried it with a different list and it works fine. What did I do wrong?
from datetime import datetime
import math
def GroceryReceipt():
grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3], ["beef", 8]]
amountGroceries = int(input("Input the amount of food you wish to buy: "))
userGroc = []
for i in range(amountGroceries):
buyGroceries = input("Pick some foods: ")
userGroc.append(buyGroceries)
for j in range(len(grocery)):
if(len(userGroc) < j):
break
else:
print("$",grocery[j][1])
if(userGroc[j] in grocery[j][0]):
add = grocery[j][1] + grocery[j][1]
tax = math.pi/100 * add
total = tax + add
round(total, 2)
x = datetime.today()
print(total, x)
GroceryReceipt()
Upvotes: 3
Views: 2094
Reputation: 2747
A big challenge when starting out as a programmer is figuring out how to split a program up to reduce complexity at any given point in the code. Another challenge is choosing the right data structures to make your task easier. Here is another way to imagine solving your problem taking those concerns into account
Example:
from datetime import datetime
import math
in_stock = {
"bread": 3.0,
"eggs": 3.0,
"soda": 7.0,
"chips": 3.0,
"beef": 8.0
}
def select_stock_item():
stock_string = ", ".join([key for key in in_stock])
while True:
item = input(
f"Please choose an item from available stock\n[{stock_string}]: "
).casefold()
if not item in in_stock:
print(f"I'm sorry, that item is not in stock.")
continue
return item, in_stock[item]
def grocery_session():
purchase_qty = int(input("How many items will you be purchasing today? "))
purchases = []
for _ in range(purchase_qty):
purchases.append(select_stock_item())
for one_purchase in purchases:
purchase_subtotal = sum(one_purchase[1] for one_purchase in purchases)
tax_on_purchase = purchase_subtotal * math.pi / 100
purchase_total = purchase_subtotal + tax_on_purchase
date_and_time = datetime.today().strftime("%m/%d/%y %H:%M")
print("Thank you for your purchases.")
print(f"You spent a total of ${round(purchase_total, 2)} on {date_and_time}")
print("Please come again.")
grocery_session()
Output:
How many items will you be purchasing today? 3
Please choose an item from available stock
[bread, eggs, soda, chips, beef]: soap
I'm sorry, that item is not in stock.
Please choose an item from available stock
[bread, eggs, soda, chips, beef]: bread
Please choose an item from available stock
[bread, eggs, soda, chips, beef]: eggs
Please choose an item from available stock
[bread, eggs, soda, chips, beef]: soda
Thank you for your purchases.
You spent a total of $13.41 on 03/20/21 15:55
Please come again.
Upvotes: 0
Reputation: 200
use the 'else' command like this:
from datetime import datetime
import math
def GroceryReceipt():
grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3]], ["beef", 8]
amountGroceries = int(input("Input the amount of food you wish to buy: "))
userGroc = []
for i in range(amountGroceries):
buyGroceries = input("Pick some foods: ")
userGroc.append(buyGroceries)
for j in range(len(grocery)):
if(len(userGroc) < j):
break
else: # Use 'else' here
print("$3")
GroceryReceipt()
your 'if' statement breaks the loop if the length of userGroc < j; but even though it breaks the loop the other 'if' statement will be executed, and the index error will occur. so its better to use and 'else' statements,
the else statement will be executed only if the 'if' statement doesn't meet the requirements, otherwise both of the 'if' statements will be executed.
Upvotes: 1
Reputation:
In grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3], ["beef", 8]
you forgot to add another "]". If you add it, it should work well enough.
Upvotes: 0