【问题标题】:User input choice using while loops and if loops in pythonpython中使用while循环和if循环的用户输入选择
【发布时间】:2017-10-07 13:14:57
【问题描述】:

我是 Python 新手,所以这可能是非常基本的东西。我在 Stackoverflow 和其他地方发现了类似的问题,但并不完全相同。

我正在尝试编写一个 Python 程序来更新 Sqlite 数据库。数据库有三列,项目、数量、价格。以前我通过将这些列中的每一个的这些值插入到我的代码中来更新数据库,但现在我想使用用户输入来做同样的事情。

我希望您能从我的代码中看到,我创建了 3 个函数来创建表、将数据插入表中以及查看表中存在的数据。

使用变量user_choice 然后我问用户他们想对程序做什么。 我首先尝试通过将输入转换为字符串来处理错误,其次将其更改为小写,最后使用 while 循环。如果输入不是 i 或 v,则 while 循环应该循环,或者如果输入被验证,则应该满足条件以退出循环。

我相信问题发生在 while 循环中。该变量永远不会被验证,它总是进入 while 循环并停留在那里。即便如此,每次循环时,变量user_choice 都有可能被更改,但它再也不会得到验证。

有人能告诉我这是怎么回事吗?我很想学习。

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

【问题讨论】:

    标签: python validation loops while-loop sqlite


    【解决方案1】:

    你犯了一个很容易解决的错误:)。你所要做的就是改变这一行:

    user_choice=user_choice.lower
    

    到这个:

    user_choice=user_choice.lower()
    

    此行出现两次,一次在您的 while 循环之外,一次在内部,因此请确保同时更改。问题是,您没有调用 lower() 函数,因为最后没有括号。

    【讨论】:

    • 谢谢!显然我还不能投票,但请转而感谢。
    • 总是乐于提供帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多