smartyfy.mrindigi.com

Python Master Course V2 — 022. For Loops

SMARTYFY ACADEMY · MODULE 03 · LESSON 022 OF 200

For Loops

Estimated study: 60–90 minutes · Prerequisite: Lesson 021 and preceding Python foundations.

Use for loops with lists, strings, range and enumerate.

Video lesson

Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.

Learning outcomes

  • Explain use for loops with lists, strings, range and enumerate.
  • Trace program state and predict the output.
  • Recognize common errors and boundary conditions.
  • Apply the concept to a complete practical project.
  • Write independent tests and justify results.

Understand and apply: For Loops

Choose the simplest traversal for the job

A for loop processes an iterable until it has no more items. Use direct traversal when the values themselves are enough: for name in names is clearer than building indexes just to look each name up again. Lists preserve their element order, and a string supplies its characters in order. The loop body may print, accumulate, or select values, but the loop syntax alone does not decide what to do with them.

Write the iterable after in, finish the header with a colon, and indent the repeated body. Python assigns the next item to the target at the beginning of each iteration. Reassigning that target inside the body does not replace the corresponding source-list item. Also, changing it does not control which item the for loop obtains next; the traversal is managed by the iterable.

Direct list and string traversal

for name in ["Ana", "Ravi"]:
    print("Hello", name)
for letter in "cat":
    print(letter)

Expected output:

Hello Ana
Hello Ravi
c
a
t

The first loop runs twice, once per name. The second runs three times, once per character in this simple word. Use string traversal for tasks such as counting selected characters or checking a small token. Visible symbols in more complex Unicode text can involve multiple code points, so this simple character model should not be confused with every possible human-perceived symbol.

Use range for a numeric progression

Count without building a list of numbers

for number in range(1, 4):
    print(number)
print("Done")

Expected output:

1
2
3
Done

Here range supplies 1, 2, and 3; the stop value 4 is excluded. With one argument, range(3) starts at zero and supplies 0, 1, and 2. Range is useful when the task needs a fixed number of repetitions or a sequence of integer positions. It does not include its endpoint merely because the task is described as "through" that number. The dedicated range lesson explores steps and descending sequences.

Enumerate keeps a label beside each item

Number an attendance report

names = ["Ana", "Ravi", "Mira"]
present = {"Ana", "Mira"}
for number, name in enumerate(names, start=1):
    status = "Present" if name in present else "Absent"
    print(number, name, status)

Expected output:

1 Ana Present
2 Ravi Absent
3 Mira Present

Enumerate supplies a pair for each item: a counter and the item itself. The two target names unpack that pair. The optional start changes the counter's initial value; it does not skip elements. Starting at one is useful for human-readable report numbering, while the default zero aligns with ordinary sequence indexes. If start is one, do not use that counter as a list index without adjusting it.

The report checks membership in the present collection for each name, chooses a status value, then prints one row. Ana and Mira match; Ravi does not. The source names list determines report order, regardless of the order in which present names were entered. Duplicate source names produce duplicate report rows under this simple contract, so a real roster should use unique identifiers if two people can share a name.

An empty roster produces no attendance rows. That is different from a nonempty roster with an empty present collection, which produces one Absent row per name. Avoid inserting or removing roster items while traversing the same list. If the task is just to display each name, direct traversal is enough; choose enumerate only when the numbering is meaningful. This keeps the code focused on the information the report actually requires.

Runnable example and expected output

Setup: Python 3.10 or newer, standard library only. Save the following as lesson_022.py and run python lesson_022.py (or python3).

for i,name in enumerate(["Ana","Ravi"],start=1):
    print(i,name)

Expected output:

1 Ana
2 Ravi

Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.

Guided project: attendance report

Names are assumed unique within this classroom roster. The enumerate counter starts at one for display and visits every name; it does not skip the first list item. Empty names produces no rows, while an empty present collection marks each roster name Absent.

This project applies for loops to a practical scenario. Review the input values and decision or iteration rule before running the program.

def attendance(names,present):
    for index,name in enumerate(names,1):
        print(index,name,"Present" if name in present else "Absent")
attendance(["Ana","Ravi","Mira"],{"Ana","Mira"})

Expected output:

1 Ana Present
2 Ravi Absent
3 Mira Present

Testing plan: Run the shown sample, add an empty or minimum-size input where applicable, and test a value at the relevant boundary. For larger systems, separate the core calculation from user input so it can be tested independently.

Common mistakes and professional practices

  • Confusing an expression’s value with a side effect.
  • Skipping validation of inputs and collection sizes.
  • Misreading the order of operations or changes to state.
  • Forgetting to test zero, empty, minimum and maximum cases.
  • Using overly complicated logic instead of descriptive intermediate variables.

Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.

Practice and reason it through

Attempt each question before opening its answer. Write down the result and the reason, then compare your reasoning with the worked solution.

1. What numbers does range(3) supply?

for number in range(3):
    print(number)
Need a hint?

Count from the default start, and remember that range excludes its stop.

Reveal answer and explanation

It supplies 0, 1, and 2. The default start is zero and the stop value three is excluded. This is three iterations even though the final printed value is two.

Expected output:

0
1
2

2. Does enumerate(start=5) skip the first four items?

for number, name in enumerate(["Ana", "Ravi"], start=5):
    print(number, name)
Reveal answer and explanation

No. It starts the counter at five while visiting every item from the beginning. The first pair is (5, "Ana"), and the second is (6, "Ravi").

Expected output:

5 Ana
6 Ravi

3. Why does this code leave the original list unchanged?

names = ["ana", "ravi"]
for name in names:
    name = name.upper()
print(names)
Reveal answer and explanation

The assignment changes the local loop-target binding to a new string. It does not assign into a list position. The next iteration again receives its item from the list. Constructing a new list or assigning by index is a separate operation taught later.

Expected output:

['ana', 'ravi']

4. How do an empty roster and an empty present collection differ?

Reveal answer and explanation

An empty roster means zero loop iterations and no rows. A roster of Ana and Ravi with no names in present produces two rows: 1 Ana Absent and 2 Ravi Absent. The iterable controls how many rows exist; membership controls each row's status.

for number, name in enumerate(["Ana", "Ravi"], start=1):
    print(number, name, "Present" if name in set() else "Absent")

Expected output:

1 Ana Absent
2 Ravi Absent

5. Which traversal should print names without numbering?

Reveal answer and explanation

Use direct traversal: for name in names. Enumerate adds a counter you do not need, while range(len(names)) adds indexing work that obscures the simple intent. If later requirements add row numbers, enumerate naturally supplies both pieces.

names = ["Ana", "Ravi"]
for name in names:
    print(name)

Expected output:

Ana
Ravi

Further challenge

  • Advanced challenge: Add a new business rule, provide three test cases and explain the expected result for each.

Mastery checkpoint

Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.

Summary: Use for loops with lists, strings, range and enumerate. Reliable programs combine clear logic, appropriate validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.