External Exam Download Resources Web Applications Games Recycle Bin

Displaying Bookshop Data Fields

how_list_of_tuples_works.py

#list of tuples:
result = [("a","b"),("c","d"),("e","f")]

#tuple 0:
print(result[0][0]) #a
print(result[0][1]) #b

#tuple 1:
print(result[1][0]) #c
print(result[1][1]) #d

#tuple 2:
print(result[2][0]) #e
print(result[2][1]) #f

tuple_one_category_and_desc.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

print(result[1][2]) #category: fiction

print(result[1][3]) #description field of tuple number 1

tuple_zero_name_author_price.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

print(result[0][1])
print(result[0][5])
print("$" + str(result[0][4]))
Given that the SQL query "SELECT * FROM books" returns all six fields from the books table, the six fields are indexed from 0 to 5:

There are 13 books (tuples) in the bookshop.db table, indexed from 0 to 12 in the result list variable. It is important to note that the index for both lists and tuples in Python starts at 0 and not 1.

    Core Activities:

  1. Run all of the Python files above, and make sure you get no error messages.
  2. Write new code using the above examples that can show the following fields from the result list variable:
    • the category field of tuple number 0
    • the description field of tuple number 0
    • the title field of tuple number 1
  3. Extension Activities:

  4. In the file tuple_zero_name_author_price.py code (above), we joined a "$" to the price. What happens if you try dividing the price by 2? (in other words, make the book in tuple 0 half price or 50% off. If you can work out how, round to the nearest dollar.)
  5. From your previous question, try making your answer look exactly like this output, but still calculating the title, author and prices using the techniques shown (i.e. don't just "hard code" this to print):
    Harry Potter and the Chamber of Secrets by Rowling, J.K.
    RRP: $13.95
    Half price: $7