Looping through a list of tuples
looping_tuples_finding_length.py
import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()
n = len(result)
print(n) #total number of tuples
looping_tuples_show_all.py
import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()
n = len(result) #total number of tuples
i = 0 #we will use i as an 'iterator' variable
while i < n: #while there are tuples to iterate..
print(result[i]) #.. print the tuple, then
i = i + 1 #.. move onto the next
looping_tuples_show_titles.py
import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()
n = len(result)
i = 0
while i < n:
print(result[i][1]) #book title
i = i + 1
- Run the above code files
- Change the looping_tuples_show_titles.py code (above) to show all of the book authors (instead of the titles)
- Change the same code so that the title field as well as the authors field appears for each book in the output, for example:
Harry Potter and the Chamber of Secrets Rowling, J.K. Harry Potter and the Philosopher's Stone Rowling, J.K. etc...
- For your previous question, try and show all the titles of the books and their prices beside them in the output window, for example:
Harry Potter and the Chamber of Secrets $13.95 Harry Potter and the Philosopher's Stone $12.95 etc...
- Try and add some column headings to your data by attempting to recreate the following layout:
title | price ------------------------------------------------- Harry Potter and the Chamber of Secrets | $13.95 Harry Potter and the Philosopher's Stone | $12.95 etc...
Core Activities:
Extension Activities: