2 回答
TA贡献1784条经验 获得超9个赞
input
是一个函数,返回用户输入的值。
if input != 'exit':
永远为真,因为input
是一个函数,并且永远不会等于 'exit'
您需要检查输入的返回值以查看它是否与字符串“exit”匹配。
编辑:尝试以下操作- 如果您有更多提示或没有提示,则此选项应该是“可扩展的”。但有很多方法可以实现您想要做的事情。以下只是其中之一。我添加了评论,因为您似乎是 python 新手!
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
cursor = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS catalog (
number integer NOT NULL PRIMARY KEY autoincrement,
type text NOT NULL,
taxon text,
species text NOT NULL,
part text NOT NULL,
age integer,
layer text,
notes text
)""")
while True:
print('Please enter individual specimen data: ')
input_prompts = [
'Catalog #: ',
'Type of Specimen: ',
'Taxon: ',
'Species: ',
'Body Part: ',
'Estimated Age: ',
'Sedimentary Layer: ',
'Notes: '
]
responses = []
response = ''
for prompt in input_prompts: # loop over our prompts
response = input(prompt)
if response == 'exit':
break # break out of for loop
responses.append(response)
if response == 'exit':
break # break out of while loop
# we do list destructuring below to get the different responses from the list
c_number, c_type, c_taxon, c_species, c_part, c_age, c_layer, c_notes = responses
cursor.execute("""
INSERT OR IGNORE INTO catalog(number, type, taxon, species, part, age, layer, notes)
VALUES (?,?,?,?,?,?,?,?)
""",
(
c_number,
c_type,
c_taxon,
c_species,
c_part,
c_age,
c_layer,
c_notes,
))
conn.commit()
responses.clear() # clear our responses, before we start our new while loop iteration
print('Specimen data entered successfully.')
c.execute("""CREATE VIEW catalog
AS
SELECT * FROM catalog;
""")
conn.close()
TA贡献1876条经验 获得超6个赞
如果没有详细介绍您的代码,我相信它会因识别错误而失败?
python 要求您在 while 循环内缩进代码,因此它应该如下所示。
while True:
if input != 'exit':
print("Please enter individual specimen data: ")
...
第二个问题是您从未创建过该变量input。当你测试时if input == 'exit':它会失败。您需要决定用户在哪一点可以选择键入exit,将其保存到变量中并测试它,大致如下(我调用变量userinput是为了不覆盖input函数):
while True:
userinput = input( 'type exit to exit' )
if userinput != 'exit':
print("Please enter individual specimen data: ")
...
添加回答
举报