CS1411 — Exam 1 Study Guide

Thursday Sep 24, 2026 · 1:00–2:00 p.m. · ACAD 707 · closed book / note / watch / phone · laptop with Respondus LockDown Browser · photo ID + pen · written into a browser compiler.

Every word, question, code sample and answer on this page is copied from Adrien’s existing CS1411 Exam 1 prep material (TEST-INTEL.md + PRACTICE.md, built 2026-09-16 from the professor’s Exam 1 Review Sheet and the Gaddis 6e vault book). Nothing here was invented.

Exam day — the 30-second version

Thu Sep 24, 20261:00–2:00 p.m. (1 hour)ACAD 707 — be physically presentBring your laptopPhoto state IDPen or pencilClosed book / note / watch / phoneRespondus LockDown Browser
  • Type: a coding exam, taken in class, on a computer, inside Respondus LockDown Browser. Not a paper test, not a Canvas quiz.
  • Time and place: Thursday Sep 24, 1:00–2:00 p.m. (the class itself runs 1:00–2:45 p.m.; the exam slot is 1 hour). "You will need to be physically present in our assigned classroom." Assigned room is ACAD 707 (syllabus p.1).
  • Bring a laptop. Verbatim: "It is recommended that you bring a laptop because the computers in our classroom are unreliable. Make sure that the computer that you use has the Respondus Lockdown Browser installed on it." Download: https://download.respondus.com/lockdown/download.php?ID=354814027
  • Photo ID required"You will need to bring a valid photo state ID to class otherwise points will be deducted from your grade."
  • Pen or pencil"You will need a pen or pencil in order to sign your name on an attendance document."
  • Closed everything: "closed book, closed note, closed watch, and closed phone exam." Cheating → grade of 0. (Syllabus p.5 repeats this for Quiz/Exam/Lab/Assignment/Presentation.)
  • Internet: "During the exam, you will only be allowed to access the internet in order to submit your Exam 1 solutions." → the notes/code he needs must be in his head, not in a tab.
  • Scratch paper is provided by the instructor — do not bring it.
  • No headphones during the exam.
  • Online compilers used during the exam (i.e. where the code gets written):
  • https://www.programiz.com/python-programming/online-compiler/
  • https://pythonsandbox.com/code/pythonsandbox_u137695_gN5XgVhXPZJLY24pi7ACAEkn_v2.py
  • UHD laptops can be checked out, but "you will need to confirm that it has the Respondus software installed on it"https://www.uhd.edu/computing/uss/laptop-checkout.aspx

Coverage — 2. Coverage — what the exam is over

From the review sheet, page 2, verbatim:

  1. "Make sure that you read and understand chapters 1 – 4 from the textbook."
  2. "Know how to design programs that contain loops and nested loops."
  3. "Know what the purpose of the Arithmetic Logic and Control Units within the CPU is" (with the link geeksforgeeks.org/computer-science-fundamentals/difference-between-alu-and-cu/).
  4. "Make sure that you fully understand all of the source code discussed in class. You may be asked to reproduce portions of this code."
  5. "You might be asked to solve problems that you have never seen before."

Chapter mapping (Gaddis 6e, from the vendored textbook TOC):

ChTitleClass coverage note
1Introduction to Computers and Programming§1.1–1.5: hardware/software, how computers store data, how a program works (fetch-decode-execute), using Python. No source code in this chapter.
2Input, Processing, and Output§2.1–2.11 per the syllabus schedule (Week 2)
3Decision Structures and Boolean Logic§3.1–3.3 (Week 3), §3.4–3.6 (Week 4)
4Repetition Structures§4.1–4.3 (Week 5), §4.4–4.7 (Week 6) — the chapter the exam lands on

The nine named exercises — tap to tick off

0 / 9 can write from a blank page

3. The nine exercises the professor names (learn to write these from a blank page) — full list

Review sheet, page 1, verbatim: "The best way to prepare for the exam is to know how to solve all class exercises without looking at the solution. Focus on the following exercises:"

All nine are implemented in codes/ (provenance and reconstruction flags in CODES.md).

In-class evidence these were worked in class — the LECTURE POINTS rosters posted to Canvas show four in-class exercise sessions: Tue Aug 25, Thu Sep 3, Tue Sep 8, Thu Sep 10 (Canvas module 516320; Excel date serials 46259 / 46268 / 46273 / 46275). The syllabus describes the mechanic: "During the lecture, I will assign practice exercises to work on… If you do not have an answer, you are sleeping, or if the quality of your answer is bad, then .5 points will be deducted from your overall grade… recorded in Canvas under the LECTURE POINTS." (Syllabus p.5.) Adrien is at 0.0 on all four sheets — worth knowing before the next one.

Weighting and grading

ComponentWeight
Quizzes10 %
Two Exams [in class] (15 % each)30 %
Final Exam (Comprehensive) [in class]30 %
Programming Labs [in class]10 %
Programming Assignments [take-home]10 %
Programming Presentation [in class]7 %
Class Participation3 %

Letter grades: 90–100 A, 80–89 B, 70–79 C, 60–69 D, 0–59 F. Exam 1 = 15 % of the course grade. Make-ups only for documented emergencies; "Final Exams cannot be made up." "All missed grades will be recorded as zeros." Quizzes are turned in via the Revel platform (Pearson); "Everything else will be turned in via Canvas."

Course logistics

  • CS1411, section 23489, 4 credit hours, Fall 2026.
  • Class time Tuesdays and Thursdays 1:00–2:45 PM, room ACAD 707.
  • Instructor Cyril Harris, office N614F, harriscy@uhd.edu, 713-221-8418.
  • Office hours Mondays and Wednesdays 4:00–4:30 PM. Canvas mail is the preferred channel.
  • Textbook: Gaddis, Starting Out with Python, 6th ed., ISBN-13 9780137619153, delivered through Pearson Revel (access code from the bookstore).
  • IDE expectations: Visual Studio 2022 or Spyder; the syllabus asks students to name the IDE in a comment at the top of programs (e.g. //Written by: … //Developed using: Visual Studio 2022).
⚠️ How the exam date was pinned down (evidence table)

Adrien's brief for this task said the test is "tomorrow (Thu 2026-09-17)". Every piece of evidence I could reach says the CS1411 exam is one week later, Thursday 2026-09-24, and that nothing is being tested on Thu 2026-09-17 — that day carries three submission deadlines instead.

ClaimEvidence
Exam 1 = Thursday, September 24, 2026, 1:00 p.m. – 2:00 p.m.Canvas announcement #798388, title verbatim: "Exam 1 - Thursday, September 24th, 1:00 p.m. – 2:00 p.m.", posted 2026-09-09T23:38:07Z. Body: "Exam 1 is scheduled to take place: Thursday, September 24th, 1:00 p.m. – 2:00 p.m. Please read the Exam 1 review document."
Same date, second sourceCS 1411 Exam 1 Review Sheet (Fall 2026) Thursday.pdf (Canvas file 10798588, Canvas module 516315 "Exam 1 Review"), page 1: "Exam 1 is scheduled to take place: Thursday, September 24th, 1:00 p.m. – 2:00 p.m.. You will want to show up early."
Same date, third sourceSyllabus cs1411-syllabus-fall2026.pdf p.7 tentative schedule puts Exam 1 in Week 6. Semester started Mon 2026-08-17, so Week 6 = Sep 21–25. Sep 24 sits inside it.
Nothing on Sep 17Canvas announcement list is sorted newest-first; the newest announcement is "9-10 Update", posted 2026-09-10. There is no announcement of any kind after Sep 10, so no online notice of an exam moving to Sep 17.
Sep 17 is a deadline day, not a test dayCanvas assignments API, due 2026-09-18T04:59:59Z = Sep 17, 11:59:59 PM CT: Assignment 1 - Turtle Drawing (id 992027), Lottery Simulator Lab - Part 1 (100 pts, id 992048), Lottery Simulator Lab - Part 2 (id 992049). Announcement #796914 (Sep 3): "Assignment 1 - Due Thursday, September 17th, 2026".
Also due that nightRevel/Pearson item 3: Decision Structures and Boolean Logic due 2026-09-18T07:00:00Z = Sep 18, 02:00 AM CT (assignment id 1009711, 810 pts, external_tool = Pearson Revel).
The canvas calendar feed has no exam at alluser_BOnEpFPmFBrVNopn4vaekw4bgLWWfJGGQBuE8i7Z.ics fetched today: 33 events, zero containing "Exam" for CS1411. Per the known pitfall this is not evidence there is no exam — a paper in-class exam is simply not a Canvas assignment and never enters the feed.

What this means for Adrien: if he is certain a test is tomorrow, that certainty came from something not published on Canvas (a verbal change in class, or he is mixing up the Sep 17 assignment deadlines with the exam). The corpus and practice material in this folder serve either date. Verify with Prof. Harris before assuming a date change — office N614F, 713-221-8418, or Canvas mail (his stated preferred channel; 24–48 h reply).

Sources for "no newer announcement": Canvas API /api/v1/courses/39984/discussion_topics?only_announcements=true read from the authenticated Chrome session on Adrien's Mac.

What could NOT be found — explicitly
  • NOT FOUND: any announcement, file or assignment created or posted after 2026-09-10. So if the exam date changed this week, there is no online record of it.
  • NOT FOUND: a Canvas quiz entity for CS1411. /api/v1/courses/39984/quizzes returns an empty list. The chapter quizzes live on Pearson Revel, which is consistent with the syllabus — but it means "is there a quiz tomorrow?" cannot be answered from Canvas for this course.
  • NOT FOUND: the professor's actual copies of any past exam, and no exam-1 answer key.
  • NOT FOUND: verbatim in-class typed code. Canvas holds no separate artifact for code typed live in ACAD 707. The nearest real sources — all harvested — are the textbook Chapter NN.zip programs, the publisher PPT slides, the "Other Source Code" demo module, and the lab sheets + starter files.
  • PARTIAL ACCESS: the Canvas Pages API returns 404 and the course Files listing returned nothing for the student session. Everything reachable through modules was read; content sitting in an unmoduled folder could not be enumerated.
  • Exam 2 and Final review sheets on Canvas are the Spring 2026 editions (modules 516316 / 516317), not Fall 2026 — so they are not valid coverage statements for this semester's Exam 2 / Final.

A1. Time Converter

RECONSTRUCTEDcodes/time_converter.py
Prompt the user to input a number of minutes greater than 60. Output the equivalent number of hours and minutes. Example: Enter the number of minutes: 125The equivalent time is: 2 hours and 5 minutes
minutes = int(input("Enter the number of minutes: "))

hours = minutes // 60
remaining_minutes = minutes % 60

print("The equivalent time is:", hours, "hours and", remaining_minutes, "minutes")

Key ideas: // is integer division (whole hours), % is the remainder (leftover minutes). Verified: input 125The equivalent time is: 2 hours and 5 minutes.

tap the blurry block to reveal the solution

A2. Random Number

RECONSTRUCTEDcodes/random_number.py
Write a program that will output a random number from the set: {2, 4, 6, 8, 10}.
import random

number = random.randrange(2, 12, 2)

print(number)

randrange(start, stop, step) — the stop value is excluded, so 12 is never produced. Equivalent alternatives the professor would accept: random.choice([2, 4, 6, 8, 10]) or random.randint(1, 5) * 2. Verified: 40 runs produced only 2, 4, 6, 8, 10.

tap the blurry block to reveal the solution

A3. Random Capital Letter

SOURCEDcodes/random_capital_letter.py + codes/random_capital_letter_alt.py
Output a random letter between A and Z (A and Z inclusive) to the console screen.
import random

print(chr(random.randint(65, 90)))

65 is 'A' and 90 is 'Z' in ASCII; chr() converts the number to a character. This is the professor's own posted solution (Random Capital Letter SLN v2.txt), so use exactly this shape. He also posted a second accepted method:

import random
import string

letter = random.choice(string.ascii_uppercase)
print(letter)
tap the blurry block to reveal the solution
tap the blurry block to reveal the solution

A4. Turtle Triangle

RECONSTRUCTEDcodes/turtle_triangles.py
Create the design using turtle graphics. Use speed(), penup(), pendown(), goto(…, …), fillcolor(), begin_fill(), end_fill(), done().

The figure is a large unfilled (outline-only) triangle with a solid blue triangle nested inside it, apex up, both sharing the same bottom line — the inner triangle is the outer one at half scale, centred.

import turtle

SIDE = 200
HALF_SIDE = SIDE / 2
HEIGHT = SIDE * 0.8660254

turtle.speed(0)
turtle.hideturtle()

turtle.penup()
turtle.goto(-HALF_SIDE, -HEIGHT / 2)
turtle.pendown()

for i in range(3):
    turtle.forward(SIDE)
    turtle.left(120)

turtle.penup()
turtle.goto(-HALF_SIDE / 2, -HEIGHT / 2)
turtle.pendown()

turtle.fillcolor("blue")
turtle.begin_fill()

for i in range(3):
    turtle.forward(HALF_SIDE)
    turtle.left(120)

turtle.end_fill()

turtle.done()

Two things the professor listed that are easy to forget: the turn is 120° (exterior angle of an equilateral triangle, 360 / 3) and the fill must be wrapped in begin_fill()end_fill(). No posted solution exists for this one — this is my reconstruction of the sheet's figure.

tap the blurry block to reveal the solution

A5. 4 Circles

RECONSTRUCTEDcodes/four_circles.py
Create the design using Python's Turtle graphics.

Four filled circles in a 2×2 grid, each touching its neighbours: top-left green, top-right blue, bottom-left yellow, bottom-right red.

import turtle

RADIUS = 50

turtle.speed(0)
turtle.penup()

turtle.goto(-RADIUS, 0)
turtle.pendown()
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(RADIUS)
turtle.end_fill()

turtle.penup()
turtle.goto(RADIUS, 0)
turtle.pendown()
turtle.fillcolor("blue")
turtle.begin_fill()
turtle.circle(RADIUS)
turtle.end_fill()

turtle.penup()
turtle.goto(-RADIUS, -2 * RADIUS)
turtle.pendown()
turtle.fillcolor("yellow")
turtle.begin_fill()
turtle.circle(RADIUS)
turtle.end_fill()

turtle.penup()
turtle.goto(RADIUS, -2 * RADIUS)
turtle.pendown()
turtle.fillcolor("red")
turtle.begin_fill()
turtle.circle(RADIUS)
turtle.end_fill()

turtle.hideturtle()
turtle.done()

Geometry worth memorising: with the heading pointing east, circle(r) puts the circle's centre r units to the left (north) of the starting point, so the start points above are the bottoms of each circle. Verified against the sheet's figure: the four centres come out at (±50, ±50) with radius 50 — tangent.

tap the blurry block to reveal the solution

A6. Roll Dice

RECONSTRUCTEDcodes/roll_dice.py
Simulate 2 users rolling dice. Two variables holding values between 2 and 12. Output each player's roll, then who won or that it was a tie.
import random

player1 = random.randint(2, 12)
player2 = random.randint(2, 12)

print("Player 1: ", player1)
print("Player 2: ", player2)

if player1 > player2:
    print("Player 1 Wins")
elif player2 > player1:
    print("Player 2 Wins")
else:
    print("Tie")

The trap: the sheet says 2 to 12, so it is randint(2, 12), not randint(1, 12) and not randint(1, 6). Three sample runs on the sheet (6/5 → P1, 6/12 → P2, 8/8 → Tie) all reproduce.

tap the blurry block to reveal the solution

A7. Roman Numeral Converter

SOURCEDcodes/roman_numeral_converter.py
Ask the user for a number 1–10. Use if: / elif: / else: to display the Roman numeral. Input validation: do not accept a number less than 1 or greater than 10.
number = int(input("Input an integer from the range: 1 through 10: "))

if number == 1:
    print("The Roman Numeral Equivalent is: I")
elif number == 2:
    print("The Roman Numeral Equivalent is: II")
elif number == 3:
    print("The Roman Numeral Equivalent is: III")
elif number == 4:
    print("The Roman Numeral Equivalent is: IV")
elif number == 5:
    print("The Roman Numeral Equivalent is: V")
elif number == 6:
    print("The Roman Numeral Equivalent is: VI")
elif number == 7:
    print("The Roman Numeral Equivalent is: VII")
elif number == 8:
    print("The Roman Numeral Equivalent is: VIII")
elif number == 9:
    print("The Roman Numeral Equivalent is: IX")
elif number == 10:
    print("The Roman Numeral Equivalent is: X")
else:
    print("The number is not valid")

This is Adrien's own submitted file, so it already matches what the professor accepted. Note his wording: the sheet's "input validation" for this lab is done with the else branch printing The number is not valid — no loop. Verified: 1–10 all correct, 30The number is not valid.

tap the blurry block to reveal the solution

A8. Turtle Exercise – Hit the Target (Program 3-9)

SOURCED / RECONSTRUCTEDcodes/hit_the_target.py + codes/turtle_target_loop.py
The base program draws a target square at (100, 250)–(125, 275), asks for an angle and a force, launches force * 30 pixels and reports a hit or a miss. The class modification adds hints ("Try a greater angle", "Use less force").

Base program — reproduced from the class starter file (identical to textbook Program 3-9):

import turtle

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
TARGET_LLEFT_X = 100
TARGET_LLEFT_Y = 250
TARGET_WIDTH = 25
FORCE_FACTOR = 30
PROJECTILE_SPEED = 1
NORTH = 90
SOUTH = 270
EAST = 0
WEST = 180

turtle.setup(SCREEN_WIDTH, SCREEN_HEIGHT)

turtle.hideturtle()
turtle.speed(0)
turtle.penup()
turtle.goto(TARGET_LLEFT_X, TARGET_LLEFT_Y)
turtle.pendown()
turtle.setheading(EAST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(NORTH)
turtle.forward(TARGET_WIDTH)
turtle.setheading(WEST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(SOUTH)
turtle.forward(TARGET_WIDTH)
turtle.penup()

turtle.goto(0, 0)
turtle.setheading(EAST)
turtle.showturtle()
turtle.speed(PROJECTILE_SPEED)

angle = float(input("Enter the projectile's angle: "))
force = float(input("Enter the launch force (1-10): "))

distance = force * FORCE_FACTOR

turtle.setheading(angle)
turtle.pendown()
turtle.forward(distance)

if (turtle.xcor() >= TARGET_LLEFT_X and
    turtle.xcor() <= (TARGET_LLEFT_X + TARGET_WIDTH) and
    turtle.ycor() >= TARGET_LLEFT_Y and
    turtle.ycor() <= (TARGET_LLEFT_Y + TARGET_WIDTH)):
    print('Target hit!')
else:
    print('You missed the target.')

turtle.done()

Verified by execution: angle 68 / force 9 — the combination the sheet gives as a winner — lands at (101.14, 250.34), inside the box. angle 45 / force 3 lands at (63.6, 63.6), a clean miss.

The hint version adds, in the else: branch:

        if turtle.xcor() < TARGET_LLEFT_X:
            print('Try a greater angle.')
        elif turtle.xcor() > (TARGET_LLEFT_X + TARGET_WIDTH):
            print('Try a smaller angle.')
        if turtle.ycor() < TARGET_LLEFT_Y:
            print('Use more force.')
        elif turtle.ycor() > (TARGET_LLEFT_Y + TARGET_WIDTH):
            print('Use less force.')

The extended version (sheet Turtle Target Loop, lab due Sep 22) wraps the whole prompt + launch in a while loop that repeats until the box test passes — see codes/turtle_target_loop.py. If the exam asks for the looped version, that is the shape: initialise a flag, loop while not hit, re-goto(0, 0) each try.

tap the blurry block to reveal the solution
tap the blurry block to reveal the solution

A9. Loop Exercise 0 — Input validation and even numbers

SOURCEDcodes/loop_input_validation_even.py
Prompt for a positive integer num; keep prompting until the input is positive; then loop to output every even integer from 0 up to but not including num. Sample run: -1, 0, 10Output integers -> then 0 2 4 6 8 (one per line).
num = int(input("Input a positive integer "))

while num <= 0:
    num = int(input("Input a positive integer "))

print("Output integers ->")

for i in range(0, num, 2):
    print(i)

Two loops, two purposes — he will be looking for exactly this: a while for validation and a for with a step for the output. Note range(0, num, 2) stops before num. Verified: -1, 0, 10 gives 0 2 4 6 8.

tap the blurry block to reveal the solution

Part C — Concept / short-answer questions

C1. What is the purpose of the ALU and the CU? (the review sheet names this one specifically)

  • ALU — Arithmetic Logic Unit: performs the arithmetic operations (add, subtract, multiply, divide) and the logical operations (comparisons such as equal / greater / less, and AND/OR/NOT) on the data. It has direct access to RAM for its inputs and results.
  • CU — Control Unit: directs and coordinates the rest of the computer. It fetches and decodes each instruction, tells the ALU, memory and I/O devices what to do, and keeps the steps of a program happening in the right sequence and at the right time. It does not itself do arithmetic.
  • One-line contrast to memorise: the ALU does the work; the CU tells everyone else what to do.

Sources: the professor's own slide Computer Organization Overview (Canvas, Lecture Notes module 516318) labels the CPU as ALU – Arithmetic Logic Unit / CU – Control Unit; the review sheet links geeksforgeeks.org/computer-science-fundamentals/difference-between-alu-and-cu/, which states: "ALU … performs all the basic arithmetic (addition, subtraction, multiplication, and division) operations and logical operations" and "the main work of the CU is to tell the most efficient method to work … It informs the ALU, I/O devices, and the RAM how to respond to the command that has been sent to the processor."

C2. The fetch-decode-execute cycle (textbook §1.4, Figure 1-16 — also on the professor's slide)

"When a CPU executes the instructions in a program, it is engaged in a process that is known as the fetch-decode-execute cycle. This cycle, which consists of three steps, is repeated for each instruction in the program."

  1. Fetch — read the next machine-language instruction from memory into the CPU.
  2. Decode — work out which operation the instruction is asking for.
  3. Execute — perform the operation. The textbook's own review question on this: "In the ______ part of the fetch-decode-execute cycle, the CPU determines which operation it should perform"decode. Related wording to know: a program is nothing more than a list of instructions that cause the CPU to perform operations; those instructions are written in machine language (binary); the complete set of instructions a CPU can execute is its instruction set.

C3. Binary, bits and bytes (textbook §1.3)

  • A bit is a single binary digit; a bit that is off represents 0; 1 = high voltage, 0 = low voltage (professor's slide).
  • 8 bits = 1 byte, "enough memory to store a letter of the alphabet or a small number."
  • ASCII = a set of 128 numeric codes for English letters, punctuation and other characters. Unicode = the extensive encoding scheme that can represent characters for many languages.
  • Negative numbers are stored with two's complement; real numbers with floating point.
  • Digital images are made of pixels.

C4. Memory and storage

  • Main memory / RAM is volatile and is where a program must be copied before the CPU can execute it ("a program … has to be copied into main memory, or RAM, each time the CPU executes it").
  • Secondary storage keeps data when the power is off.
  • An input device collects data and sends it to the computer; a video display is an output device.

C5. Structures and loop vocabulary (Chapter 3–4 slides)

  • Sequence structure: statements execute in the order they appear.
  • Decision / selection structure: an action happens only if a condition is true; the diamond in a flowchart is the true/false test.
  • Repetition structure: repeats as long as a condition holds.
  • while = condition-controlled (pretest) — it can execute zero times.
  • for = count-controlled — iterates once per item in a sequence.
  • Infinite loop: a loop with no way of stopping (the slide deck: "Occurs when programmer forgets to include stopping code in the loop").
  • Sentinel: "a special value that marks the end of a sequence of items".
  • Input validation: "inspecting input before it is processed by the program" — repeat while the input is bad.
  • Nested loop: a loop inside another loop; the inner loop completes all of its iterations for each single iteration of the outer loop.

C6. Python language details that show up as short questions

  • input() returns a string; convert with int() / float() when you need math.
  • = assigns, == compares, != is "not equal".
  • In an if/elif/else, Python tests the branches in order and stops at the first true one — that is exactly why the Roman-numeral elif chain works.
  • Comments start with #. The syllabus itself asks students to note which IDE they used in a comment at the top of a program.
  • The walrus operator := assigns and returns the value (print(num := 99)), and is used in the book's newer input-validation loops — while (score := int(input('Enter your score: '))) < 0:. Lower priority, but it is on the Chapter 3 and 4 slides.

C7. Software development life cycle (professor's System Development Life Cycle note)

System Request → Planning → Analysis → Design → Implementation → Maintenance. Planning = feasibility study (is it possible? is it profitable?); Analysis = the list of requirements; Design = how each requirement gets implemented; Implementation = code it and test it; Maintenance = updates, security, fixing bugs, new features.

Part D — “What is the output?” (trace questions)

All outputs below were produced by actually running the programs.

D1

n = 0
while n < 5:
    print(f'Inside the loop, the value of n is {n}.')
    n += 1

Inside the loop, the value of n is 0. through … is 4. (5 lines, 0→4).

D2

count = 10
while count > 0:
    print(count)
    count -= 1
print('Blastoff!')

→ 10 9 8 7 6 5 4 3 2 1 then Blastoff!

D3

for name in ['Winken', 'Blinken', 'Nod']:
    print(name)

Winken, Blinken, Nod

D4

for n in range(3):
    if n == 5:
        print('Breaking out of the loop.')
        break
    print(n)
else:
    print(f'After the loop, n is {n}.')

0, 1, 2, After the loop, n is 2. (no break happened, so else runs)

D5

n = 100
while n < 5:
    print(n)
    n += 1
else:
    print(f'Now n is {n}.')

Now n is 100. only — the body never ran, else still ran.

D6

for outer in range(5):
    for inner in range(20):
        print('*', end='')
        if inner == 3:
            break
    print()

→ five lines, each **** (10 stars per row would be the trap if you assumed break exits both loops).

D7

BASE_SIZE = 8
for r in range(BASE_SIZE):
    for c in range(r + 1):
        print('*', end='')
    print()

→ 8 lines: 1, 2, 3, 4, 5, 6, 7, 8 stars.

D8

n = 0; while n < 10: n += 1 → prints nothing at all (there is no print inside; the loop just counts). A favourite trick question.

Quick reference — every rule, in the material’s own words

f-strings
f'{value:,.2f}' gives thousands separators and 2 decimals ($1,234.57).
// and %
Key ideas: // is integer division (whole hours), % is the remainder (leftover minutes). Verified: input 125The equivalent time is: 2 hours and 5 minutes.
range()
range() rules to have cold: one argument = ending limit; two arguments = start, end; three = start, end, step; and the ending limit is never included.
while vs for
while = condition-controlled (pretest) — it can execute zero times.
for = count-controlled
for = count-controlled — iterates once per item in a sequence.
Input validation
Input validation: "inspecting input before it is processed by the program" — repeat while the input is bad.
Turtle basics
Turtle: turn is 360 / sides (120 for a triangle, 90 for a square); begin_fill() must be paired with end_fill(); penup() before goto() or you draw a stray line; turtle.done() at the end.
Random numbers — the six functions
The professor's demo uses six functions — be able to say what each returns: random.randint(1, 100) (int, both ends included), random.random() (float 0.0–1.0), random.uniform(1.5, 10.5) (float in a range), random.choice(list) (one item), random.sample(list, 3) (3 items, no repeats), random.shuffle(list) (reorders in place).
input() returns a string
The type-conversion trap: input() always returns a string. input('Enter a number: ') * 2 repeats the string; you need int(...) or float(...) first.
randint vs randrange
randint includes both ends; randrange excludes its stop. Roll Dice wants randint(2, 12).
Nested loops — iteration count
Key rule straight from the slide deck: "Total number of iterations in nested loop = number of iterations of inner loop X number of iterations of outer loop."
break / loop else
A loop's else runs unless break fired — and break only exits the loop it is inside.
if / elif / else order
if/elif/else stops at the first true branch, so elif number == 5 never sees values already handled above it.

Part E — Traps, and how to drill this in the time left

Traps + drill plan

Traps that cost marks on this exact material

  1. range() excludes the ending value — range(1, 11) is 1–10, range(0, num, 2) stops before num.
  2. range(start, stop, step) — three arguments, third is the step. Loop Exercise 0 depends on it.
  3. input() is a string. Convert before arithmetic.
  4. // vs /: // is integer division (hours), % is the remainder (minutes).
  5. randint includes both ends; randrange excludes its stop. Roll Dice wants randint(2, 12).
  6. Forgetting the read at the bottom of a sentinel loop ⇒ infinite loop.
  7. A loop's else runs unless break fired — and break only exits the loop it is inside.
  8. Turtle: turn is 360 / sides (120 for a triangle, 90 for a square); begin_fill() must be paired with end_fill(); penup() before goto() or you draw a stray line; turtle.done() at the end.
  9. if/elif/else stops at the first true branch, so elif number == 5 never sees values already handled above it.
  10. Variable names matter to him — his own files use num, num1, tries, matched, divisors, player1, and named constants in caps (TARGET_WIDTH, FORCE_FACTOR, MARK_UP). Reuse those names where the exercise implies them.

Drill plan for the remaining time (highest value first)

  1. The nine in Part A, from a blank file, with the solution hidden. The review sheet's own instruction: "know how to solve all class exercises without looking at the solution." Aim for all nine typed correctly with no reference — that alone is most of the exam.
  2. Then B1 (nested patterns), B2 (range() shapes) and B3/B4 (validation, sentinel).
  3. Then Part C1–C2 out loud (ALU/CU, fetch-decode-execute) — that is the one non-coding item the sheet names explicitly.
  4. In the browser compilers he'll be using, on the laptop he'll actually bring — click through programiz.com/python-programming/online-compiler/ and the pythonsandbox link once so the first minute of the exam is not spent finding the Run button.
  5. Night before: re-run each file in codes/ and read the output. Everything in that folder compiles and runs; nothing in it is untested.

Part B — other code questions that are fair game

B1. Nested loops — star patterns (Chapter 4, explicitly named on the sheet)

Write nested loops that print a right triangle of * with 8 rows, growing by one star each row.
BASE_SIZE = 8

for r in range(BASE_SIZE):
    for c in range(r + 1):
        print('*', end='')
    print()

Output (verified): *, **, ***, … ********. The pair to remember: the inner loop controls the row length, the outer loop controls how many rows, and print() with no arguments ends the row.

Same idea, staircase: 6 steps, each a single # preceded by a growing run of spaces.
NUM_STEPS = 6

for r in range(NUM_STEPS):
   for c in range(r):
      print(' ', end='')
   print('#')
Ask the user for rows and columns, then print a rectangle of stars.
rows = int(input('How many rows? '))
cols = int(input('How many columns? '))

for r in range(rows):
    for c in range(cols):
        print('*', end='')
    print()

Key rule straight from the slide deck: "Total number of iterations in nested loop = number of iterations of inner loop X number of iterations of outer loop."

B2. for vs while vs range() (Chapter 4)

Print a table of the numbers 1–10 and their squares.
print('Number\tSquare')
print('--------------')

for number in range(1, 11):
    square = number**2
    print(f'{number}\t{square}')
Use a while loop as a count-controlled loop: print the value of n for n = 0..4.
n = 0
while n < 5:
    print(f'Inside the loop, the value of n is {n}.')
    n += 1

The slide deck names the three obligations of a count-controlled while: initialise, compare, update (here n = 0, n < 5, n += 1). Expect a question where one of the three is missing — that's the bug.

range() rules to have cold: one argument = ending limit; two arguments = start, end; three = start, end, step; and the ending limit is never included.

B3. Input validation loop (Chapter 4 + used in half the labs)

Keep asking for a wholesale cost until it is not negative, then print the retail price at a 2.5 markup.
MARK_UP = 2.5
another = 'y'

while another == 'y' or another == 'Y':
    wholesale = float(input("Enter the item's wholesale cost: "))

    while wholesale < 0:
        print('ERROR: the cost cannot be negative.')
        wholesale = float(input('Enter the correct ' +
                                'wholesale cost: '))

    retail = wholesale * MARK_UP

    print(f'Retail price: ${retail:,.2f}')

    another = input('Do you have another item? ' +
                    '(Enter y for yes): ')

This is the book's retail_with_validation.py, and it is the template for Loop Exercise 0 and the Lottery Part 2 lab: an outer "do it again?" loop, an inner validation loop.

B4. Sentinel / running total / average (Chapter 4)

A sentinel value ends the loop; add up the inputs until then; then report the total (and average).

The pattern: prime the read before the loop, test the sentinel in the while condition, and read again at the bottom of the loop body. The book's sum_numbers.py / commission.py do exactly that, and count_commission.py shows the counter-variable version. Expect a question that gives a starting template with only the bottom read missing — forgetting it produces an infinite loop, which the slide deck calls out by name.

B5. break, continue, and the loop else (Chapter 4)

What does this print, and why does the else clause run?
n = 100
while n < 5:
    print(n)
    n += 1
else:
    print(f'Now n is {n}.')

Verified output: just Now n is 100. — the loop body never executed but else still runs, because else on a loop runs whenever the loop ends without break. Contrast with for r in range(3): if r == 5: break — no break happens, so else also runs and prints After the loop, n is 2. Only break suppresses a loop's else.

break inside nested loops:
for outer in range(5):
    for inner in range(20):
        print('*', end='')
        if inner == 3:
            break
    print()

Verified output: five lines of ****. break leaves only the loop it is in — the outer loop keeps going, which is the mistake the book flags.

B6. Random numbers (Chapter 2/5 material the class covered with demo_random_number_generation.py)

The professor's demo uses six functions — be able to say what each returns: random.randint(1, 100) (int, both ends included), random.random() (float 0.0–1.0), random.uniform(1.5, 10.5) (float in a range), random.choice(list) (one item), random.sample(list, 3) (3 items, no repeats), random.shuffle(list) (reorders in place).

B7. Decisions — if / elif / else, string comparison, ranges

Convert a numeric score to a letter grade with an if-elif-else chain (book grader.py).
Test whether a value is inside a numeric range — slide deck: use and for inside (x >= 10 and x <= 20), use or for outside (x < 10 or x > 20).
Put two names in alphabetical order with if name1 < name2: — strings compare character by character using ASCII, and string comparison is case sensitive.

B8. Formatting and arithmetic (Chapter 2)

  • f'{value:,.2f}' gives thousands separators and 2 decimals ($1,234.57).
  • //, %, **, and the augmented forms += -= *= /= //= %=.
  • The type-conversion trap: input() always returns a string. input('Enter a number: ') * 2 repeats the string; you need int(...) or float(...) first.