1 · Learn and explore
Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.
import sqlite3
def setup(connection):
connection.execute('CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, name TEXT NOT NULL, complete INTEGER NOT NULL DEFAULT 0)')
def add_task(connection, name):
if not name.strip(): raise ValueError('name required')
connection.execute('INSERT INTO tasks(name) VALUES (?)', (name.strip(),))
connection.commit()
def list_tasks(connection):
return connection.execute('SELECT id, name, complete FROM tasks ORDER BY id').fetchall()
def complete_task(connection, task_id):
cursor = connection.execute('UPDATE tasks SET complete=1 WHERE id=?', (task_id,))
connection.commit()
return cursor.rowcount > 0
def main():
with sqlite3.connect('tasks.db') as db:
setup(db)
while True:
command=input('1 add / 2 list / 3 complete / 4 exit: ').strip()
if command=='1':
name=input('Task name: ').strip()
try: add_task(db,name)
except ValueError as error: print(error)
elif command=='2':
for task_id,name,done in list_tasks(db): print(task_id,'[x]' if done else '[ ]',name)
elif command=='3':
try: print('Updated' if complete_task(db,int(input('Task ID: '))) else 'Not found')
except ValueError: print('Please enter a numeric ID')
elif command=='4': break
else: print('Choose 1 to 4')
