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

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

我想写一个代码,创建一个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.")`
30byixjq

30byixjq1#

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

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)

choice1 = input("Please enter the product ID number:")
nos1=input("Please enter the desired weight in kilograms:")
if int(choice1)in range(8):
    cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice1)))
    price1=cursor.fetchone()
    if type(price1)=="":
        print("This product does not exist. please check your product id")
    float_price1=float('.'.join(str(i) for i in price1))
    float_nos1=float(nos1)
    p1=float_price1*float_nos1
else:
    print("There is no product under that ID. Please verify your number.")
choice2 = input("Please enter the product ID number:")
nos2=input("Please enter the desired weight in kilograms:")
if int(choice2) in range(8):
    cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice2)))
    price2=cursor.fetchone()
    if type(price2)=="":
        print("This product does not exist. please check your product id")
    float_price2=float('.'.join(str(i) for i in price2))
    float_nos2=float(nos2)
    p2=float_price2*float_nos2
else:
    print("There is no product under that ID. Please verify your number.")
userContinue = input("Would you like to add another item to your purchase? Y/N: ")
total=p1+p2
while userContinue.upper() == "Y":
    choice3 = input("Please enter the product ID number:")
    nos3=input("Please enter the desired weight in kilograms:")
    if int(choice3) in range(8):
        cursor.execute("SELECT productPrice FROM productList WHERE productID ={}".format(int(choice3)))
        price3=cursor.fetchone()
        if type(price3)=="":
            print("This product does not exist. please check your product id")
        float_price3=float('.'.join(str(i) for i in price3))
        float_nos3=float(nos3)
        p3=float_price3*float_nos3
        total=total+p3
        userContinue = input("Would you like to add another item to your purchase? Y/N: ")
    else:
        print("There is no product under that ID. Please verify your number.")
print("Your total is", total,"\n Thank You")
connection.close()

相关问题