Python for Databases 2: Loops and Functions
How a Python program goes over the rows of a table, decides about each one, and packs a piece of work into a function with parameters and a sorting key.
Last updated:
How does a program go over every row and answer a question?
A query returns many rows. To answer a question such as “how many rentals were there on all the summer days in this list?”, a program has to go over the rows, decide about each one, and add things up.
This lesson teaches the three tools for that: decisions with if, repetition with for, and functions that give a name to a piece of work.
The lesson continues Python for Databases 1. If a term here is new, such as tuple, index or dictionary, go back to it.
The examples run in your browser: select Run under a box, from top to bottom, because the boxes of a page share their variables.
We use six real rows of the bike-share table: three winter days and three summer days, each as a tuple of the identifier, the date, the season and the number of rentals.
rows = [
(1, '2011-01-01', 'Winter', 985),
(2, '2011-01-02', 'Winter', 801),
(3, '2011-01-03', 'Winter', 1349),
(185, '2011-07-04', 'Summer', 6043),
(186, '2011-07-05', 'Summer', 4665),
(187, '2011-07-06', 'Summer', 4629),
]
len(rows)
6
Decisions: if, elif and else
A block is a group of lines that belong together. Python marks a block by indentation (spaces at the beginning of the lines), and the line that opens the block ends with a colon.
Indent the whole block by the same amount, usually four spaces.
rentals = 4665
if rentals >= 5000:
label = 'very busy'
elif rentals >= 3000:
label = 'busy'
else:
label = 'quiet'
print(rentals, label)
4665 busy
Python checks the conditions from the top. It runs the block of the first condition that is true, and skips the rest.
The else block runs when no condition was true. The parts elif (short for “else if”) and else are optional.
Practice
Write the decision. Set rentals = 6043. Then write an if, elif and else that print one word:busy when rentals is above 5000, normal when it is above 2000, and quiet otherwise.
# your code here
Show a solution
rentals = 6043
if rentals > 5000:
print('busy')
elif rentals > 2000:
print('normal')
else:
print('quiet')
busy
Show a common mistake and why it happens
With two separate if statements, the else belongs only to the second one, and the first if is checked on its own.
A number above 5000 is also above 2000, so both words are printed.
Use elif to make the conditions one chain, where only the first true block runs.
rentals = 6043
if rentals > 5000:
print('busy')
if rentals > 2000:
print('normal')
else:
print('quiet')
Show a common mistake and why it happens
Python runs the first block whose condition is true, and stops there.
Every number above 5000 is also above 2000, so the check for normal comes first and catches it before busy is reached.
Put the narrowest condition first.
rentals = 6043
if rentals > 2000:
print('normal')
elif rentals > 5000:
print('busy')
else:
print('quiet')
Repetition: for
A for loop runs its block once for each value of a collection, and puts the current value in a name that you choose:
for row in rows:
print(row[2], row[3])
Winter 985
Winter 801
Winter 1349
Summer 6043
Summer 4665
Summer 4629
The loop header can unpack the values of each tuple at the same time, so the names describe the values:
for day_id, date, season, rentals in rows:
if season == 'Summer':
print(date, rentals)
2011-07-04 6043
2011-07-05 4665
2011-07-06 4629
To add things up, start a variable before the loop and update it inside the block.
The form total += x means total = total + x:
total = 0
count = 0
for day_id, date, season, rentals in rows:
if season == 'Summer':
total += rentals
count += 1
print(total, count, total / count)
15337 3 5112.333333333333
Notice the difference in what is inside the block of the for and what is inside the block of the if:
the if block is indented one more level, so it runs only for the rows that pass the condition.
To build a new list, start with an empty list and append to it:
summer_days = []
for day_id, date, season, rentals in rows:
if season == 'Summer':
summer_days.append(date)
print(summer_days)
['2011-07-04', '2011-07-05', '2011-07-06']
To repeat something a fixed number of times, loop over range(n), which returns the numbers from 0 up to n - 1:for i in range(3) runs with i equal to 0, 1 and 2.
for i in range(3):
print(i)
0
1
2
A dictionary loops through its pairs with the method items(), which returns the pairs of a key and its value, one pair on each round:
day = {
'date': '2011-01-01', 'season': 'Winter', 'rentals': 985
}
for key, value in day.items():
print(key, '->', value)
date -> 2011-01-01
season -> Winter
rentals -> 985
Practice
Write the loop. Loop over rows and print the date of each winter day, one date on each line.
# your code here
Show a solution
for day_id, date, season, rentals in rows:
if season == 'Winter':
print(date)
2011-01-01
2011-01-02
2011-01-03
Show a common mistake and why it happens
The loop runs on every row and nothing filters it, so all six dates are printed.
The season has to be tested with an if inside the loop, so that only the rows that pass the condition reach print.
for day_id, date, season, rentals in rows:
print(date)
Show a common mistake and why it happens
The loop is correct, but the dates are collected in a list and the list is printed once, so the output is one line in brackets with quotation marks.
Printing inside the loop gives one plain date on each line.
winter_dates = []
for day_id, date, season, rentals in rows:
if season == 'Winter':
winter_dates.append(date)
print(winter_dates)
Functions: a name for a piece of work
The loop above that adds the summer rentals is useful for any season.
Instead of copying it, put it in a function. The keyword def starts the definition, then the name, the parameters in brackets (the values that the function needs), and a colon.
The return line sends the result back to the place that called the function:
def season_total(rows, season):
total = 0
for day_id, date, day_season, rentals in rows:
if day_season == season:
total += rentals
return total
print(season_total(rows, 'Summer'))
print(season_total(rows, 'Winter'))
15337
3135
How to read the definition:
rowsandseasonare the parameters, the names that the function uses inside its block. The values that you write in the call,rowsand'Summer', are the arguments.- The variables created inside the function, such as
total, exist only while the function runs, and do not disturb variables with the same name outside. - A function that does not reach a
returnreturnsNone.
An argument can be given by the parameter’s name, which makes a call easier to read and lets you write the arguments in any order.
A parameter can also have a default value, which is used when the call leaves it out:
def busy_days(rows, limit=5000):
dates = []
for day_id, date, season, rentals in rows:
if rentals > limit:
dates.append(date)
return dates
print(busy_days(rows))
print(busy_days(rows, limit=4650))
print(busy_days(limit=1000, rows=rows))
['2011-07-04']
['2011-07-04', '2011-07-05']
['2011-01-03', '2011-07-04', '2011-07-05', '2011-07-06']
The call style with names, such as limit=4650, is also how an object is created from named values in objects and generator expressions, so the call style you practice here carries over.
Practice
Write the function. Define a function is_summer(row) that returns True when the season of the row is 'Summer', and False otherwise.
Then print is_summer(rows[0]) and, on the next line, is_summer(rows[3]).
# your code here
Show a solution
def is_summer(row):
return row[2] == 'Summer'
print(is_summer(rows[0]))
print(is_summer(rows[3]))
False
True
Show a common mistake and why it happens
This function prints its answer but does not return it. The call then gives back None, so the outer print shows None after the printed value.
The word return is what sends the result back to the place that called the function.
def is_summer(row):
print(row[2] == 'Summer')
print(is_summer(rows[0]))
print(is_summer(rows[3]))
Show a common mistake and why it happens
The index counts from 0, and the season is the third value of the row, row[2].
The value row[1] is the date, which is never equal to 'Summer', so the function always answers False.
def is_summer(row):
return row[1] == 'Summer'
print(is_summer(rows[0]))
print(is_summer(rows[3]))
Functions as values: a sorting key
In Python a function is a value, so it can be given to another function.
The functions max, min and sorted accept a key function: they call it on each item and compare the results.
To find the busiest day in rows, the key function should return the number of rentals of a row:
def rentals_of(row):
return row[3]
print(max(rows, key=rentals_of))
print(sorted(rows, key=rentals_of, reverse=True)[:2])
(185, '2011-07-04', 'Summer', 6043)
[(185, '2011-07-04', 'Summer', 6043), (186, '2011-07-05', 'Summer', 4665)]
The call sorted(..., reverse=True) sorts from the largest to the smallest, and the slice [:2] keeps the first two items.
The SQL guide did the same with ORDER BY ... DESC LIMIT, in Sort and limit results.
A function this small is often written in place, without a name, as a lambda:lambda row: row[3] means “given a row, give back row[3]”. It is the same as the function rentals_of:
print(max(rows, key=lambda row: row[3]))
print(min(rows, key=lambda row: row[3])[1])
(185, '2011-07-04', 'Summer', 6043)
2011-01-02
The key function decides what “largest” means. With key=lambda row: row[3], the largest row is the one with the most rentals; with key=lambda row: row[1], it would be the row with the latest date.
Check yourself: what does this expression return?
max(rows, key=lambda row: row[3])
A: the number 6043
The thinking: it finds the largest number of rentals.
The mistake: max with a key returns the item that has the largest key, not the key itself.
Here the item is the whole row. To get the number, take item 3 of the result:
max(rows, key=lambda row: row[3])[3]
B: the row (187, '2011-07-06', 'Summer', 4629)
The thinking: the last row, or the row with the largest identifier.
The mistake: the key is row[3], the rentals, not the identifier row[0].
With key=lambda row: row[0] this answer would be right.
C: the row (185, '2011-07-04', 'Summer', 6043)
Correct: the key function turns each row into its number of rentals, max finds the row with the largest number, and returns that row.
Practice
Each question has its own code box: write your answer there and select Run.
Open a hint if you are stuck, and the solution only after you try.
Question 1. Write a function count_days(rows, season) that returns how many rows have the given season, and print the number of winter days of rows.
# your answer here
Show a first hint
Think of a counter: a variable that starts at 0 and grows inside the loop.
Show a second hint
Start count = 0, loop over the rows, and add 1 for each row whose season is the requested one.
Do not forget return.
Show a solution
def count_days(rows, season):
count = 0
for day_id, date, day_season, rentals in rows:
if day_season == season:
count += 1
return count
print(count_days(rows, 'Winter'))
3
The parameter is called season, so inside the loop the season of each row gets a different name, day_season.
With the same name, the comparison would be a row’s season against itself and always true.
Show a common mistake and why it happens
This function never looks at the season, so it returns the number of all rows:
def count_days(rows, season):
return len(rows)
print(count_days(rows, 'Winter'))
Question 2. Print the date and rentals of the three days with the most rentals, from the busiest day down, one day on each line with a space between them (for example 2011-01-01 985).
# your answer here
Show a first hint
First put the rows in order, with the most rentals first. Then keep only three of them.
Show a second hint
Sort the rows with sorted, with a key and reverse=True, keep the first three with a slice, and loop over them.
Show a solution
top = sorted(rows, key=lambda row: row[3], reverse=True)[:3]
for day_id, date, season, rentals in top:
print(date, rentals)
2011-07-04 6043
2011-07-05 4665
2011-07-06 4629
Show a common mistake and why it happens
Without reverse=True, sorted starts with the smallest values, so the slice keeps the three days with the fewest rentals:
top = sorted(rows, key=lambda row: row[3])[:3]
for day_id, date, season, rentals in top:
print(date, rentals)
Question 3. Write a function average_rentals(rows, season) that returns the average rentals of the days of one season, and returns None when the list has no such day.
Print the result for 'Winter' and then for 'Spring', one on each line.
# your answer here
Show a first hint
Two cases: the list of matching rentals is empty, or it is not.
Show a second hint
Collect the rentals of the matching rows in a list. If the list is empty, return None; otherwise return the sum divided by the length.
Show a solution
def average_rentals(rows, season):
values = []
for day_id, date, day_season, rentals in rows:
if day_season == season:
values.append(rentals)
if len(values) == 0:
return None
return sum(values) / len(values)
print(average_rentals(rows, 'Winter'))
print(average_rentals(rows, 'Spring'))
1045.0
None
The check for an empty list prevents a division by zero, which stops a program with an error.
SQL treats the same situation differently: the average of no rows is NULL, not an error.
In Python we choose what to return, and None is the natural choice, because it is also what Python receives when a database returns NULL.
Show a common mistake and why it happens
An average of no days is not 0 (that would be a real average):None says that there is no value:
def average_rentals(rows, season):
values = []
for day_id, date, day_season, rentals in rows:
if day_season == season:
values.append(rentals)
if len(values) == 0:
return 0
return sum(values) / len(values)
print(average_rentals(rows, 'Winter'))
print(average_rentals(rows, 'Spring'))
Keep in mind
- A block is marked by a colon and indentation;
if,elifandelsechoose which block runs. for item in collection:runs its block once for each item; a variable that starts before the loop collects a total or a count, andappendbuilds a list.def name(parameters):defines a function,returnsends the result back, parameters may have default values, and arguments may be given by name.- A function is a value:
max,minandsortedtake akeyfunction, often written as a shortlambda, andmaxandminreturn the item with the largest or smallest key.
Next: objects, classes and generator expressions, which turn a row into an object with named attributes.