Python Foundations: from values to a working program — full text

6 original lessons · about 99 minutes · self-paced

Course details & full text

Six practical lessons. Predict, run, explain and improve a small local program.

No programming experience required. Use an existing local Python 3 installation and a plain-text editor to run the examples, or trace them on paper if Python is not available. No account, paid service, external package or personal data is needed. Examples were checked with Python 3.12.14.

Complete beginner short course · 6 lessons and a local practice-report project · content version 1.0 · reviewed 29 October 2026. This is an introduction, not a semester curriculum or professional qualification. Progress records your own review, not assessed competence.

  • Predict how assignments, integer arithmetic and printed output behave.
  • Write and test conditions, including an exact boundary case.
  • Define a small function with parameters and a useful returned result.
  • Trace a finite loop and accumulate a result without resetting it accidentally.
  • Use lists and dictionaries to represent fictional records and handle an empty list.
  • Build, test and revise a local report program using synthetic records and explicit assumptions.

LESSON 1 OF 6 · 14 MINUTES

Values, names and a first local script

STEP 1 OF 6

Your objective

Run or trace a short script, distinguish a number from text, and explain why a calculated value does not automatically update.

STEP 2 OF 6

The idea

A program is a sequence of instructions. In this course, each displayed runnable example is a complete small script: start at the first line and proceed downward. Predict the output before running it; the difference between your prediction and the actual result is useful evidence, not a score.

For a local run, save only the code as a plain-text file such as first_steps.py. In a terminal already opened in that folder, try python3 first_steps.py; on a Windows installation the command may be py first_steps.py. Use the command your existing installation provides. Do not type these terminal commands at the Python >>> prompt, and do not copy expected-output lines into the file. If no interpreter is installed, trace the examples on paper; the course does not require an online service.

An integer such as 12 is a whole-number value. Text such as "minutes" is a string and needs quotation marks. The value 12 and the string "12" are different: 12 + 3 is 15, while "12" + "3" joins text to make "123". We use integers for all practice durations, avoiding fractional-number precision questions.

Assignment uses one equals sign. In total = sessions * minutes_each, Python first calculates the right-hand expression and then binds the name total to that result. It does not save a live spreadsheet formula. Changing sessions later does not recalculate total until the assignment is run again.

Use descriptive names with underscores and consistent spelling. print("Total:", total) displays a text label and a value separated by a space, then ends the line. A line beginning with # is a comment for the reader. If you see NameError, check whether you used a name before assigning it or spelled it differently; the final error line and reported location are clues.

STEP 3 OF 6

A fictional practice plan changes

Starting point

The plan starts with three sessions of 12 minutes. A fourth session is added after the total has already been calculated. Will the earlier total change by itself?

A checkable approach

sessions = 3 minutes_each = 12 total = sessions * minutes_each sessions = 4 print("Stored total:", total) total = sessions * minutes_each print("Recalculated total:", total)

Output is Stored total: 36 followed by Recalculated total: 48. The first multiplication happened while sessions was 3. Repeating the multiplication after the new assignment produces 48. The labels are strings; total is an integer.

STEP 4 OF 6

Try it yourself

Create a script with pages = 5 and minutes_each = 7. Calculate total, then change pages to 6. Print the old total, recalculate it and print the new total. Predict both outputs first. In a separate sentence, explain why printing "total" is different from printing total. Keep the prediction and correction in your own notes.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. Both prints show 42 because total is linked permanently to pages.

Assignment is not a permanent formula link. The first result stays 35 until the calculation is run again.

B. The first print shows 35 and the second 42; quoted "total" would print the word.

Correct. Five times seven is stored first, then six times seven is stored. Quotes make literal text, not a lookup of the variable.

C. Changing pages produces an error because variables cannot be reassigned.

Reassignment is allowed. The question is when each expression is evaluated, not whether the name can receive a new value.

STEP 5 OF 6

Worked answer & self-check

Worked code: pages = 5 minutes_each = 7 total = pages * minutes_each pages = 6 print("Before recalculation:", total) total = pages * minutes_each print("After recalculation:", total) print("total") Expected output: Before recalculation: 35 After recalculation: 42 total Trace: after line 3, total is 35. After line 4, pages is 6 but total remains 35. Line 6 replaces total with 42. The last print receives literal text, so it does not look up a variable. If your first prediction was 42 twice, revise it by writing the current values beside each assignment. Each run begins from the top of this complete script.

Compare your answer

  • Predicts 35 and 42 before checking, or records and explains a corrected prediction.
  • Keeps the recalculation after the changed pages assignment.
  • Distinguishes a quoted string from an unquoted name.
  • Can identify the terminal command, source code and displayed output as three different things.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • A name refers to the result assigned at that moment.
  • Quotes mark text; unquoted names are looked up.
  • Predict, run and trace the first point of disagreement.

Keep your working script. Next, make the program select different messages from different values.

Next lesson: Choose a path with conditions →

LESSON 2 OF 6 · 14 MINUTES

Choose a path with conditions

STEP 1 OF 6

Your objective

Write an if/elif/else decision and check values below, at and above its boundary.

STEP 2 OF 6

The idea

A comparison asks a yes-or-no question. minutes >= target is True when minutes is greater than or equal to target, and False otherwise. The symbols <, >, <= and >= compare order; == tests equality. One equals sign assigns a value, while two compare values.

An if statement ends its condition with a colon. Indent the statements belonging to that branch by four spaces. An elif adds another condition, and else covers what remains. Within one if/elif/else chain, Python runs only the first branch whose condition is true, or the else branch if none are true.

The order of conditions is part of the rule. Our fictional duration rule checks negative values first, then whether the target was reached. A negative duration is invalid for this exercise, not simply an ordinary short session. An exact target counts as reached, so >= is appropriate; > would exclude equality.

A test should challenge the rule, not just repeat an easy example. For target 20, use 19, 20 and 21 to expose an off-by-one boundary error, plus -1 to check the invalid-duration branch. A successful test compares an actual message with an expected message chosen before running the code.

Indentation is syntax, not decoration. Keep statements for the same branch aligned, and do not mix tabs with spaces. If Python reports SyntaxError or IndentationError, inspect the named line and the preceding colon or block before changing the decision rule. The error location can indicate where parsing failed rather than the original missing character.

STEP 3 OF 6

Exactly on the target

Starting point

An invented session lasts 20 minutes and the target is 20. A draft uses minutes > target, which would incorrectly classify this exact boundary as below target.

A checkable approach

minutes = 20 target = 20 if minutes < 0: print("Invalid duration") elif minutes >= target: print("Target reached") else: print("Below target")

Output is Target reached. The negative check is false, then 20 >= 20 is true. The else branch is skipped. With minutes = -1, the first branch runs and the remaining conditions are not evaluated.

STEP 4 OF 6

Try it yourself

Copy the example and run four separate versions with minutes set to -1, 19, 20 and 21; leave target at 20. Record the expected and actual message for each. Then temporarily change >= to > and identify the one supplied nonnegative test that changes. Restore the correct operator. Explain why four independent if statements would not necessarily behave like one if/elif/else chain.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. With >=, the results are Invalid duration, Below target, Target reached, Target reached.

Correct. Equality belongs to the reached branch. The -1 case is caught before the target comparison.

B. With >=, 20 is below target because the program needs at least 21 minutes.

That describes > 20, not >= 20. The equals part includes the boundary value.

C. Every branch runs once because the script is read from top to bottom.

Reading a branch does not mean executing its body. A single if/elif/else chain selects at most one branch.

STEP 5 OF 6

Worked answer & self-check

Worked code: minutes = 20 target = 20 if minutes < 0: print("Invalid duration") elif minutes >= target: print("Target reached") else: print("Below target") Expected output: Target reached Four-run check: -1 gives Invalid duration; 19 gives Below target; 20 gives Target reached; 21 gives Target reached. Replacing >= with > changes the 20-minute case to Below target; the other three expected messages stay the same. Restore >= to match the stated rule. Independent if statements each test their own condition, so more than one body can run if their conditions overlap. The chain instead stops selecting branches after the first match. This rule assumes the variables contain numbers; text conversion and arbitrary external input are outside this exercise.

Compare your answer

  • Uses a colon and consistent four-space indentation for each branch body.
  • Separates assignment (=) from equality comparison (==).
  • Records all four test cases, including the exact boundary and invalid negative value.
  • Explains which case catches > instead of >= and restores the intended rule.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • A condition evaluates to a truth value.
  • One if/elif/else chain selects at most one branch.
  • Boundary tests reveal mistakes that typical examples can miss.

Next, give a reusable calculation a name so that you can test it without copying its body.

Next lesson: Build a function that returns a useful result →

LESSON 3 OF 6 · 15 MINUTES

Build a function that returns a useful result

STEP 1 OF 6

Your objective

Define and call a two-parameter function, distinguish return from print, and test the function against explicit expectations.

STEP 2 OF 6

The idea

A function packages a task behind a name. A definition begins with def, then the name, parentheses containing parameter names and a colon. Its indented body runs when the function is called, not merely because the definition was read.

Parameters are local names for inputs. In minutes_left(12, 20), the arguments 12 and 20 are assigned to the parameters completed and target for that call. A later call can use different arguments without rewriting the body. Use the parameters inside the function instead of relying on unrelated outside variables.

return sends a value back to the calling expression and immediately ends that call. The caller can store it, compare it or use it in another calculation. print only displays information; it is not a substitute for returning the calculated value. A function that reaches its end without a return value returns None, which means no result value was supplied here.

Our contract is deliberately small: completed and target are nonnegative integer minute counts, and the result is the remaining minutes, never negative. If completed meets or exceeds target, return 0; otherwise return target - completed. The contract describes accepted inputs; this simple function does not validate every possible type or negative input.

Test ordinary, exact-target and over-target inputs. Print an actual result beside its expected value, then explain any mismatch. Testing only one call cannot establish the whole contract. Clear function boundaries make failures easier to locate because you can inspect a calculation separately from the messages around it.

STEP 3 OF 6

Return the calculation, then display it

Starting point

A fictional plan has completed 12 of its target 20 minutes. Another plan already has 24 minutes. Both need the same rule, but not the same result.

A checkable approach

def minutes_left(completed, target): if completed >= target: return 0 return target - completed remaining = minutes_left(12, 20) print("Still to do:", remaining) print("Over target:", minutes_left(24, 20))

Output is Still to do: 8, then Over target: 0. For the second call, return 0 ends the call, so the subtraction below it is not reached. The unindented print lines are outside the function.

STEP 4 OF 6

Try it yourself

Write minutes_left yourself and test (completed, target) pairs (7, 15), (15, 15), (18, 15) and (0, 0). Predict each result first. Store the first result as remaining and calculate remaining + 2 to represent a separate two-minute setup task. Explain what would go wrong if the function printed its result but did not return it.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. Expected remaining values are 8, 0, 0 and 0; the separate setup calculation is 10.

Correct. The function clamps a met or exceeded target to zero, and its numeric return value can be reused.

B. Expected values are 8, 0, -3 and 0 because remaining time must always be target minus completed.

The stated contract says remaining time must not be negative. The first branch handles the over-target case before subtraction.

C. Printing 8 inside the function automatically stores 8 in remaining.

Displaying a value does not return it to the caller. Without an explicit returned result, remaining would be None and adding 2 would fail.

STEP 5 OF 6

Worked answer & self-check

Worked code: def minutes_left(completed, target): if completed >= target: return 0 return target - completed remaining = minutes_left(7, 15) print("Ordinary:", remaining) print("Exact:", minutes_left(15, 15)) print("Over:", minutes_left(18, 15)) print("Zero target:", minutes_left(0, 0)) print("With setup:", remaining + 2) Expected output: Ordinary: 8 Exact: 0 Over: 0 Zero target: 0 With setup: 10 The function is defined once and called four times. The first result is retained for a later arithmetic expression. Replacing return with print would produce screen output but leave the caller without the intended integer result; a call that falls through returns None. Keep calculation and presentation separate. A useful revision is to rename vague parameters a and b to completed and target, then rerun the same four tests to check that the behavior stayed the same.

Compare your answer

  • Defines the function with two parameters and calls it with the intended argument order.
  • Returns integers instead of relying on displayed output.
  • Checks ordinary, equal, over-target and zero-target cases.
  • Reuses the returned result in a separate expression and states the nonnegative-integer input assumption.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • A definition describes a task; a call performs it.
  • Parameters receive inputs and return supplies the result.
  • Test the function independently from how its result is displayed.

Next, repeat an operation over a finite sequence without copying the same lines.

Next lesson: Repeat work and keep a running total →

LESSON 4 OF 6 · 15 MINUTES

Repeat work and keep a running total

STEP 1 OF 6

Your objective

Trace a for loop, use an accumulator correctly, and explain a range endpoint and an empty-loop result.

STEP 2 OF 6

The idea

A for loop takes one item at a time from a finite collection. In for minutes in [8, 12, 5], minutes is first 8, then 12, then 5. Square brackets make a list, an ordered collection we will explore next. The indented body runs once for each item.

A running total is an accumulator. Start total = 0 before the loop. Inside, total = total + minutes calculates a new value from the old total and the current item. The shorter total += minutes has the same effect for these integer totals, but the longer spelling makes the update visible while learning.

The placement of initialization matters. If total = 0 is inside the body, every iteration throws away the previous running total. Similarly, a print inside the body shows each intermediate state; a print after the loop shows the final result once. Trace these positions rather than guessing from the output.

range(start, stop) supplies integers beginning at start and stopping before stop. Thus range(1, 4) visits 1, 2 and 3, not 4. Use it when you need numbered repetitions; loop directly over values when you need those values. These examples are finite, so there is no need to create an open-ended while loop.

The empty-list case is informative: a for loop over [] runs its body zero times. A total initialized to 0 still exists after the loop and correctly reports zero. If you created total only inside the body, an empty collection would leave no such value to print. Do not add or remove items from the same list while learning to loop over it.

STEP 3 OF 6

Watch an accumulator change

Starting point

Three invented practice sessions last 8, 12 and 5 minutes. The desired answer is their sum, but intermediate output can help show how that sum was built.

A checkable approach

durations = [8, 12, 5] total = 0 for minutes in durations: total = total + minutes print("Running total:", total) print("Final total:", total)

The four output lines are Running total: 8, Running total: 20, Running total: 25 and Final total: 25. The first print is indented inside the body; the final print is outside it.

STEP 4 OF 6

Try it yourself

Use durations = [6, 9, 0, 10]. Write a loop that prints only the final total, and write the running totals in your notes. Repeat with durations = []. Then use a separate for loop over range(1, 4) to print three numbered practice rounds. Explain why placing total = 0 inside the duration loop would be wrong.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. The total is 10, because each iteration replaces the previous duration.

That would happen if you assigned total = minutes or reset the accumulator each time. The intended update adds the current duration to the accumulated value.

B. The total is 25, the empty-list total is 0, and range(1, 4) prints rounds 1, 2 and 3.

Correct. The running totals are 6, 15, 15 and 25. The zero-duration item does not increase the sum, and the range stop value is excluded.

C. The total is 25, but range(1, 4) must also include round 4.

The sum is right, but range excludes its stop value. To include 4 while starting at 1, use range(1, 5).

STEP 5 OF 6

Worked answer & self-check

Worked code: durations = [6, 9, 0, 10] total = 0 for minutes in durations: total = total + minutes print("Final total:", total) empty_total = 0 for minutes in []: empty_total = empty_total + minutes print("Empty total:", empty_total) for round_number in range(1, 4): print("Round:", round_number) Expected output: Final total: 25 Empty total: 0 Round: 1 Round: 2 Round: 3 Trace the first loop as old total + item = new total: 0 + 6 = 6; 6 + 9 = 15; 15 + 0 = 15; 15 + 10 = 25. Resetting total to 0 inside that loop would leave just 10 after the last iteration. The empty loop never enters its body, so the initial 0 remains. Revision: move initialization above the loop and keep the final print below it; rerun both the ordinary and empty examples.

Compare your answer

  • Initializes each accumulator before the relevant loop.
  • Shows the four intermediate totals and the final total 25.
  • Checks the empty collection without an undefined variable.
  • Explains both indentation placement and the excluded range endpoint.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • A finite for loop processes one item per iteration.
  • Initialize once, update inside, report afterward.
  • Check no items as well as several items.

Next, give related values a structure so that a program can handle more than a loose list of numbers.

Next lesson: Organize lists and dictionary records →

LESSON 5 OF 6 · 16 MINUTES

Organize lists and dictionary records

STEP 1 OF 6

Your objective

Read and update a list and a dictionary, then loop through a list of consistently shaped fictional records.

STEP 2 OF 6

The idea

A list stores an ordered sequence. In durations = [12, 20], durations[0] is 12 because positions start at zero; durations[1] is 20. len(durations) reports the number of items, which is 2 here, not the last valid position. An empty list has length 0 and has no valid first item.

durations.append(8) adds one item at the end and changes the existing list. Call it as a statement; do not write durations = durations.append(8), because append returns None rather than the updated list. Assignment to durations[0] replaces that item. Reading an out-of-range position raises IndexError.

A dictionary maps keys to values. The record {"label": "Sketch", "minutes": 12} uses named fields rather than positional meaning. record["minutes"] retrieves 12. Keys are not variable names here: the quotes are part of specifying string keys. Reading a missing key with square brackets raises KeyError.

A list of dictionaries combines the two ideas: the list represents several sessions, and each dictionary represents one session with the same fields. Loop over the list, then read each record by key. This makes labels and durations travel together instead of relying on two separate lists staying aligned.

Keep the representation consistent. In these exercises every record has a label string and a nonnegative integer minutes value. A missing field is not silently the same as zero minutes. Because the data are invented and written directly in the script, you can inspect and correct them; handling untrusted or messy external data would require validation beyond this lesson.

Lists and dictionaries can be changed in place. Assigning another name to the same list does not create an independent copy. To keep this beginner exercise predictable, use one name for each working collection and avoid changing its length during iteration. Start a fresh script run when comparing versions.

STEP 3 OF 6

Keep each label with its duration

Starting point

Two fictional sessions are recorded. A third is added, and the first duration is corrected from 12 to 14. The report should reflect those deliberate changes.

A checkable approach

sessions = [ {"label": "Sketch", "minutes": 12}, {"label": "Shapes", "minutes": 20}, ] sessions.append({"label": "Pattern", "minutes": 8}) sessions[0]["minutes"] = 14 print("Session count:", len(sessions)) for session in sessions: print(session["label"], session["minutes"])

Output is Session count: 3, then Sketch 14, Shapes 20 and Pattern 8. sessions[0] finds the first dictionary; ["minutes"] selects its named field. The trailing comma after a list item is allowed.

STEP 4 OF 6

Try it yourself

Create a sessions list with records Grid = 9 minutes and Line = 16 minutes. Append Curve = 5 minutes, then correct Line to 18 minutes. Print the count and every label-duration pair. Finally, total the durations using a loop. Identify the expression for the second record’s minutes and explain why sessions[3] is invalid after these changes.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. The count is 3, the total is 32, and sessions[1]["minutes"] reads the second duration.

Correct. Nine plus eighteen plus five is 32, and index 1 is the second item. Valid list positions are 0, 1 and 2.

B. The count is 2 because append returns None and therefore does not change the list.

append changes the list in place even though its returned result is None. Do not confuse the mutation with the return value.

C. Use sessions[2]["minutes"] for the second item, because counting starts at 1.

Python list positions start at 0. Index 2 is the third item, Curve. The second item is at index 1.

STEP 5 OF 6

Worked answer & self-check

Worked code: sessions = [ {"label": "Grid", "minutes": 9}, {"label": "Line", "minutes": 16}, ] sessions.append({"label": "Curve", "minutes": 5}) sessions[1]["minutes"] = 18 print("Session count:", len(sessions)) total = 0 for session in sessions: print(session["label"], session["minutes"]) total = total + session["minutes"] print("Total minutes:", total) Expected output: Session count: 3 Grid 9 Line 18 Curve 5 Total minutes: 32 The second record is sessions[1], and its duration is sessions[1]["minutes"]. After appending, the length is 3 but the last valid index is 2. sessions[3] would raise IndexError; session["duration"] would raise KeyError because the records use minutes, not duration. Avoid both by checking the structure, not by inventing a default value that hides a misspelled key. If your first total was 30, check that the correction ran before the summing loop.

Compare your answer

  • Creates three records with the same label and minutes keys.
  • Appends without assigning the None return value back to sessions.
  • Updates the second record at index 1 and reports the final total 32.
  • Distinguishes list length, list position and dictionary key lookup.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • Lists group items in order; dictionaries name fields.
  • Zero-based positions run from 0 through length minus 1.
  • A method can change a collection without returning that collection.

Next, combine values, decisions, functions, loops and records into one small report program with a repeatable test set.

Next lesson: Project: a tested local practice report →

LESSON 6 OF 6 · 25 MINUTES

Project: a tested local practice report

STEP 1 OF 6

Your objective

Build a report function, verify five input cases, and revise a small program while keeping its stated behavior intact.

STEP 2 OF 6

The idea

The project is a local report for fictional practice sessions. Given a list of records and a target duration, return a dictionary containing session_count, total_minutes and met_target. met_target counts sessions whose own duration meets or exceeds the target; it does not compare the combined total with the target.

State the contract before coding. The records use label strings and nonnegative integer minutes; target is a positive integer. The function reads the records without editing them. An empty list returns zero for all three counts. The script uses no input prompt, files, accounts, network or packages. Its report describes invented numbers, not a person’s learning quality.

Build the calculation separately from the display. Initialize total_minutes and met_target before the loop. For each record, add its minutes and increment met_target only if that duration is >= target. Return a dictionary after the loop, not inside it: returning inside the loop would stop after the first record.

Use small expected results you can verify by hand. The supplied main case has 12, 20 and 28 minutes: three sessions, 60 total minutes and two sessions meeting a target of 20. At target 25, only the 28-minute session qualifies. Keep the same data while changing one parameter to make the difference explainable.

A passing example is not a complete test set. Check the main case, a changed target, an exact boundary, no records and records all below target. A zero-minute session is still one record, even though it adds nothing to the total. If a check fails, compare the first wrong intermediate value with your manual trace before making several changes at once.

This remains a small beginner script, not a production application. It does not validate arbitrary input, save a history, measure competence or infer whether a target is educationally appropriate. Keep those limits in the final explanation. Adding real users, uploaded data or a service would be a different project requiring new design and safeguards.

STEP 3 OF 6

A complete miniature report

Starting point

The two synthetic records below last 5 and 20 minutes. At target 20, the expected report is two sessions, 25 minutes and one qualifying session. The report function returns a dictionary so the caller can choose how to display it.

A checkable approach

def summarize(sessions, target): total_minutes = 0 met_target = 0 for session in sessions: minutes = session["minutes"] total_minutes = total_minutes + minutes if minutes >= target: met_target = met_target + 1 return { "session_count": len(sessions), "total_minutes": total_minutes, "met_target": met_target, } sessions = [ {"label": "Dots", "minutes": 5}, {"label": "Blocks", "minutes": 20}, ] report = summarize(sessions, 20) print("Sessions:", report["session_count"]) print("Total minutes:", report["total_minutes"]) print("At target:", report["met_target"])

Output is Sessions: 2, Total minutes: 25 and At target: 1. Trace the loop: after Dots the total is 5 and count is 0; after Blocks they are 25 and 1. The return line is outside the loop but inside the function.

STEP 4 OF 6

Try it yourself

Build practice_report.py using synthetic records Tiles = 12, Lines = 20 and Motifs = 28 minutes. Write summarize(sessions, target), display the three reported fields, and verify these five cases: (1) the supplied records at target 20; (2) the same records at target 25; (3) one 20-minute record at target 20; (4) an empty list at target 20; (5) two records with 0 and 19 minutes at target 20. For each case record expected and actual (session count, total minutes, met target). Revise the display label At target to Sessions meeting target without changing the function, then rerun the checks. Keep the code, five-case check and one-paragraph explanation locally.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Practice options

A. At target 20, the main case reports 3 sessions, 60 minutes and 3 meeting the target because the combined total exceeds 20.

The total is 60, but the rule applies separately to each session. The 12-minute session is below target, so only two qualify.

B. At target 20, the main case reports (3, 60, 2); the empty case reports (0, 0, 0).

Correct. The 20- and 28-minute records qualify, and an empty loop leaves both accumulators at zero. The function still returns a report.

C. Put return inside the loop so that every iteration adds a returned report to the result.

return ends the function call; it does not accumulate returns. Inside the loop it would stop after the first record, and an empty list would reach the end without the intended dictionary.

STEP 5 OF 6

Worked answer & self-check

Worked code: def summarize(sessions, target): total_minutes = 0 met_target = 0 for session in sessions: minutes = session["minutes"] total_minutes = total_minutes + minutes if minutes >= target: met_target = met_target + 1 return { "session_count": len(sessions), "total_minutes": total_minutes, "met_target": met_target, } sessions = [ {"label": "Tiles", "minutes": 12}, {"label": "Lines", "minutes": 20}, {"label": "Motifs", "minutes": 28}, ] report = summarize(sessions, 20) print("Sessions:", report["session_count"]) print("Total minutes:", report["total_minutes"]) print("Sessions meeting target:", report["met_target"]) Expected output: Sessions: 3 Total minutes: 60 Sessions meeting target: 2 Five-case expected results, written as (session count, total minutes, met target): main case at 20 = (3, 60, 2); same records at 25 = (3, 60, 1); one 20-minute record at 20 = (1, 20, 1); empty list at 20 = (0, 0, 0); 0- and 19-minute records at 20 = (2, 19, 0). For each separate run, replace only sessions and the target argument, then compare the printed fields. Keep the function unchanged unless a result fails. Model explanation: The function loops over every supplied record, adds its duration and counts only individual durations that reach the target. It returns the summary after all records, so the empty case still returns zeros. The display revision clarifies what is counted without changing the calculation. These results assume consistently shaped synthetic records and nonnegative integer durations; duration alone does not measure learning. If the main result is (3, 12, 0), inspect whether return was placed inside the loop. If it is (3, 60, 1) at target 20, inspect whether > accidentally replaced >=. If an empty case yields None, check that the return is outside the loop. After any fix, rerun all five cases rather than only the failing one.

Compare your answer

  • Contract: states the required record keys, nonnegative integer durations, positive integer target and empty-list behavior.
  • Implementation: uses parameters, a finite loop, two initialized accumulators, a >= condition and a dictionary returned after the loop.
  • Verification: records actual results matching all five expected triples, or documents and fixes a mismatch before marking reviewed.
  • Separation: changes the display label without changing the calculation and reruns the checks.
  • Explanation: traces the main case, notes that each session is tested individually, and avoids claiming that minutes measure competence.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • Separate a program’s inputs, calculation, returned result and display.
  • Make expected outputs explicit, including boundary and empty cases.
  • After a revision, rerun the earlier checks to look for regressions.

Finish by checking every rubric item and correcting any mismatch. Mark reviewed after your own self-check, not merely after selecting an option. You have completed this introductory short course, not an independent assessment or qualification. Keep the local script and tests as a starting point; no upload, certificate or external account is required.

Revisit the course → · Choose another course →

Sources & learning limits

Examples, exercises and worked answers are original fictional teaching material. Source checks inform the factual explanations; these organisations do not endorse this course.

This independent course is general education, not accreditation, a degree, professional advice or a promise of competence. No institutional affiliation or endorsement is implied. The illustrated setting is fictional.