
Code
Ask for the Right Rows
SELECT * gives you everything. Usually you want a precise answer:
some columns, from some rows, in a useful order.
rows = conn.execute(
"SELECT name, coins FROM members "
"WHERE coins > 10 "
"ORDER BY coins DESC, name"
).fetchall()
SELECT name, coinspicks the columns, in that order.WHEREkeeps only rows where the condition is true. Use=,<>(not equal),<,>,<=,>=, and combine withANDandOR. Text values go in single quotes:WHERE island = 'Fog Reach'.ORDER BY coins DESCsorts biggest first (ASC, the default, is smallest first)., namebreaks ties A to Z.LIMIT 3would keep only the first 3 rows.
Let the database do the filtering and sorting. It's fast, and the rule lives right next to the question.
Pip tip: Python glues neighbouring strings together, so end each piece with a space.
"FROM members" "WHERE"becomesFROM membersWHERE, and SQL gets confused!
Assignment
rich_members(conn)returns a list of(name, coins)tuples for members with at least 50 coins. Most coins first; ties in name order (A to Z).fog_roll(conn)returns a list of just the names (strings) of members on'Fog Reach', A to Z. Loop over the rows and append eachrow[0].- Sort with
ORDER BYin SQL, not with Python'ssorted().
The program should print:
[('Bram', 120), ('Ada', 75), ('Wren', 75)]
['Ada', 'Moss', 'Wren']rich_members(conn)returns a list of(name, coins)tuples for members with at least 50 coins. Most coins first; ties in name order (A to Z).fog_roll(conn)returns a list of just the names (strings) of members on'Fog Reach', A to Z. Loop over the rows and append eachrow[0].- Sort with
ORDER BYin SQL, not with Python'ssorted().
The program should print:
[('Bram', 120), ('Ada', 75), ('Wren', 75)]
['Ada', 'Moss', 'Wren']main.py Python sleeping
Press Run to try your code, then Check to test it.