我创建了一个数据库,用作时令水果/蔬菜列表。我需要使用用户输入搜索该数据库,然后将其附加到一个空列表,然后附加该输入中的价格值,并将其附加到第二个空列表。但是,当我运行该程序时,它会读取 IndexError:列表索引超出范围。
之后我需要做的是要求用户输入他们想要选择的商品的公斤数,然后乘以价格(我应该从索引中获得)。
import sqlite3
connection = sqlite3.connect('seasonalProduce.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS productList (
productID INTEGER PRIMARY KEY,
productName text NOT NULL,
productPrice real
);""")
#add rows (records) to the productList table
productRecords = [(1, "Apples", 4.59),
(2, "Grapes", 5.99),
(3, "Pumpkin", 3.00),
(4, "Strawberries", 2.50),
(5, "Leafy Greens", 4.00)]
cursor.executemany("INSERT OR IGNORE INTO productList (productID, productName, productPrice) VALUES(?,?,?);", productRecords)
connection.commit()
cursor.execute("SELECT * FROM productList;")
produce = cursor.fetchall()
for rows in produce:
print(rows)
connection.close()
# create list to store productID("ID"), price("price")
#with empty list as their values
#data structure to hold user items as they make their order
groceryList = []
priceList = []
total = 0
productType = 0
#create tuples list with products
productsList = [(1, "Apples", 4.59),
(2, "Grapes", 5.99),
(3, "Pumpkin", 3.00),
(4, "Strawberries", 2.50),
(5, "Leafy Greens", 4.00)]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed with an if/else statement asking for user input
# It should continue and keep adding the total price * weight - BUT THIS FUNCTION DOESN'T WORK
while True:
while True:
try:
choice = int(input("1.SELECT\n2.EXIT\nPlease select 1 or 2 (from the menu) here : ")) #use new line formatting
except ValueError:
print("Invalid response. Please try again.")
if choice == 1:
#have user enter productID -unique identification for each product
#straight into inner-loop with validation
while True: #create inner loop to search database
connection = sqlite3.connect('seasonalProduce.db') #sQ search database
cursor = connection.cursor()
itemID = int(input("Please enter the product ID here : "))
#To display the updates animals to screen:
cursor.execute("SELECT * FROM productList WHERE productID = ?;", (itemID,))
results = cursor.fetchall() #if it's there returns single row - list with 1 tuple
if results == []:
print("Product ID not found.")
else:
#if it does exist return rows
print(results)
#append to groceryList[]
groceryList.append((results))
#access price with indexing [2]
priceList.append((results[2]))
#print(priceList)
#Close connection to database
connection.close()
break
您的
results
是 rows 的列表,因此 results[2]
正在尝试查找不存在的第三行。你想要的是results[0][2]
,即第一行的第三列。