I am new to Python so this is probably something pretty basic. I have found similar questions on Stackoverflow and other places but not exactly the same.
I am trying to write a Python program to update an Sqlite database. The database has three columns, item, quantity, price. Previously I had updated the database by inserting these values for each of these columns into my code, but now I want to do the same thing using user input.
I hope you'll see from my code that I have created 3 functions to create a table, insert data into the table and one to view the data present in the table.
Using a variable user_choice I then ask the user what they want to do with the program.
I attempt to handle errors firstly by converting the input to a string, secondly to change it lower-case, and thirdly with the use of a while loop. The while loop should loop if the input is not either i or v, or if the input is validated the condition should be satisfied to exit the loop.
The problem is occurring at the while loop I believe. The variable is never validated and it always enters the while loop and stays there. Even then though, each time it loops there is a chance for the variable user_choice to be changed, but again it never gets validated.
Could somebody tell me what's going wrong with this? I am keen to learn.
import sqlite3
def create_table():
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert_data(item, quantity, price):
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur.execute("INSERT INTO store VALUES (?,?,?)",(item, quantity, price))
conn.commit()
conn.close()
def view_data():
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur.execute("SELECT * FROM store")
rows=cur.fetchall()
conn.close()
return rows
create_table()
user_choice=str(input("What would you like to do? \n Insert data (I) \n View data (V) \n Enter your choice, I or V: "))
user_choice=user_choice.lower
print(user_choice)
while user_choice not in ['i','v']:
print ("Your choice is invalid. Please try again.")
user_choice=input("Choose I or V: ")
user_choice=user_choice.lower
if user_choice == 'i':
user_input = input("Enter the item, quantity and price you want to update: ")
input_list = user_input.split(',')
item=str(input_list[0])
quantity=int(input_list[1])
price=float(input_list[2])
insert_data(item,quantity,price)
elif user_choice == 'v':
print(view_data())