在Python中从数据库中的项目添加总计

2eafrhcq  于 2023-10-14  发布在  Python
关注(0)|答案(1)|浏览(135)

我想写一个代码,创建一个while True循环,并要求用户从显示的杂货清单中选择一个项目。当用户完成时,我想打破循环,计算这些项目的总价并打印到屏幕上。

  1. import sqlite3
  2. connection = sqlite3.connect('seasonalProduce.db')
  3. cursor = connection.cursor()
  4. cursor.execute("""CREATE TABLE IF NOT EXISTS productList (
  5. productID integer PRIMARY KEY,
  6. productName text NOT NULL,
  7. productPrice real
  8. );""")
  9. #add rows (records) to the productList table
  10. productRecords = [(1, "Apples", 4.59),
  11. (2, "Grapes", 5.99),
  12. (3, "Pumpkin", 3.00),
  13. (4, "Strawberries", 2.50),
  14. (5, "Leafy Greens", 4.00)]
  15. cursor.executemany("INSERT OR IGNORE INTO productList (productID, productName, productPrice) VALUES(?,?,?);", productRecords)
  16. connection.commit()
  17. cursor.execute("SELECT * FROM productList;")
  18. produce = cursor.fetchall()
  19. for rows in produce:
  20. print(rows)
  21. connection.close()
  22. while True:
  23. while True:
  24. try:
  25. choice1 = input("Please enter the product ID number:")
  26. if choice1 in range(8):
  27. print("Thank you. Please enter the price of the item.")
  28. price1 = input(float("price per kg:"))
  29. break
  30. else:
  31. print("Please try again. Enter a number within range 1 to 7.")
  32. except ValueError:
  33. print("Invalid input. Please try again.")
  34. while True:
  35. choice2 = input("Please enter the product ID number:")
  36. if choice2 in range(8):
  37. print("Thank you.Please enter the price of the item.")
  38. price1 = input(float("price per kg:"))
  39. price2 = input(float("price per kg:"))
  40. break
  41. else:
  42. print("Please try again. Enter a number within range 1 to 7.")
  43. try:
  44. userContinue = input("Would you like to add another item to your purchase? Y/N: ")
  45. if userContinue.upper() == "Y":
  46. choice3 = input("Please enter the product ID number:")
  47. elif userContinue.upper() == "N":
  48. total = price1 + price2
  49. print("Your total is", total)
  50. except ValueError:
  51. print("Invalid input. Please try again.")`
30byixjq

30byixjq1#

在代码中有一些错误。在执行迭代时会出现许多缩进错误。while和try语句沿着的缩进错误在程序中造成了很多冲突。因此,它必须被删除。
另一个问题是在选择输入之后的if语句中。在继续之前,我们必须将字符串转换为整数。分别从字符串转换权重。如果用户输入了3个产品,则代码不会添加并显示总和。
如果你希望用户能够添加无限数量的产品,我们可以尝试while循环而不是最后一个选择中的if循环。它基本上是当userContinue等于Y时,它会要求用户添加另一个产品并将其权重添加到总数中。最后,它将再次询问用户他是否想输入另一个产品。
因此,用户可以添加无限数量的产品。如果用户给出N,那么它将退出循环并打印存储在变量total中的total。创建这个变量也应该解决总计问题。因此,首先我们添加一个cursor命令,它不是要求用户输入价格,而是命令SQL fetchone()与给定产品ID相关联的价格。它以元组形式出现,我们使用float()join()和str()函数将其转换为float。
我们还指定了一个语句if,它的功能是告诉用户他们是否输入了数据库中没有的产品id值。我们通过检查该字段是否为null来实现这一点。它允许用户再次进入。最后,我们必须允许用户选择他们喜欢的重量。
我们接收输入并将其转换为浮点数,因为根据用户的需要,值可以是小数(例如,我们还将其乘以成本,然后将其添加到总变量中。我还在打印命令中做了一些修改,请查看。我还将关闭连接行移到了末尾,因为我们在中间执行了许多数据库操作,下面是实现了所有更改的代码:

  1. import sqlite3
  2. connection = sqlite3.connect('seasonalProduce.db')
  3. cursor = connection.cursor()
  4. cursor.execute("""CREATE TABLE IF NOT EXISTS productList (
  5. productID integer PRIMARY KEY,
  6. productName text NOT NULL,
  7. productPrice real
  8. );""")
  9. #add rows (records) to the productList table
  10. productRecords = [(1, "Apples", 4.59),
  11. (2, "Grapes", 5.99),
  12. (3, "Pumpkin", 3.00),
  13. (4, "Strawberries", 2.50),
  14. (5, "Leafy Greens", 4.00)]
  15. cursor.executemany("INSERT OR IGNORE INTO productList (productID, productName, productPrice) VALUES(?,?,?);", productRecords)
  16. connection.commit()
  17. cursor.execute("SELECT * FROM productList;")
  18. produce = cursor.fetchall()
  19. for rows in produce:
  20. print(rows)
  21. choice1 = input("Please enter the product ID number:")
  22. nos1=input("Please enter the desired weight in kilograms:")
  23. if int(choice1)in range(8):
  24. cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice1)))
  25. price1=cursor.fetchone()
  26. if type(price1)=="":
  27. print("This product does not exist. please check your product id")
  28. float_price1=float('.'.join(str(i) for i in price1))
  29. float_nos1=float(nos1)
  30. p1=float_price1*float_nos1
  31. else:
  32. print("There is no product under that ID. Please verify your number.")
  33. choice2 = input("Please enter the product ID number:")
  34. nos2=input("Please enter the desired weight in kilograms:")
  35. if int(choice2) in range(8):
  36. cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice2)))
  37. price2=cursor.fetchone()
  38. if type(price2)=="":
  39. print("This product does not exist. please check your product id")
  40. float_price2=float('.'.join(str(i) for i in price2))
  41. float_nos2=float(nos2)
  42. p2=float_price2*float_nos2
  43. else:
  44. print("There is no product under that ID. Please verify your number.")
  45. userContinue = input("Would you like to add another item to your purchase? Y/N: ")
  46. total=p1+p2
  47. while userContinue.upper() == "Y":
  48. choice3 = input("Please enter the product ID number:")
  49. nos3=input("Please enter the desired weight in kilograms:")
  50. if int(choice3) in range(8):
  51. cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice3)))
  52. price3=cursor.fetchone()
  53. if type(price3)=="":
  54. print("This product does not exist. please check your product id")
  55. float_price3=float('.'.join(str(i) for i in price3))
  56. float_nos3=float(nos3)
  57. p3=float_price3*float_nos3
  58. total=total+p3
  59. userContinue = input("Would you like to add another item to your purchase? Y/N: ")
  60. else:
  61. print("There is no product under that ID. Please verify your number.")
  62. print("Your total is", total,"\n Thank You")
  63. connection.close()
展开查看全部

相关问题