for loop, range, break, continue, pass, else with for, nested for loop

Python for loops iterate directly over elements or sequence ranges, offering powerful control with break, continue, pass, and a unique else block.

12 min read · 12 cards · 3 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The Fixed Checklist Puzzle

In your Semester 1 BCA104 C labs, printing numbers from 1 to 10 required setting up a loop counter, checking conditions, and manually incrementing values like for(int i=1; i<=10; i++). If you forgot to increment, your system crashed into an infinite cycle. Why does Python discard this complex index-management math entirely, letting you sweep across data arrays or numeric ranges with clean, sentence-like readability?

Theory

The Attendance Register

Think of a Python for loop like a class professor ticking off names in an attendance register. The professor does not calculate the distance between student desks: they simply point to the first student on the list, move sequentially to the second, and automatically stop when the final name is reached. The range() function acts like an automated roll-call generator, calling out specific numbers one by one based on a fixed step pattern.

Theory

Definite Iteration Formally

A for loop is a collection-controlled iteration structure that executes a block of code a predetermined number of times by stepping through a sequence like a list, string, or range. The range() function generates an immutable sequence of integers dynamically. Python loops include unique modifiers: break exits instantly, continue skips the current turn, pass acts as a blank syntactic placeholder, and the unique else with for block executes only if the loop completes fully without hitting a break.

At a glance

Table 1: Definite iteration tools and structural modifiers in Python.

Loop Keyword StructureFunctional Impact inside CodePocketMoney Tracking Use Case
range(start, stop, step)Generates integers up to but excluding the stop value.range(1, 31, 7) tracks weekly dates.
passNull operation placeholder that keeps blocks valid.Placeholder for an unwritten category filter.
for...elseExecutes else block only if no break is triggered.Confirms zero fraudulent logs found in audit.
nested forRuns an inner loop fully for each outer loop step.Iterates over weeks and daily spends.

Theory

Worked Example: Auditing the Weekly Ledger

Let us implement a multi-layered verification system for our PocketMoney tracker. We want to loop through a sequence of daily transactions, use continue to skip zero-value entries, use pass for future development, and check for a critical emergency overspent limit using a for-else structure.

Practical

PocketMoney Definite Iteration Auditor

daily_spends = [40, 0, 150, 200, 0, 30]
limit_breached = False

for spend in daily_spends:
    if spend == 0:
        continue
    if spend > 150:
        print("Audit Alert: Suspicious transaction detected!")
        break
    if spend == 40:
        pass
else:
    print("Audit Clean: All spends are within bounds.")

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

Trace the Control Flow Outcome

Analyze the Python script above mentally. What exact messages will be sent to the terminal? Trace each index condition carefully before tapping.

Show the answer

The script will output:

Audit Alert: Suspicious transaction detected!

Why? Let us trace the sequence. index 0 is 40 (hits pass, continues). index 1 is 0 (hits continue, skips to top). index 2 is 150 (not greater than 150, ignored). index 3 is 200 (greater than 150, prints the alert and hits break). Because break is triggered, the entire loop terminates instantly, and the for-else block is skipped completely.

Quiz

What is the exact output sequence of the expression list(range(2, 11, 3)) in a university theory exam?

  1. [2, 5, 8, 11]
  2. [2, 5, 8]
  3. [5, 8, 11]
  4. [3, 6, 9]
Show the answer

[2, 5, 8]

The range function starts at 2 and increments by a step of 3, yielding 2, 5, and 8. It stops immediately before reaching or exceeding the upper limit of 11. Therefore, 11 is excluded from the final list sequence.

Quiz

What happens if a programmer leaves an itemized loop block completely empty without any code or placeholders?

  1. Python ignores the blank space and runs the next line smoothly.
  2. The script raises an immediate IndentationError or SyntaxError.
  3. Python automatically inserts a break statement.
  4. The compiler fills the block with zero values.
Show the answer

The script raises an immediate IndentationError or SyntaxError.

Python cannot handle structurally empty blocks. If you write a loop header line ending with a colon but provide no block code underneath, the interpreter crashes. You must use the pass keyword as a structural placeholder to prevent errors.

Watch out

The Classic Trap: The Stop-Value Exclusion

The most frequent mark-losing mistake in university laboratory examinations is assuming range(1, 5) loops five times from 1 to 5. It does not. Python range sequences are open-ended at the top: they include the start integer but terminate strictly before the stop integer. Writing range(1, 5) only processes indices 1, 2, 3, and 4. To include 5, your stop value must be written as 6.

Theory

Connecting Loops to Semester 3

Definite loops are the core mechanism for row data manipulation. In Semester 3 (BCA303), when unpacking structural tuples from an SQLite database dataset using a database connector cursor, you will rely on expressions like for row in database_cursor: to parse multi-column rows efficiently into singular application entities.

Summary

Key takeaways

  • For loops iterate sequentially across distinct members of collection groupings.
  • The range function generates mathematical integer progressions excluding the final limit bound.
  • The break statement exits loops instantly, bypassing any accompanying else clauses.
  • The continue modifier halts the active pass and moves to the next header value entry.
  • Pass acts as a code placeholder keeping empty conditional or structural loops valid.
  • Memory Hook: Loop finishes trigger else, breaks escape completely!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Conditions, Loops and Strings

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

for loop, range, break, continue, pass, else with for, nested for loop · Programming Skills · Gri-Learn