我想写一个代码,创建一个while True
循环,并要求用户从显示的杂货清单中选择一个项目。当用户完成时,我想打破循环,计算这些项目的总价并打印到屏幕上。
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()
while True:
while True:
try:
choice1 = input("Please enter the product ID number:")
if choice1 in range(8):
print("Thank you. Please enter the price of the item.")
price1 = input(float("price per kg:"))
break
else:
print("Please try again. Enter a number within range 1 to 7.")
except ValueError:
print("Invalid input. Please try again.")
while True:
choice2 = input("Please enter the product ID number:")
if choice2 in range(8):
print("Thank you.Please enter the price of the item.")
price1 = input(float("price per kg:"))
price2 = input(float("price per kg:"))
break
else:
print("Please try again. Enter a number within range 1 to 7.")
try:
userContinue = input("Would you like to add another item to your purchase? Y/N: ")
if userContinue.upper() == "Y":
choice3 = input("Please enter the product ID number:")
elif userContinue.upper() == "N":
total = price1 + price2
print("Your total is", total)
except ValueError:
print("Invalid input. Please try again.")`
1条答案
按热度按时间30byixjq1#
在代码中有一些错误。在执行迭代时会出现许多缩进错误。while和try语句沿着的缩进错误在程序中造成了很多冲突。因此,它必须被删除。
另一个问题是在选择输入之后的if语句中。在继续之前,我们必须将字符串转换为整数。分别从字符串转换权重。如果用户输入了3个产品,则代码不会添加并显示总和。
如果你希望用户能够添加无限数量的产品,我们可以尝试while循环而不是最后一个选择中的if循环。它基本上是当userContinue等于Y时,它会要求用户添加另一个产品并将其权重添加到总数中。最后,它将再次询问用户他是否想输入另一个产品。
因此,用户可以添加无限数量的产品。如果用户给出N,那么它将退出循环并打印存储在变量total中的total。创建这个变量也应该解决总计问题。因此,首先我们添加一个cursor命令,它不是要求用户输入价格,而是命令SQL fetchone()与给定产品ID相关联的价格。它以元组形式出现,我们使用float()join()和str()函数将其转换为float。
我们还指定了一个语句if,它的功能是告诉用户他们是否输入了数据库中没有的产品id值。我们通过检查该字段是否为null来实现这一点。它允许用户再次进入。最后,我们必须允许用户选择他们喜欢的重量。
我们接收输入并将其转换为浮点数,因为根据用户的需要,值可以是小数(例如,我们还将其乘以成本,然后将其添加到总变量中。我还在打印命令中做了一些修改,请查看。我还将关闭连接行移到了末尾,因为我们在中间执行了许多数据库操作,下面是实现了所有更改的代码: