Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Database
  • Question 1
  • Question 2
  • Question 3
  • Question 4
  • Question 5
  • Question 6
  • Question 7
  • Question 8
  • Question 9
  • Question 10
  • Question 11
  • Question 12
  • Question 13
  • Question 14
  • Question 15
  • Question 16
  • Question 17
  • Question 18
  • Question 19
  • Question 20
  • Question 21
  • Question 22
  • Question 23
  • Question 24
  • Question 25
  • Question 26
  • Question 27
  • Question 28
  • Question 29
  • Question 30
  • Question 31
  • Question 32

Backend Web Development: Practice Questions

For each snippet, write the output. If it prints nothing, write “No Output”.

Database

Every problem starts with a fresh copy of this SQLite database. NULL denotes a SQL NULL value. Rows are shown in id order.

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    username TEXT NOT NULL UNIQUE,
    password TEXT NOT NULL,
    age INTEGER
);
CREATE TABLE messages (
    id integer primary key,
    sender_id integer not null,
    message text not null,
    created_at timestamp not null default current_timestamp
    );

Initial rows:

users(id, username, password, age):
1 | Trump | Trump | 78
2 | Biden | Biden | 81
3 | Evan | correct horse battery staple | 7
4 | Isaac | soccer | 4
5 | Aaron | guaguagua | 3
6 | Aurelia |  | 1
7 | Teal | 524euTjrWm6uK2C5iw8mC6aNgX1JI78o | 35
8 | Kristen | Possible-Rich-Absolute-Battle | NULL

messages(id, sender_id, message, created_at):
1 | 1 | I'm a baby | 2021-11-14 14:30:00
2 | 2 | I'm a baby | 2021-11-14 14:30:00
3 | 3 | I'm a baby | 2021-11-14 14:33:01
4 | 4 | I'm a baby | 2021-11-15 14:35:45
5 | 3 | I'm actually a toddler | 2021-11-16 14:35:45
6 | 6 | Today in 1918, the Armistice that effectively ended WWI came into effect. | 2021-11-11 11:00:00
7 | 6 | I'm an adult | 2021-11-17 14:35:45
8 | 6 | SQL is the best!! | 2021-11-17 14:35:45
9 | 7 | I'm an adult | 2021-11-17 14:35:45
10 | 7 | WTF is SQL?!  I thought you liked the snake thing. | 2021-11-17 14:35:45

Question 1

Use the database above.

# A simplified route table: keys contain both method and path.
routes = {('GET', '/login'): 'show form',
          ('POST', '/login'): 'check credentials'}
print(routes[('GET', '/login')])
print(routes[('POST', '/login')])
Answer
show form
check credentials

Question 2

Use the database above.

# This handler runs once for every request to its route.
def home():
    events = ['Jazz', 'Poetry']
    return {'events': events, 'count': len(events)}

first = home()
first['events'].append('Chess')
second = home()
print(len(first['events']), second['count'])
Answer
3 2

Question 3

Use the database above.

events = [{'title': 'Jazz', 'venue': 'Hall'},
          {'title': 'Poetry', 'venue': 'Garden'}]
context = {'items': events, 'heading': 'Tonight'}
print(context['heading'])
print(context['items'][1]['venue'])
Answer
Tonight
Garden

Question 4

Use the database above.

# A template's loop visits the same items as this Python loop.
context = {'events': [], 'title': 'Calendar'}
print(context['title'])
for event in context['events']:
    print(event['title'])
if not context['events']:
    print('No events yet.')
Answer
Calendar
No events yet.

Question 5

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()
sql = """
SELECT id,password FROM users WHERE username='Trump';
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
    print('row[1]=', row[1])
Answer
row[0]= 1
row[1]= Trump

Question 6

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()
sql = """
SELECT count(*) FROM messages WHERE message LIKE '%a%';
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
Answer
row[0]= 9

Question 7

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
cur = con.execute('SELECT username FROM users WHERE age < 5 ORDER BY age')
print(cur.fetchone()[0])
print(cur.fetchall())
Answer
Aurelia
[('Aaron',), ('Isaac',)]

Question 8

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
con.row_factory = sqlite3.Row
rows = con.execute('''
    SELECT id AS number, username AS author
    FROM users
    WHERE age < 5
    ORDER BY age DESC
''').fetchall()
con.close()

print(rows[1]['author'])
print(rows[0][0])
print(rows[-1]['number'])
Answer
Aaron
4
6

Question 9

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = 'Teal'
sql = """
SELECT id,password FROM users WHERE username=?;
"""
cur.execute(sql, [username])
user_ids = []
for row in cur.fetchall():
    user_ids.append(row[0])

for user_id in user_ids:
    sql = """
    SELECT count(*) FROM messages WHERE sender_id=?;
    """
    cur.execute(sql, [user_id])
    for row in cur.fetchall():
        print('row[0]=', row[0])
Answer
row[0]= 2

Question 10

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = 'Teal'
sql = """
SELECT id FROM users WHERE username=?;
"""
cur.execute(sql, [username])
user_ids = []
for row in cur.fetchall():
    user_ids.append(row[0])

for user_id in user_ids:
    sql = """
    SELECT id, sender_id, message, created_at FROM messages WHERE sender_id=? ORDER BY id;
    """
    cur.execute(sql, [user_id])
    for row in cur.fetchall():
        print(
            'id=',
            row[0],
            'sender_id=',
            row[1],
            'message=',
            row[2],
            'created_at=',
            row[3],
        )
Answer
id= 9 sender_id= 7 message= I'm an adult created_at= 2021-11-17 14:35:45
id= 10 sender_id= 7 message= WTF is SQL?!  I thought you liked the snake thing. created_at= 2021-11-17 14:35:45

Question 11

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
con.row_factory = sqlite3.Row
rows = con.execute('''
    SELECT users.username AS author, messages.message AS text
    FROM messages JOIN users ON messages.sender_id = users.id
    WHERE users.id = 3
    ORDER BY messages.id DESC
''').fetchall()
con.close()

context = {'messages': [
    {'author': row['author'], 'text': row['text'].upper()}
    for row in rows
]}
print(len(context['messages']))
print(context['messages'][0]['author'])
print(context['messages'][1]['text'])
Answer
2
Evan
I'M A BABY

Question 12

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
con.row_factory = sqlite3.Row
rows = con.execute('SELECT users.username AS author, count(*) AS total\nFROM users JOIN messages ON users.id = messages.sender_id\nGROUP BY users.id HAVING count(*) >= 2 ORDER BY total DESC, author').fetchall()
context = {'authors': [dict(row) for row in rows]}
print(context['authors'][0]['author'])
print([row['total'] for row in context['authors']])
Answer
Aurelia
[3, 2, 2]

Question 13

Use the database above.

from html import escape

text = '<em>Hello</em> & goodbye'
print('<p>' + escape(text) + '</p>')
Answer
<p>&lt;em&gt;Hello&lt;/em&gt; &amp; goodbye</p>

Question 14

Use the database above.

from html import escape

context = {'title': 'Arts & Crafts', 'items': ['Paint', 'Clay']}
parts = ['<h2>' + escape(context['title']) + '</h2>']
for item in context['items']:
    parts.append('<p>' + escape(item) + '</p>')
print(''.join(parts))
Answer
<h2>Arts &amp; Crafts</h2><p>Paint</p><p>Clay</p>

Question 15

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
rows = con.execute("SELECT username FROM users WHERE age > 100").fetchall()
context = {'users': rows}
print(context['users'])
for user in context['users']:
    print(user[0])
print('done')
Answer
[]
done

Question 16

Use the database above.

# A small Python version of filling a named template block.
base = '<nav>Home</nav>{content}'
home = '<h2>Events</h2>'
login = '<h2>Log in</h2>'
print(base.format(content=home))
print(base.format(content=login))
Answer
<nav>Home</nav><h2>Events</h2>
<nav>Home</nav><h2>Log in</h2>

Question 17

Use the database above.

# The input was named "user", but the route expects "username".
form = {'user': 'Maya', 'password': 'sun'}
username = form.get('username', '')
password = form.get('password', '')
print(repr(username), repr(password))
Answer
'' 'sun'

Question 18

Use the database above.

def valid_title(form):
    title = form.get('title', '').strip()
    return len(title) > 0

print(valid_title({'title': '  Jazz  '}))
print(valid_title({'title': '   '}))
print(valid_title({}))
Answer
True
False
False

Question 19

Use the database above.

cookies = {'session': 'abc', 'theme': 'dark'}
print(cookies.get('username'))
print(cookies.get('theme', 'light'))
print(cookies.get('session'))
print(cookies.get('session'))
Answer
None
dark
abc
abc

Question 20

Use the database above.

# A response changes cookies on the browser's next request.
request_cookies = {'session': 'old'}
response_cookies = {'session': 'new'}
print(request_cookies['session'])
next_request_cookies = request_cookies.copy()
next_request_cookies.update(response_cookies)
print(next_request_cookies['session'])
Answer
old
new

Question 21

Use the database above.

sessions = {'abc': 'Maya', 'xyz': 'Noor'}
for cookies in [{'session': 'xyz'}, {'session': 'Maya'}, {}]:
    username = sessions.get(cookies.get('session'))
    print(username, username is not None)
Answer
Noor True
None False
None False

Question 22

Use the database above.

sessions = {'abc': 'Maya', 'xyz': 'Noor'}
cookies = {'session': 'abc'}
token = cookies.get('session')
if token in sessions:
    del sessions[token]
print(sessions.get(cookies.get('session')))
print(sessions.get('xyz'))
Answer
None
Noor

Question 23

Use the database above.

def can_edit(username, event):
    return username is not None and username == event['organizer']

event = {'title': 'Jazz', 'organizer': 'Maya'}
for username in ['Maya', 'Noor', None]:
    print(can_edit(username, event))
Answer
True
False
False

Question 24

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
def valid(username, password):
    row = con.execute('SELECT count(*) FROM users WHERE username=? AND password=?',
                      [username, password]).fetchone()
    return row[0] > 0

print(valid('Isaac', 'soccer'))
print(valid('Isaac', 'wrong'))
print(valid('Isaac', "' OR '1'='1"))
Answer
True
False
False

Question 25

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = 'example'
password = 'password'
sql = """
INSERT INTO users (username, password) VALUES (?, ?);
"""
cur.execute(sql, [username, password])
con.commit()

sql = """
SELECT id,password FROM users WHERE username='example';
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
    print('row[1]=', row[1])
Answer
row[0]= 9
row[1]= password

Question 26

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = "example', 'password'), ('example2"
password = 'password'
sql = (
    """
INSERT INTO users (username, password) VALUES ('"""
    + username
    + """', '"""
    + password
    + """');
"""
)
cur.execute(sql)
con.commit()

sql = """
SELECT id,password FROM users WHERE username LIKE 'example%' ORDER BY id;
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
    print('row[1]=', row[1])
Answer
row[0]= 9
row[1]= password
row[0]= 10
row[1]= password

Question 27

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = "example', 'password'), ('example2"
password = 'password'
sql = """
INSERT INTO users (username, password) VALUES (?, ?);
"""
cur.execute(sql, [username, password])
con.commit()

sql = """
SELECT id,password FROM users WHERE username='example';
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
    print('row[1]=', row[1])
Answer
No Output

Question 28

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = 'example'
password = 'password'
sql = """
INSERT INTO users (username, password) VALUES ('?', ?);
"""
cur.execute(sql, [username])
con.commit()

sql = """
SELECT id,password FROM users WHERE username='?';
"""
cur.execute(sql)
for row in cur.fetchall():
    print('row[0]=', row[0])
    print('row[1]=', row[1])
Answer
row[0]= 9
row[1]= example

Question 29

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = "Teal' OR username='Trump"
sql = (
    """
SELECT id,password FROM users WHERE username='"""
    + username
    + """' ORDER BY username;
"""
)
cur.execute(sql)
user_ids = []
for row in cur.fetchall():
    user_ids.append(row[0])

for user_id in user_ids:
    sql = """
    SELECT count(*) FROM messages WHERE sender_id=?;
    """
    cur.execute(sql, [user_id])
    for row in cur.fetchall():
        print('row[0]=', row[0])
Answer
row[0]= 2
row[0]= 1

Question 30

Use the database above.

import sqlite3

con = sqlite3.connect('twitter_clone.db')
cur = con.cursor()

username = "Teal' OR username='Trump"
sql = """
SELECT id,password FROM users WHERE username=?;
"""
cur.execute(sql, [username])
user_ids = []
for row in cur.fetchall():
    user_ids.append(row[0])

for user_id in user_ids:
    sql = """
    SELECT count(*) FROM messages WHERE sender_id=?;
    """
    cur.execute(sql, [user_id])
    for row in cur.fetchall():
        print('row[0]=', row[0])
Answer
No Output

Question 31

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
con.execute('UPDATE users SET age=? WHERE username=?', [8, 'Evan'])
con.commit()
con.close()
con = sqlite3.connect('twitter_clone.db')
print(con.execute("SELECT age FROM users WHERE username='Evan'").fetchone()[0])
Answer
8

Question 32

Use the database above.

import sqlite3
con = sqlite3.connect('twitter_clone.db')
con.execute('DELETE FROM messages WHERE sender_id=?', [3])
con.execute('UPDATE users SET age=? WHERE id=?', [8, 3])
con.rollback()
print(con.execute('SELECT count(*) FROM messages WHERE sender_id=3').fetchone()[0])
print(con.execute('SELECT age FROM users WHERE id=3').fetchone()[0])
Answer
2
7