简体   繁体   English

试图用用户输入的关键字“exit”跳出 while 循环。 (SQLite3 表插入) [Python]

[英]Trying to break out of while loop with user input of keyword 'exit'. (SQLite3 table insert) [Python]

Warning: I am VERY new to coding, apologies in advance & thank you for any help.警告:我对编码非常陌生,提前道歉并感谢您的帮助。

Hello, I am trying to write my first program, just a simple SQLite 3 program to familiarize myself with it.你好,我正在尝试编写我的第一个程序,只是一个简单的 SQLite 3 程序来熟悉它。 First, the goal of the program is to create a table that holds basic data on archaeological faunal remains (since the way they catalog remains is archaic atm).首先,该程序的目标是创建一个表格,其中包含考古动物遗骸的基本数据(因为他们编目遗骸的方式是古老的 atm)。 My problem within the code begins at line 16-35 where I am trying to create a loop that takes user input and then inserts that data into the table/catalog.我在代码中的问题从第 16-35 行开始,我试图创建一个循环,该循环接受用户输入,然后将该数据插入到表/目录中。 I am trying to have the program recognize the keyword 'exit' to break from the loop.我试图让程序识别关键字“退出”以中断循环。 I've tried using a for loop with if & else statements at first, didn't work.我一开始尝试使用带有 if & else 语句的 for 循环,但没有奏效。 I looked at several other similar questions for help and my latest attempt I tried switching to the while loop.我查看了其他几个类似的问题寻求帮助,而我最近尝试切换到 while 循环。 With the current code provided the input loop keeps going and ignores the keyword 'exit'.使用提供的当前代码,输入循环继续运行并忽略关键字“exit”。 I've tried quite a few solutions such as moving around the placement of the else/if statements, changing the while true to a while input == 'exit' or vice versa while input != 'exit' .我已经尝试了很多解决方案,例如移动 else/if 语句的位置,将 while true 更改为while input == 'exit'或反之亦然while input != 'exit' I also tried to import sys and have the keyword 'exit' use sys.exit() and that just made the program not run (maybe I placed it too early within the loop).我还尝试导入 sys 并让关键字“exit”使用 sys.exit() 并且这只是使程序无法运行(也许我将它放在循环中的太早)。 I tried defining functions for sys.exit() and break and that also gave the same problem of the keyword being ignored.我尝试为 sys.exit() 和 break 定义函数,这也给出了忽略关键字的相同问题。

(I initially wrote it in pycharm, starting to use Visual Studio since community edition pycharm no longer includes a database tool) (As you can see my code is procedural, I am still trying to become confident in OOP) (I put the database in :memory: in the sample below) (我最初是在 pycharm 中编写的,由于社区版 pycharm 不再包含数据库工具,因此开始使用 Visual Studio)(如您所见,我的代码是程序性的,我仍在尝试对 OOP 充满信心)(我将数据库放入:内存:在下面的示例中)

Thank you in advance.先感谢您。 I apologize if I didn't provide more concise information on my problem and will be happy to provide anything else needed.如果我没有提供有关我的问题的更简洁的信息,我深表歉意,并且很乐意提供任何其他需要的信息。

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:
if input != 'exit':
    print("Please enter individual specimen data: ")
    c_number = input('Catalog #: ')
    c_type = input('Type of Specimen: ')
    c_taxon = input('Taxon: ')
    c_species = input('Species: ')
    c_part = input('Body Part: ')
    c_age = input('Estimated Age: ')
    c_layer = input('Sedimentary Layer: ')
    c_notes = input('Notes: ')
    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()
    print('Specimen data entered successfully.')
else:
    if input == 'exit':
        break
c.execute("""CREATE VIEW catalog (
AS
SELECT * FROM catalog;
""")
conn.close()

input is a function and returns a value of the user input. input是一个函数并返回用户输入的值。 https://www.geeksforgeeks.org/taking-input-in-python/ . https://www.geeksforgeeks.org/taking-input-in-python/

if input != 'exit': will always be true, because input is a function, and will never equal 'exit' if input != 'exit':永远为真,因为input是一个函数,永远不会等于 'exit'

You'll need to check the return value of input to see if it matches the string 'exit'.您需要检查 input 的返回值以查看它是否与字符串 'exit' 匹配。


EDIT: try the below - this option should be 'scalable' if you have more prompts or what not.编辑:请尝试以下操作- 如果您有更多提示或其他提示,则此选项应该是“可扩展的”。 But there are many ways to do what you're trying to do.但是有很多方法可以做你想做的事情。 Below is just one of them.以下只是其中之一。 I added comments since it seems like you're new to python!我添加了评论,因为您似乎是 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()

Without going into too much detail of your code, I believe it fails with an identation error?没有深入了解您的代码的太多细节,我相信它会因识别错误而失败?

python requires you to indent the code inside the while loop, so it should look something like the below. python 要求你在 while 循环中缩进代码,所以它应该看起来像下面这样。

while True:
    if input != 'exit':
        print("Please enter individual specimen data: ")
        ...

The second issue that stands out is that you never created the variable input .第二个突出的问题是您从未创建变量input When you test if input == 'exit': it will fails.当您测试if input == 'exit':它将失败。 You need to decide at which point the user has the option to type exit , save it into a variable and test it, something along the lines (I am calling the variable userinput to not override the input function):您需要决定用户在哪一点可以选择输入exit ,将其保存到一个变量中并对其进行测试,类似的东西(我调用变量userinput为了不覆盖input函数):

while True:
    userinput = input( 'type exit to exit' )
    if userinput != 'exit':
        print("Please enter individual specimen data: ")
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM