简体   繁体   中英

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. 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). 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. 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. I looked at several other similar questions for help and my latest attempt I tried switching to the while loop. With the current code provided the input loop keeps going and ignores the keyword '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' . 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). I tried defining functions for sys.exit() and break and that also gave the same problem of the keyword being ignored.

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

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. 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'

You'll need to check the return value of input to see if it matches the string '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!

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.

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 . When you test if input == 'exit': it will fails. 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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