Yes or No While 循环可在 while true 循环中工作 -- 使用 SQL 数据库和用户输入 (Python)

Yes or No While Loop to Work Within While True Loop -- with SQL Database and User Input (Python)

提问人:Rendevouz 提问时间:10/14/2023 更新时间:10/14/2023 访问量:20

问:

让 Y/N 语句作为遍历循环工作有很多麻烦。然后,在后续用户选项中遇到问题,包括:确认或取消,或退出并返回主菜单。有些有效,有些无效。没有显示 ValueErrors,所以我认为这与代码的编写方式(?)和布局有关。

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()

connection.close()

def mainMenu():
    connection = sqlite3.connect('seasonalProduce.db')
    cursor = connection.cursor()
   cursor.execute("SELECT * FROM productList;")
   produce = cursor.fetchall()
   for rows in produce:
        print(rows)
        connection.close()

grocerList = []
priceList = []
userSelection = ""
userContinue = ""
purchaseConfirmation = ""
leaveOrMenu = ""

def userMenu():
    while True:
        try:
            mainMenu()
            userSelection = int(input("\nPlease select from the following:\n1. BUY PRODUCTS\n2. EXIT\n3. ADMIN LOGIN\n Your selection: "))
            if userSelection in range(3):
                break
            else:
                print("Please enter a number from the menu.")
        except ValueError:
            print("Please try again and select an option from the menu provided.")

userMenu()
while True:
    try:
        userSelection == 1
        itemID = int(input("Please enter the product ID number: "))
        if itemID not in range(6):
            print("Please provide a valid product ID number from the list provided.")
            mainMenu()
        else:
            weight = float(input("Please enter how many KGs of the product you'd like: "))
            connection = sqlite3.connect('seasonalProduce.db')
            cursor = connection.cursor()
            cursor.execute("SELECT * FROM productList WHERE productID = ?;", (itemID,))
            result = cursor.fetchall()
            if result == []:
                print("Product ID not found. Please check your response and try again.")
            else:
                grocerList.append((result))
                for item in result:
                    priceList.append((float(result[0][2])))
                    totalPrice =  result[0][2] * weight
                    connection.close()

                    userContinue.upper() == input("Would you like to purchase another item? Y/N: ")
                    if userContinue.upper() == "Y":
                        userMenu()
                        break
                    else:
                        userContinue.upper() == "N"
                        finalOrder = ' '.join(map(str, grocerList))
                        print("Here is your order:", grocerList, "\nYour total is", totalPrice)

                        purchaseConfirmation = int(input("\n1. Confirm your order\n2. Cancel your order\nPlease select 1 or 2: "))

                        while purchaseConfirmation == 1:
                            print("Your order is confirmed. Thank you for shopping with us.")

                            confirmation = open("orderConfirmation.txt", "a")
                            confirmation.write(finalOrder)
                            confirmation.close()
                        
                            userMenu()
                        if purchaseConfirmation == 2:
                            print("Your order has been cancelled. Thank you for shopping with us.")

                        elif leaveOrMenu == int(input("\n1. Exit\n2. Return to Menu\n Your answer: ")):
                            if leaveOrMenu == "1":
                                break
                            elif leaveOrMenu == "2":
                                userMenu()
                            else:
                                print("Invalid response, please try again, by selecting either 1 or 2.")
                        
                    
        
    except ValueError:
        print("Please enter a product ID number provided for in the menu and the number of KGs you wish to buy.")
        mainMenu()
sql while-loop 菜单 user-input try-except

评论


答: 暂无答案