0

一个简单的 ddl 程序,但是当响应使用 y 或 n 时,我得到一个名称错误,例如。y 未定义。当我将代码更改为使用 1 或 2 时,程序运行良好。我对 y 或 n 如何引发名称错误感到困惑,我尝试将输入结果定义为字符串,但它仍然给出了名称错误。

import sqlite3
#
def create_table(db_name,table_name,sql):
    with sqlite3.connect(db_name) as db:
        cursor = db.cursor()
        cursor.execute('select name from sqlite_master where name=?',(table_name,))
        result = cursor.fetchall()
        keep_table = True
        if len(result) == 1:
#Problem area
            response = input('The table {0} already exists, do you wish to overide? (y/n): '.format(table_name))
            if response == 'y':
#Problem area end
                keep_table = False
                cursor.execute('drop table if exists {0}'.format(table_name))
                print('Table overwritten')
                db.commit()
            else:
                print('Table kept')
        else:
            keep_table = False
        if not keep_table:
            cursor.execute(sql)
            db.commit()
#
if __name__ == '__main__':
    db_name = 'coffee_shop.db'
    sql = '''create table Product
             (ProductID integer,
             Name varchar(30),
             Price real,
             primary key(ProductID))'''
    create_table(db_name,'Product',sql)

错误信息

The table Product already exists, do you wish to overide? (y/n): y
Traceback (most recent call last):
  File "coffee_shop_v2.db", line 34, in <module>
    create_table(db_name,'Product',sql)
  File "coffee_shop_v2.db", line 13, in create_table
    response = input('The table {0} already exists, do you wish to overide? (y/n): '.format(table_name))
  File "<string>", line 1, in <module>
NameError: name 'y' is not defined
4

1 回答 1

1

使用函数raw_input而不是input. Input evals 显然不是您要查找的响应。

于 2013-07-28T16:00:59.553 回答