Python Loops

Loops are a compact way to repeat certain instructions until a specific condition is met or for a specified number of times. The following tutorial is an introduction to loops in Python including for and while loops.


Generative AI Learning

Write-it-yourself class: the AI is your adversary here, not your code generator. Use these prompts after writing the loop examples yourself.

"Quiz me with 5 questions, one at a time, on Python loops: what range(5) and range(1,6) each produce and why the endpoint is excluded, when a while loop is required instead of a for loop, what break does, how an accumulator pattern (total = total + x inside the loop) works, and what an infinite loop is and the two most common ways students create one. Ask me to predict the exact printed output of at least two short loops. Grade my answers and list my misconceptions."
"Write a short Python loop that is supposed to sum the first 10 measurements in a list and report the average, but plant ONE off-by-one or accumulator bug (range end wrong, accumulator initialized inside the loop, dividing by the wrong count). I will hand-trace it and state the printed result before running anything. Then reveal the bug, and give me a second, different planted-bug loop to catch."

Tip: Hand-tracing is the loop skill: write the value of every variable at the end of each pass for the first 3 passes and the last pass. A loop you can trace is a loop you can debug - and later in the course it is how you will audit AI-generated loops in seconds.

What to Turn In

Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but the code must be your own. Answer these questions:

  1. Include a for loop and a while loop you wrote for the same small task (for example, cumulative volume from a list of flow readings, or doubling time of bacteria growth) and state when each form is the natural choice.
  2. Show a hand-trace table (variable values pass by pass) for one of your loops, and confirm the final printed value matches the trace.
  3. From the planted-bug prompts: show both buggy loops, your hand-traced prediction for each, the bugs you found, and the fixes. Did either survive your trace?
  4. From the quiz prompt: one question you missed and the corrected answer.

Course Information

Excel and VBA

Python

MATLAB

MathCAD

Related Courses

Admin