Lecture 3.3 · Interactive lab

Loops Lab

Step through loops round by round, explore range(), and watch a spam filter check every word

Introduction to Data Science and Machine Learning
Md Mahbub E Noor · University of Barishal
All labs

Loop stepper: watch every round

Pick an example from the lecture, or write your own. Step forwards and backwards; the trace table fills in exactly like the ones on the slides.

What to notice

  • The for line runs once per round, and once more to find there is nothing left.
  • Lines before the loop run once; lines inside run every round; lines after run once at the end.
  • A while condition is checked before every round, including the last, False one.

Try this

range() explorer: the numbers a loop will visit

range(start, stop, step) starts at start, adds step each time, and stops before reaching stop.

always
Python
Python gives

In a for loop

On the number line

What to notice

  • range(5) is 0, 1, 2, 3, 4: five numbers, and 5 is not one of them.
  • To include N, write range(1, N + 1).
  • With a positive step and start ≥ stop, the range is empty: the loop body never runs.

Try this

Nested loop grid: every message against every word

The outer loop takes one message; the inner loop checks it against every suspicious word. Each cell is one check. Watch the order they happen in.

Checks done
0
Checks without break
0
Flagged as spam
0

What to notice

  • The inner loop finishes all its rounds before the outer loop moves to the next message.
  • Total checks = messages × words. Double the words and the work doubles.
  • break only leaves the inner loop; the outer loop carries on.

Try this

Predict the loop: what will it print?

Read the code, choose the output, then step through it to see why. The correct answers come from running the code.

What does it print?

What to notice

  • Is the print inside the loop (indented) or after it? That decides how many lines appear.
  • range is worked out once, when the loop starts. Changing a variable inside does not change it.

Try this

Works offline: no internet needed. The Python shown here runs in your browser with the same rules as Python 3, so results and error messages match what you will see in Jupyter.