Loops in Python

Learn to make a Python program repeat work. Write while loops that run until a condition changes, for loops that step through strings, lists and ranges of numbers, and use break, continue and a loop's else block to control them. Apply the standard patterns for counting, totaling, averaging, finding the largest value and searching, build nested loops for grids and combinations, and trace loops by hand to catch off-by-one errors and loops that never stop.

BeginnerLesson 3 of 10 in Python for Beginners: Introduction to Programming

What you will learn

  1. Write while loops that repeat a block of code for as long as a condition is true, make sure every loop stops, and use loops to read input until the user is done.
    • Write a while loop that counts and updates
      Read and write the three working parts of a while loop: a starting value, a condition that is tested before every pass, and an update in the indented body.
    • Make sure a while loop stops
      Recognize infinite loops, explain why they happen, fix them, and stop a program that is stuck in one.
    • Read input until the user is done
      Use while loops to keep reading values until a stop value appears, and to ask again until the user gives an acceptable answer.
  2. Use for loops to visit every item of a string or list and every number in a range, and decide when a for loop or a while loop fits a task better.
    • Loop over the items of a sequence
      Write for loops that visit each character of a string or each value of a short list, in order, and use the loop variable correctly.
    • Generate number sequences with range
      Use range with one, two or three arguments to repeat a set number of times or to step through evenly spaced integers, including counting down.
    • Choose between a for loop and a while loop
      Decide which kind of loop fits a task, and rewrite a counting loop from one form into the other.
  3. Change the normal flow of a loop: leave it early, skip the rest of one iteration, and run code only when a loop has finished without being stopped.
    • Leave a loop early with break
      Use break to end a loop as soon as its job is done, including the while True pattern for input loops.
    • Skip to the next iteration with continue
      Use continue to skip the rest of one iteration, avoid its trap in while loops, and tell continue, break and pass apart.
    • Run code when a loop finishes without break
      Attach an else block to a for or while loop to report the case where no break happened, and use a flag variable for the same job.
  4. Use the standard loop patterns to count, total and average values, find the largest and smallest value, and search for items that meet a condition.
    • Count and accumulate values
      Use counters and accumulators to build a count, a total, a product, an average or a piece of text across the iterations of a loop.
    • Find the largest and smallest value
      Track the best value seen so far to find a maximum or minimum, choose a safe starting value, and also record where it occurred.
    • Search for items that meet a condition
      Check items one by one to find a match, decide "not found" only after checking everything, and answer "is there any…?" and "are all…?" questions.
  5. Place one loop inside another to work with rows and columns, combinations and shapes, predict how often the inner body runs, and control both loops.
    • Build a loop inside a loop
      Write nested loops for grids, tables, combinations and growing patterns, and count how many times the inner body runs.
    • Control the flow of nested loops
      Use conditions, break, continue and flags inside nested loops, knowing that each statement affects only its own loop.
  6. Predict exactly what a loop does by tracing it by hand, count its iterations, and find and fix off-by-one errors and other common loop bugs.
    • Trace a loop with a trace table
      Run a loop by hand in a trace table to predict its output, its final values and its number of iterations, and use print statements to trace it automatically.
    • Find and fix off-by-one errors
      Spot loops that run one time too many or too few, use exact rules to count iterations, and fix the boundaries.

Python Loops study guide

6 chapters

1

Repeat actions with while loops

A program can keep asking for input or repeat a calculation until it reaches a target. A while loop makes that possible by checking a condition before each pass through its body. You will connect the starting value, test, and update, then use that structure for input and validation. Following the values as they change also reveals why a loop stops, skips its body entirely, or keeps running without reaching an exit.

1.1 How a while loop repeats work

A loop repeats a block of code. Each pass through the block is an iteration. A while loop checks a condition before every pass and runs its body while that condition is true. This suits a task such as “keep adding until the total reaches 100.”

Start, test, and update

A counting loop needs a starting value, a condition, and an update. The header ends with a colon. Indent the body by four spaces:

n = 3
while n > 0:
    print(n)
    n = n - 1
print("Liftoff!")

The output is:

3
2
1
Liftoff!

At the first check, n > 0 is true because n is 3. Python prints 3, subtracts 1, and returns to the header. It repeats with 2 and then 1. The update makes n equal to 0, so the next check is false. Python skips the body and runs the final print.

Indentation determines what repeats. Both indented lines belong to the body. The last line lines up with while, so it runs once after the loop. An if checks its condition once; while returns to check again after each completed body.

The check happens at the top

Changing a variable does not interrupt the rest of the current body:

n = 1
while n > 0:
    n -= 1
    print("Still in this pass")
print(n)

This prints Still in this pass and then 0, on separate lines. The update makes the condition false, but Python checks it only when it returns to the header. Starting with n = 0 instead would skip the whole body: a while loop can run zero times.

Short updates and changing values

n -= 1 means n = n - 1. Similarly, count += 1 adds 1, balance *= 1.07 multiplies by 1.07, and n //= 10 replaces n with its integer quotient by 10. Python has no increment operator: count++ is a syntax error. Writing ++count applies unary plus twice and leaves the integer unchanged.

Here a loop removes one digit on each pass:

n = 472
total = 0
while n > 0:
    total += n % 10
    n //= 10
print(total)

The remainder n % 10 is the last digit. First, 2 is added and n becomes 47. Next, 7 is added and n becomes 4. Finally, 4 is added and n becomes 0. The output is 13. The update both prepares the next pass and moves toward the exit.

A target loop need not have a count known in advance. Starting with a balance of 1000, multiplying it by 1.07 and increasing a year counter until it reaches 2000 takes 11 passes. After 10 passes the balance is about 1967.15; after 11 it is about 2104.85.

Conditions can combine comparisons with and, or, and not. Truthiness also works: for an integer, while n: repeats while n is nonzero. Use a condition whose meaning is easy to follow. Keep indentation consistent with spaces; mismatched levels can raise IndentationError, and mixed tabs and spaces can raise TabError.

Key Takeaways

  • A while loop checks its condition before each iteration, so its body may run zero times.
  • Initialize before the loop and update inside it to move toward the exit.
  • Lines after an update still run before the condition is checked again.
  • Indentation determines which statements repeat.
  • Use += and -= for updates; Python has no ++ increment operator.

1.2 Why a loop keeps running

An infinite loop keeps repeating without reaching an exit. You might see the same output scrolling or a program appearing to do nothing. To find the cause, follow the values used in the condition and look for a reachable way out.

Find the update

This loop keeps printing 3:

n = 3
while n > 0:
    print(n)

The test stays true because nothing changes n. Add n -= 1 inside the body to make the values 3, 2, and 1 print before the loop stops. Putting that update after the loop does not help: the program cannot reach it while the loop is still running.

The direction matters too. With while n > 0:, an update of n += 1 makes a positive value grow. Python integers do not wrap around at a fixed maximum to provide an accidental exit. Name the change you expect, such as “one fewer attempt remaining,” and check that the code makes that change on each path through the body.

A target can be missed

An update can change the value on every pass and still never reach an equality target:

n = 1
while n != 10:
    print(n)
    n += 2

The values are 1, 3, 5, 7, 9, 11, and so on. They are always odd, so none equals 10. For the task “print odd values below 10,” use while n < 10:. Once n becomes 11, that condition is false. The choice of comparison must match whether the task ends at a value or when a boundary is crossed.

Decimal steps and exact equality

Many decimal fractions are stored approximately as floats. Repeatedly adding 0.1 to 0.0 ten times gives 0.9999999999999999. A loop waiting for exact equality with 1.0 therefore misses its intended stop.

When the task is to visit a fixed set of tenths, count with integers and compute each decimal:

for i in range(11):
    x = i / 10
    print(x)

This visits 11 values from 0.0 through 1.0. The integer count controls the repetitions; the stored decimal does not decide whether the loop should stop.

Check every route through the body

Before running a while loop, locate its starting values, its condition, and every statement that changes those values. Check that the change can make the condition false. If an if skips an update, trace that route too. A temporary line such as print("n =", n) inside the body can show a value that is stuck or moving away from the boundary.

To interrupt a running program, press Ctrl+C in a terminal, or use the editor's Stop or Interrupt button. In a terminal, Python normally reports KeyboardInterrupt with a traceback.

Deliberate repetition

while True: deliberately keeps its header condition true. Its body uses break to leave the loop when an event occurs, such as the user entering “quit.” The exit must be reachable. An input loop may keep waiting because the user has not requested an exit; a bug is a loop whose logic makes the intended exit impossible.

Key Takeaways

  • Check that every repeating path can reach an exit.
  • A missing, misplaced, or wrong-direction update can keep a while loop running.
  • An equality target can be skipped by the step size.
  • Use an integer counter for a fixed number of decimal steps.
  • Ctrl+C or an editor interrupt stops a running program.
  • A deliberate while True loop exits through a reachable break.

1.3 Input loops and acceptable answers

An input loop can collect an unknown amount of data or keep asking until an answer is acceptable. In both cases, the new input must affect the next decision to repeat.

Stop at a sentinel

A sentinel is a special input that means “no more data.” Choose a value that cannot be a genuine data item. For positive counts, 0 can work; if 0 is a valid measurement, choose a different stop signal.

The priming read gets the first value before the condition is checked:

total = 0
number = int(input("Number (0 to stop): "))
while number != 0:
    total += number
    number = int(input("Number (0 to stop): "))
print("Total:", total)

For inputs 4, 7, and 0, the body first adds 4, then adds 7. Reading 0 makes the next condition false. The program prints Total: 11; it never processes the sentinel. If the first input is 0, the body runs zero times and the total stays 0.

The final read inside the body is essential. Without it, the same first value is processed forever. The test must also happen before processing a newly read value: otherwise a sentinel can be counted as data.

Keep types consistent

input() returns text. The string "0" does not equal the integer 0. Convert numeric input with int() before comparing it with a numeric sentinel, or keep the input as text and compare with a string such as "done". A numeric conversion expects a valid numeric string; a range check tests the resulting number.

For an average, keep a counter alongside the total. With sentinel -1 and inputs 8, 6, 10, and -1, the total is 24 and the count is 3. Divide after the loop to get 8.0. If the first input is -1, the count stays 0, so use if count > 0: before division. That handles an empty data set without ZeroDivisionError.

Ask again while an answer is invalid

A validation loop describes the unacceptable answers in its condition:

age = int(input("Age (0-120): "))
while age < 0 or age > 120:
    print("Please enter an age from 0 to 120.")
    age = int(input("Age (0-120): "))
print("Thank you.")

With 150, -2, and 34, the warning appears twice. The value 34 makes both comparisons false, so the loop ends. The endpoints 0 and 120 are accepted too.

The word or matters: an age is invalid if it is below the minimum or above the maximum. Writing age < 0 and age > 120 would reject nothing, because one number cannot be both.

For a yes/no answer, the invalid test is answer != "y" and answer != "n". An answer must differ from both accepted strings to be rejected. With or, even "y" would repeat because it differs from "n". Trace one acceptable and one unacceptable answer to check such a condition.

The same tasks can use while True with one read in the body, followed by an exit test and break. That puts the decision immediately after the input and avoids writing the read twice.

Key Takeaways

  • A sentinel marks the end of data and must be tested before processing.
  • A priming-read loop reads before the loop and again at the end of the body.
  • Compare compatible types: input returns a string.
  • Validation repeats while the current answer is invalid.
  • Check for a positive count before calculating an average.
2

Step through sequences with for loops and range

When a task visits every character, every value in a list, or a known sequence of numbers, a for loop handles the stepping. You can concentrate on the action for each item. A range supplies integer steps without writing a long list. Its start, excluded stop, and step explain both the values visited and the empty cases. Comparing this structure with while loops will help you choose a clear way to express a task.

2.1 Visiting characters and list values

A for loop visits the items of a sequence in order. At each pass, Python assigns the next item to the loop variable and runs the indented body. A loop over a sequence is often called a definite loop because the items give it a defined set of work.

One item at a time

A string is a sequence of characters:

for ch in "cat":
    print(ch)

This prints c, a, and t on separate lines. Spaces and punctuation count as characters too. The string "hi there" has eight characters, including its space, so visiting every character takes eight passes.

A list holds a sequence of values. Its literal form uses square brackets and commas:

scores = [3, 41, 12]
for score in scores:
    print(score * 2)

The output is 6, 82, and 24, each on its own line. score is one number at a time, not the whole list and not its position. No manual counter update is needed to move from 3 to 41 to 12.

Use a name that describes one item: name in names, or score in scores. If the body never needs the current value, _ is a common name for that unused loop variable.

Assignment does not replace an item

The loop variable is an ordinary variable. Assigning a different number to it does not replace the number in the list:

numbers = [1, 2, 3]
for n in numbers:
    n = n * 10
    print(n)
print(numbers)

The body prints 10, 20, and 30. On each new iteration, the next original list item is assigned to n. The final output line is [1, 2, 3]: the list itself has not changed. After the loop, n retains 30, the last value assigned to it in the body.

An empty sequence gives the body no work. With for ch in "":, there are zero passes, and the loop makes no assignment to ch. Do not rely on a loop creating its variable when there might be no items.

Membership inside a loop

In a for header, in introduces the sequence to visit. In a condition, it tests membership and produces True or False. These uses can work together:

vowels = 0
for ch in "education":
    if ch in "aeiou":
        vowels += 1
print(vowels)

Each character is visited, but the counter changes only for e, u, a, i, and o. The output is 5. The if is indented inside the loop, and the counter update is indented inside the if.

This loop also shows why a loop variable and a counter have different jobs. ch holds the current character; vowels records how many characters have met the condition so far. The counter starts before the loop so it keeps its result between passes.

A bare integer cannot supply items: for i in 5: raises TypeError. To repeat an action five times, write for _ in range(5):. The range supplies the steps, even when the body does not use their values.

Key Takeaways

  • A for loop assigns each sequence item to its loop variable in order.
  • Spaces and punctuation are characters in a string.
  • Reassigning a numeric loop variable leaves the original list unchanged.
  • An empty sequence causes zero body executions and no loop-variable assignment.
  • In a condition, in tests membership; in a for header, it introduces the items to visit.
  • Use range(5), not the integer 5, to supply five repetitions.

2.2 Choosing the start, stop, and step of a range

A range describes evenly spaced integers. It is useful for repeating work a set number of times, counting up or down, and selecting regular steps. Its stop value is always excluded.

Three forms
FormMeaningValues
range(5)Start at 0; step by 10, 1, 2, 3, 4
range(2, 6)Start at 2; step by 12, 3, 4, 5
range(1, 10, 2)Start at 1; step by 21, 3, 5, 7, 9

With one argument, that argument is the stop. With two, they are the start and stop. With three, the last argument is the step added after each value. range(0, 10, 3) visits 0, 3, 6, and 9; the next step would reach 12, so it is not supplied.

The stop stays excluded even when a step could land exactly on it. range(0, 10, 5) supplies only 0 and 5. For the default positive step of 1 and a stop above the start, the number of supplied values is the stop minus the start.

Count down with a negative step

range(5, 0, -1) supplies 5, 4, 3, 2, and 1. To include 0, put the stop below it: range(5, -1, -1) supplies six values, ending at 0.

The direction must match the bounds. range(5, 0) is empty because its default step is positive. range(1, 5, -1) is also empty because it starts below the stop but steps downward. Empty ranges are valid and cause zero iterations; a zero step, in contrast, raises ValueError.

Put the last required value inside the boundary

To add the even integers from 2 through 20:

total = 0
for n in range(2, 21, 2):
    total += n
print(total)

The stop of 21 allows 20 to be visited. The ten values total 110, so the program prints 110. Using stop 20 would leave out 20 and give 90.

For a multiplication table, let the range supply the factors:

for i in range(1, 11):
    print(7, "x", i, "=", 7 * i)

The first output line is 7 x 1 = 7, and the tenth is 7 x 10 = 70. If the number itself is unused, for _ in range(3): can repeat a message three times.

Inspect a range and check its arguments

list(range(2, 6)) produces [2, 3, 4, 5], which is useful when checking the bounds. len(range(0, 10, 3)) is 4. A range stores its defining bounds and step instead of building a list containing every integer.

The arguments are integers, including zero and negative integers: range(-3, 3) visits -3 through 2. A float such as 3.0 is rejected with TypeError, even though it has no fractional part. A count entered as text can be converted first with n = int(input("How many? ")), then used in range(n).

Key Takeaways

  • The stop of a range is excluded in every form.
  • A missing start defaults to 0; a missing step defaults to 1.
  • Count down with a negative step and a stop below the start.
  • Bounds that disagree with the step direction produce an empty range.
  • Range arguments must be integers, and its step cannot be zero.
  • Inspect supplied values with list() and their count with len().

2.3 Choosing a loop that matches the task

Choose a loop by asking what controls repetition. If there is a sequence of items to visit, or a count of repetitions, for usually expresses the work directly. If the next repetition depends on a changing condition or a future input, while puts that decision in its header.

Defined items or a changing condition
TaskNatural loopReason
Show every name in a listfor name in names:The list supplies the items.
Repeat a message a user-chosen number of timesfor _ in range(n):The entered number supplies a count.
Read messages until “quit”whileThe stopping point depends on future input.
Grow a balance to a targetwhile balance < target:The current balance decides whether to repeat.

A count need not be written as a literal in the program. After reading n from input, range(n) still gives a definite set of steps. An indefinite loop waits on a condition whose stopping point is not specified as a repetition count.

Guessing a large number of repetitions is a poor fit for “until done.” A loop over range(1000) can exhaust its attempts before the user finishes, and a version without an exit check will continue after the work is complete.

Rewrite a counting loop

These two loops print 1 through 5, each number on its own line:

for i in range(1, 6):
    print(i)
i = 1
while i < 6:
    print(i)
    i += 1

In the while version, the range's start becomes the initialization, the excluded stop becomes the < comparison, and the step becomes the update. The body uses i before that update. Moving the update before print(i) would shift the printed values.

Counting down changes both the comparison and the update:

i = 10
while i > 0:
    print(i)
    i -= 2

This prints 10, 8, 6, 4, and 2, just as for i in range(10, 0, -2): would. The descending range excludes its stop, so the matching while condition is i > 0.

The two forms match the printed counting task; their final loop-variable values differ. The while version performs its last update to 0 before stopping. The for version ends after assigning its last supplied value, 2.

A range keeps the bounds it was given
n = 3
for i in range(n):
    n = 10
    print(i)

This still prints 0, 1, and 2. The range was created using 3; assigning 10 to n does not rebuild it. A break can end the loop early, but changing that separate variable does not change the range's supplied numbers.

A while header, in contrast, evaluates its expression again on each return. If that expression uses n, changing n in the body can change when the loop ends. When both forms express a counting task clearly, the for version handles stepping without a manual update to forget.

Key Takeaways

  • Use for to visit supplied items or a known count, even a count read at run time.
  • Use while when a changing condition or future input controls repetition.
  • A counting-loop conversion must preserve the start, boundary, step, and order of work.
  • Changing a variable used to create a range does not change that range.
3

Control a loop with break, continue and else

A loop normally completes its body and returns for another pass. Sometimes it should stop as soon as a result appears, or skip the current item and keep going. Break and continue express those decisions. A loop can also have an else block for normal completion. Following the exact jump made by each statement will help you read searches, input loops, and limited attempts without confusing an early exit with an ordinary finish.

3.1 Stopping early with break

break ends the innermost loop containing it immediately. Python skips the rest of that body and all remaining iterations, then continues after the loop. A condition inside the body decides when this early exit should happen.

Stop when the first result is found

Search for the first multiple of 7 above 50:

for n in range(51, 100):
    if n % 7 == 0:
        print(n)
        break

The loop checks 51, 52, 53, 54, 55, and 56. The remainder is zero at 56, so Python prints 56 and leaves the loop. It takes six iterations, even though the range can supply 49 numbers. Without break, the loop would also print later multiples of 7.

break is indented inside the if, so it runs only for a match. If it lined up with if instead, it would run on the very first iteration regardless of the test. A break inside an if ends the loop containing that if; it does not merely end the conditional block.

Read once, then decide whether to process

A while True loop places the exit decision after reading input:

while True:
    line = input("> ")
    if line == "done":
        break
    print(line)
print("Done!")

For inputs “hello,” “there,” and “done,” the response lines are:

hello
there
Done!

The sentinel is tested before the processing line. When it appears, break jumps over print(line). The final unindented print still runs after the loop. There is only one input statement, because every pass begins by reading a new line.

A numeric total uses the same order: initialize total = 0 before the loop; read and convert a number; break if it is 0; otherwise add it. For 4, 7, and 0, the total is 11. Processing before the exit test would let the sentinel reach the calculation, which matters when the stop value could alter a count, product, or average.

Validate at the point of input
while True:
    age = int(input("Age: "))
    if 0 <= age <= 120:
        break
    print("Please enter an age from 0 to 120.")
print("Accepted:", age)

The chained comparison accepts an age from 0 through 120. It means 0 <= age and age <= 120. An accepted number exits before the warning; a number outside that range reaches the warning and then another input. In this form the if describes a valid answer, whereas a header-controlled validation loop describes an invalid one.

Read the jump literally

A statement after break in the same block cannot run. Put a message or saved result before the break when it belongs to the successful case. Put code after the loop when it should run after either an early exit or normal completion.

break must be inside a loop; otherwise Python raises SyntaxError. Several separate exit points can make a loop harder to follow. When a single condition naturally describes the task's stopping rule, keeping it in the header can make the path easier to trace.

Key Takeaways

  • Break immediately ends its innermost containing loop.
  • Place the break inside the condition that should cause the exit.
  • A while True input loop reads, tests for the sentinel, and then processes the data.
  • Statements after break in the same block are unreachable.

3.2 Skipping an item with continue

continue skips the rest of the current iteration. The loop remains active: a for loop takes its next item, and a while loop returns to its condition. It is useful when an item should receive none of the processing that follows a check.

Skip selected values
total = 0
for n in range(1, 11):
    if n % 3 == 0:
        continue
    total += n
print(total)

The range supplies all ten integers from 1 through 10. At 3, 6, and 9, continue skips the addition. The sum of all ten is 55; leaving out those three values removes 18, so the program prints 37.

Continue does not remove an iteration from the range. The body still starts with each value, including the skipped ones. It changes which later lines execute on that pass.

A positive filter can express the same work. In a loop over [5, -2, 8, -7, 3], if n < 0: continue followed by print(n) prints 5, 8, and 3. Putting the print inside if n >= 0: gives the same output. Continue is often helpful when several processing lines follow, because rejected items can leave that part of the body immediately.

Do not skip a while update
i = 0
while i < 5:
    if i == 2:
        continue
    print(i)
    i += 1

This prints 0 and 1, then gets stuck at 2. At 2, continue jumps to the condition without reaching the update. The condition stays true, and the same branch is taken again.

To skip printing 2 while still making progress, update on that branch too:

i = 0
while i < 5:
    if i == 2:
        i += 1
        continue
    print(i)
    i += 1

Now the output is 0, 1, 3, and 4 on separate lines. The skipped path advances from 2 to 3. Each route through this body performs exactly one update.

Break, continue, and pass
StatementEffect when reached
breakEnd the containing loop immediately.
continueSkip the rest of this pass and begin the next loop check or item.
passDo nothing; continue to the following statement normally.

For a loop over [1, 2, 3, 4], suppose an if n == 2: contains one of these statements and print(n) follows the if. Break prints only 1. Continue prints 1, 3, and 4. Pass prints all four values because it does not skip the print.

pass can fill a body where Python requires a statement while the code is being developed. It does not provide an update or an exit: while True: pass keeps running. Break and continue must be inside a loop and affect only the innermost loop containing them.

Key Takeaways

  • Continue skips remaining statements on the current pass, then the loop proceeds.
  • A skipped item still counts as an iteration.
  • Every repeating route through a while body must preserve progress toward an exit.
  • Pass does nothing and does not skip later statements.
  • Break ends the loop; continue keeps it active.

3.3 What a loop else means

An else block can belong to a for or while loop. It runs once when the loop finishes normally: a for loop runs out of items, or a while condition becomes false. It is skipped when that loop ends through break. Read it as the no-break case.

Report a search that found no match
for n in [4, 9, 15, 22]:
    if n % 5 == 0:
        print("First multiple of 5:", n)
        break
else:
    print("No multiple of 5")

The loop reaches 15, prints First multiple of 5: 15, and breaks. The else is skipped. With [4, 9, 22], the loop uses every item without breaking and prints No multiple of 5 once.

The alignment is decisive. The else lines up with for, so it belongs to the loop. An else lined up with the inner if would run for each nonmatching item, announcing failure before the search had finished.

An empty list also reaches the loop else. There are no items, so the body runs zero times and there is no break. Likewise, a while loop whose condition is false at its first check runs its else immediately.

Search for a divisor

A prime number is an integer at least 2 whose only positive divisors are 1 and itself. Search for a divisor between those endpoints:

n = 29
if n < 2:
    print("Not prime")
else:
    for d in range(2, n):
        if n % d == 0:
            print(n, "is divisible by", d)
            break
    else:
        print(n, "is prime")

For 29, every remainder is nonzero and the loop else prints 29 is prime. For 21, the first divisor is 3 and the break skips the loop else. The outer check handles numbers below 2. Without it, an empty range for 1 would reach the else and incorrectly call 1 prime. For 2 the range is also empty, but the “prime” conclusion is correct.

Limited attempts with while else
attempts = 0
while attempts < 3:
    guess = input("Password: ")
    if guess == "open sesame":
        print("Welcome!")
        break
    attempts += 1
else:
    print("Too many attempts.")

A correct guess takes the break, even on the third attempt. Three wrong guesses raise the counter to 3; the condition becomes false and the else prints the failure message. An ordinary statement after the loop would run in both cases, so it would not distinguish them.

Record the result with a flag

A flag is a Boolean variable that records whether something happened. Start found = False, change it to True when a match appears, and break. After the loop, if not found: handles failure. That provides the same search outcome as loop else, using an explicit record of the event. Choose a form whose indentation and exit path you can explain clearly.

Key Takeaways

  • A loop else runs on normal completion and is skipped by a break from that loop.
  • An else aligned with an inner if has a different meaning.
  • Zero iterations still reach loop else.
  • A search can report failure once, after every item has failed its test.
  • A Boolean flag can record a result for use after the loop.
  • An empty divisor search needs the separate rule that prime numbers are at least 2.
4

Use standard loop patterns

Many loop tasks follow a small set of reusable patterns. A counter records how often a test passes, an accumulator builds a result, and a best-so-far variable keeps a maximum or minimum. Searches use a similar running record to remember a match. The starting value and the place where it changes determine what the final result means. You will also handle empty data and ties, where a small choice can change the answer.

4.1 Building counts, totals, products, and text

An accumulator keeps a result between iterations. A counter is a particular accumulator that increases by 1 each time an event occurs. Set the starting value before the loop, update inside it, and use the finished result afterward.

Count events or add values
count = 0
for n in [4, 15, 22, 8, 11]:
    if n > 10:
        count += 1
print(count)

The test succeeds for 15, 22, and 11, so the output is 3. The update adds 1 for a matching item; adding n would total the matching values instead.

To sum every item, initialize total = 0, remove the if test, add total += n directly in the body, and print total afterward. The five values total 60. Their average is 60 / 5, which gives 12.0; division with / returns a float for these integer operands.

For a filtered average, update both the total and the count under the same condition:

total = 0
count = 0
for n in [4, 15, 22, 8, 11]:
    if n > 10:
        total += n
        count += 1
if count > 0:
    print(total / count)
else:
    print("No matching values")

Here the selected total is 48 and the count is 3, so the output is 16.0. Dividing by the length of the whole list would use the wrong group. The count check also handles an empty list or a list with no matches.

Choose a starting value that fits the operation
ResultStarting valueUpdate
Count0Add 1 for an event.
Sum0Add each selected value.
Product1Multiply by each selected value.
Text""Join each new piece to the accumulated text.

A product of the integers 1 through 5 starts at 1 and finishes at 120. Starting it at 0 would keep every product at 0.

Text accumulation also depends on order:

rev = ""
for ch in "stressed":
    rev = ch + rev
print(rev)

Each new character goes in front of the saved text, producing desserts. Changing the update to rev = rev + ch adds characters at the end and rebuilds stressed.

Keep the result between iterations

Moving total = 0 inside a sum loop erases the previous work on every pass. With [4, 15, 22, 8, 11], resetting before every addition leaves only 11 at the end. Initialize outside the loop so the next addition uses the previous subtotal.

A print inside the body shows the running total after each update: 4, 19, 41, 49, and 60 in this example. A print after the loop shows only 60. Choose its placement to match the requested output.

For a simple stored list, sum(values) gives its total and len(values) gives its count. An explicit loop lets you filter values, track several results together, or process values as they arrive from input.

Key Takeaways

  • Initialize an accumulator before the loop so it retains earlier work.
  • A counter adds 1 per event; a total adds the value itself.
  • Start sums at 0, products at 1, and text at an empty string.
  • For a filtered average, count and total the same selected values.
  • Check for a nonzero count before division.
  • Print inside for running results and after the loop for a final result.
  • Adding a character before or after the saved text changes its order.

4.2 Keeping the best value seen so far

To find a maximum, keep the largest value seen so far. Compare each new item with that saved value and replace it only when the new item is larger. The minimum pattern works the same way with the comparison reversed.

Start without inventing a data value

None is Python's value for “nothing yet.” It gives the first item a clear way to become the current best:

largest = None
for n in [12, -3, 25, 7]:
    if largest is None or n > largest:
        largest = n
print(largest)

The saved values after each item are 12, 12, 25, and 25. The program prints 25. At the first item, largest is None is true. Python's or stops there, so it does not try the invalid comparison of a number with None. On later passes, the saved value is a number and the second comparison is used.

For a minimum, start smallest = None and use smallest is None or n < smallest. The same list produces -3.

Starting a maximum at 0 can report a value that never appeared. For -5, -2, and -9, no value exceeds 0, so that version would wrongly keep 0. The maximum is -2. Starting a minimum at 0 has the corresponding problem when every item is positive.

If the data is known to contain an item, using that first value as the starting best also works. Built-ins cover simple stored lists: max([12, -3, 25, 7]) gives 25 and min([12, -3, 25, 7]) gives -3. A custom loop can keep related information, such as where the value occurred.

Save the position when the best changes
largest = None
best_day = None
day = 0
for temperature in [18, 23, 21, 26, 24]:
    day += 1
    if largest is None or temperature > largest:
        largest = temperature
        best_day = day
print(largest, best_day)

The day counter advances for every item. The best day changes only when a new maximum appears. The final output is 26 4, meaning a temperature of 26 on day 4. Saving the day after the loop would merely save the last day examined.

Decide what a tie should do

For [5, 8, 8, 3], the test n > largest keeps the first 8 and its position, 2 when counting from 1. Replacing > with >= also updates on an equal value, keeping the last 8 at position 3. The largest number is unchanged; the saved position differs.

An empty list leaves a None-initialized best unchanged. Check for that state before reporting a number or doing arithmetic with it. It means no item has supplied a best value.

The comparison can use a property of an item. To keep the longest word among “pear,” “banana,” and “fig,” compare len(word) with the length of the saved word. “Banana” has six characters, so it wins. Save the word itself when it becomes best so the result identifies the item, not just its length.

Key Takeaways

  • Compare each new item with the best seen so far and replace the best when it improves.
  • None records that no first item has been seen.
  • Short-circuit or avoids comparing the first number with None.
  • Zero is an unsafe general starting value for maxima or minima.
  • Save a position at the same time as its best value.
  • Strict comparison keeps the first tied best; allowing equality keeps the last.

4.3 Searching and remembering a match

A linear search checks items in order until it finds a match or runs out of items. A match may be an exact value, the first item passing a condition, or evidence for an “any” or “all” question.

Remember success
names = ["Ana", "Ben", "Chen"]
found = False
for name in names:
    if name == "Ben":
        found = True
        break
if found:
    print("Ben is on the list")
else:
    print("Ben is not on the list")

The flag starts false because nothing has been found yet. The first check, Ana, leaves it unchanged. The second check finds Ben, sets the flag true, and exits. The output is Ben is on the list.

The flag records an event across the whole search. Do not reset it on each nonmatch. If a loop continues after finding Ben and sets found = False when it reaches Chen, the successful result is lost. Likewise, “not found” belongs after all checks have failed, not inside a per-item else that announces failure for Ana before Ben is examined.

First match or last match

For [7, 4, 9, 10], the first even number is 4 and the last is 10. This loop saves the first one:

match = None
for n in [7, 4, 9, 10]:
    if n % 2 == 0:
        match = n
        break
print(match)

The output is 4. Remove the break and each new match overwrites the previous one, leaving 10. If nothing matches, the saved value remains None. Choose whether the task wants existence, the first item, the last item, or a position before deciding what to store.

To report a position, maintain a counter that advances for every examined item and save it on a match. Say how positions are numbered: counting from 1 makes Chen position 3 in the names list; Python's usual position numbering begins at 0.

Any needs one success; all needs one failure

An “any” search starts false and becomes true at the first item that passes. It can stop there because one success answers the question.

An “all” search starts true and becomes false at the first failure:

all_positive = True
for n in [3, 8, -1, 5]:
    if n <= 0:
        all_positive = False
        break
print(all_positive)

The third value, -1, disproves “all values are positive,” so the output is False. There is no need to inspect 5. Zero would also fail because positive means greater than zero. If there are no items, the flag remains true: no counterexample has appeared.

Exact membership and custom conditions

For equality alone, "Ben" in names directly gives True or False. A loop makes the changing search state visible and lets the test express a custom condition, such as “the first word longer than five characters.”

String comparisons are exact. "ben" differs from "Ben", and "Ben " includes a trailing space. A search for one of those strings must not treat the others as equal.

Key Takeaways

  • A linear search examines items in order until its stopping rule is met.
  • Initialize a found flag once and keep a recorded success.
  • Report not found only after the complete search has failed.
  • Break keeps the first match; overwriting on every match keeps the last.
  • Any stops at a success; all stops at a counterexample.
  • String equality distinguishes case and spaces.
5

Write nested loops

A loop inside another loop can build rows, test combinations, or repeat work for each group. The outer loop chooses one group; the inner loop does its work for that group before the outer loop advances. This structure makes indentation and reset placement especially important. You will count inner executions, build a small grid and a growing shape, and follow early exits that affect one loop or both.

5.1 Rows, combinations, and growing patterns

A nested loop is a loop inside another loop's body. For each outer iteration, the inner loop starts and runs through its work. The outer variable stays fixed while the inner variable changes.

Build one row at a time
for row in range(1, 4):
    for col in range(1, 5):
        print(row * col, end=" ")
    print()

The output has these three rows, each with a trailing space after its last number:

1 2 3 4 
2 4 6 8 
3 6 9 12 

First row is 1, while col takes 1 through 4. Then row becomes 2 and the inner loop begins again at column 1. Finally row 3 gets the same four columns. The inner body executes twelve times.

end=" " replaces print's usual newline with a space. The empty print() ends the row. It is inside the outer body but outside the inner body, so it runs three times. Indenting it one level farther would put every number on its own line. Removing its indentation would end a line only once, after both loops.

Give the loop variables distinct names, such as row and col. Reusing the outer name inside the inner loop overwrites the value needed to identify the current row.

Count the work

When every outer pass gets the same number of inner passes, multiply the counts. Three rows and four columns give twelve inner executions. Two loops with 100 passes each give 10,000 inner executions; three levels give 1,000,000. A small increase in each bound can therefore create much more repeated work.

If the inner bound changes with the outer variable, add the separate counts:

for row in range(1, 5):
    for _ in range(row):
        print("*", end="")
    print()

This prints:

*
**
***
****

The row lengths are 1, 2, 3, and 4, for ten stars in total. For a pattern with n such rows, the total is n(n+1)/2. Multiplying four by four would wrongly assume every row has four stars.

Reset a result for each group

To total each row of the multiplication grid, set row_total = 0 inside the outer loop, just before the inner loop. Add row * col inside the inner body and print row_total after the inner loop. The outputs are 10, 20, and 30.

Initializing only once, before both loops, keeps earlier rows' totals too. Printing after each row then gives 10, 30, and 60. Both placements preserve a result, but one preserves a row result and the other preserves a whole-grid running total.

Visit combinations

Two loops over range(1, 7) visit all 36 ordered outcomes for two dice. The first loop supplies the first die and the second supplies the second die. A condition inside the inner body can count pairs whose sum is 7. Six pass: (1, 6), (2, 5), (3, 4), (4, 3), (5, 2), and (6, 1). Reversing a pair describes a different ordered outcome.

Key Takeaways

  • The inner loop starts again for each outer iteration.
  • Multiply iteration counts only when the inner length stays fixed.
  • Add the row lengths when the inner bound depends on the row.
  • Indentation determines whether an action happens per item, per row, or once overall.
  • Reset a per-row accumulator inside the outer loop before the inner loop.
  • Distinct loop-variable names keep row and column values available.

5.2 Skipping and stopping inside nested loops

Break and continue act on the innermost loop containing them. In nested code, locate that loop before predicting what happens next. A break in the inner body does not by itself stop the outer loop.

Follow an inner break
for a in range(1, 4):
    for b in range(1, 4):
        if b > a:
            break
        print(a, b)

At a = 1, the pair 1 1 prints. When b becomes 2, the break ends that inner loop. The outer loop advances to a = 2 and starts a fresh inner loop at b equal to 1. It prints 2 1 and 2 2, then breaks at b equal to 3. For a equal to 3, every b passes. The six output lines are:

1 1
2 1
2 2
3 1
3 2
3 3
Stop both loops with a recorded result

A search for a combination can use a flag and one break at each level:

found = False
for a in range(1, 6):
    for b in range(1, 6):
        if a * b == 12:
            found = True
            break
    if found:
        break
if found:
    print(a, b)
else:
    print("No matching pair")

Rows a equal to 1 and 2 have no match. On row 3, b reaches 4 and the product is 12. The inner break ends the b loop; the flag then makes the outer break run. The final output is 3 4.

The flag is initialized before both loops, because it records a result for the entire search. The outer if found: belongs after the inner loop but within the outer body. Its indentation gives it one check per completed or interrupted row.

Preserve values when the search continues

Removing only the outer break makes the search continue to later rows. In this example, a later match is 4 3, but the loop eventually examines row 5 and finishes with a = 5 and b = 5. Printing the loop variables then gives 5 5, not a stored match.

If the task needs the last matching pair, save best_a = a and best_b = b whenever a match occurs. Those separate variables retain a match while the loop variables continue changing. Check the found flag before reporting them when a match might not exist.

Skip a pair, then keep the row

A continue inside the inner loop moves to its next inner value. For two loops visiting 1 through 4, if a == b: continue before the processing skips four equal pairs. Twelve ordered pairs remain from the original sixteen.

An if can also select pairs without jumping. Two dice have three ordered pairs with sum 10: (4, 6), (5, 5), and (6, 4). A condition inside the inner body identifies them.

Key Takeaways

  • An inner break ends only the inner loop; an inner continue skips only the current inner pass.
  • A flag and a second break can carry an early exit out of both loops.
  • Place the outer flag check after the inner loop and inside the outer body.
  • Loop variables keep changing after a match unless the search stops; save matching values when needed.
6

Trace and debug loops

A loop can look right while visiting the wrong last value, adding a value too early, or printing one extra separator. Tracing makes its actual behavior visible: record each change in execution order and compare it with the intended result. Tiny examples are especially useful because you can check every pass. You will distinguish body executions from condition checks, inspect final values, and repair boundaries with evidence from a trace.

6.1 Tracing values in execution order

Tracing means running a program by hand, one statement at a time, while recording its values and output. A trace table gives each relevant variable a column. Label whether a value is recorded before or after an update so the rows have a clear meaning.

Trace a while loop
total = 0
i = 1
while i <= 4:
    total = total + i
    i = i + 1
print(total)

Start with total = 0 and i = 1. Check the condition before entering the body. For each true check, run the addition before the increment:

Passi beforetotal afteri after
1112
2233
3364
44105

The next check is 5 <= 4, which is false. There is no fifth body row. The body runs four times, the condition is checked five times, and the print after the loop outputs 10 once. Final values are i = 5 and total = 10.

Keep the failed check distinct from an iteration: it ends the loop without executing its body. If the initial condition is already false, there are no body rows at all and the variables retain their starting values.

Statement order changes the result

If the increment moves above the addition, each pass uses the new i. The four additions become 2, 3, 4, and 5, giving 14. The condition still tests i at the top, before that increment. Tracing only the header values would miss which value the addition actually uses.

When a body contains a break or continue, stop following its remaining lines as soon as the jump occurs. With continue, return to the header or next item; with break, proceed after the loop. A trace must follow those routes, not simply copy all body statements into each row.

Trace characters and nested loops

A for loop assigns the next item at the start of its pass:

rev = ""
for ch in "abc":
    rev = ch + rev
print(rev)

The saved text becomes "a", then "ba", then "cba". The output is cba. Record the actual text, including its order, instead of writing only that “a character was added.”

For nested loops, use one row for each inner iteration. Record both loop variables so the outer value repeats across the rows belonging to it. In a two-row, three-column loop, the row values are 1, 1, 1, 2, 2, 2 while the column values are 1, 2, 3, 1, 2, 3.

Produce a trace with print

A temporary print("i =", i, "total =", total) after both updates in the sum loop displays i and total at the end of each pass. Placing it before the updates displays a different moment. Compare the print's location with your table's column labels. Remove diagnostic prints after fixing the code so they do not become extra program output.

For a “what prints?” question, record only statements that actually print. A variable changing is not itself output; several updates can happen before a single final print.

Key Takeaways

  • Trace statements in the exact order Python executes them.
  • Label recorded values as before or after the relevant update.
  • A normally terminating while loop checks its condition once more than it executes its body.
  • Break and continue change which statements appear in a trace.
  • Track output separately from variable changes.

6.2 Repairing boundaries and separators

An off-by-one error visits one value too many or too few, or shifts the visited values by one. It often comes from a range's excluded stop, a choice between < and <=, or the starting value of a counter.

State the intended endpoints

To add 1 through 10, range(1, 10) is too short. It supplies only 1 through 9, giving a total of 45. range(1, 11) includes 10 and gives 55. For an ascending integer range with step 1, use stop n + 1 to include the final value n.

For a default step of 1, range(a, b) supplies b - a values when b is greater than a. A break can still end the loop before all of them are used. With other step sizes, list the small case or use len(range(...)) to check the count.

A while loop's count depends on its start, comparison, and update together. For a nonnegative integer n, with i += 1 at the end of every pass and no early exit:

Start and conditionBody executions
i = 0; while i < n:n
i = 1; while i <= n:n
i = 0; while i <= n:n + 1

At n equal to 0, the first two skip the body. The third runs once with i equal to 0. This tiny case exposes the extra pass without tracing a long loop.

Countdown boundaries

Starting at 5 and printing before n -= 1, while n > 0: prints five values, ending at 1. Using n >= 0 prints six, ending at 0. The corresponding descending ranges are range(5, 0, -1) and range(5, -1, -1).

Check the order too. Updating a counter before using it can shift every value even when the loop has the expected number of passes. A trace should record the actual first and last values used by the calculation.

Items and the gaps between them

A fencepost error confuses item counts with gap counts. Five fence sections need six posts. Five printed numbers need only four separators between them.

for i in range(1, 6):
    print(i, end="-")

This prints 1-2-3-4-5-, including an unwanted final dash. Each print adds a dash after an item, even the last one.

One repair is to print the first item separately, then print a separator before each later item:

print(1, end="")
for i in range(2, 6):
    print("-" + str(i), end="")
print()

The output is 1-2-3-4-5. The loop prints four dash-and-number pieces, and the final empty print ends the line. This version has a known first item; a general empty-data case must skip that first-item print too.

Check the repair with small cases

Write down the intended first value, last value, and count before changing the code. Choose the bounds and comparison to match them, then trace a short run. Check zero and one item as well as an ordinary case. Zero reveals work that should be skipped; one reveals an unnecessary separator or an extra update. Change the boundary that causes the error so the code's repetition matches the task.

Key Takeaways

  • Check the start, last required value, and number of passes together.
  • An ascending step-one range includes n when its stop is n + 1.
  • The while comparison and update jointly determine its count.
  • Descending ranges also exclude their stop.
  • Item counts and separator counts differ by one for a nonempty sequence.
  • Trace tiny cases, especially zero and one item, after a boundary repair.

Python Loops examples

6 Walkthroughs

1

Make a while loop progress and stop

15 steps
Follow changing values, repair an unreachable target, and collect input without counting the stop signal.
  1. 1
    IntroductionRepetition needs a decision

    A program that keeps asking for an answer needs a rule for another attempt. A while loop puts that rule in a condition checked before each pass.

    You will follow a countdown, find why a changing value can still miss its exit, and build an input loop whose stop signal never reaches its calculations.

  2. 2
    ExplanationSet up the countdown

    A while loop repeats an indented body while its condition is true. Give its controlling value a start before the header:

    remaining = 4
    while remaining > 0:
        print(remaining)
        remaining -= 1
    

    Here the start is 4, the test asks whether any remain, and the update subtracts 1. The print happens before that subtraction.

  3. 3
    ExampleRun the first two passes

    The first test uses remaining equal to 4 and succeeds. The print shows 4, then the update changes remaining to 3. Python returns to the header.

    The next test uses 3, so the body prints 3 and changes the value to 2. The condition is not checked again between the print and the update; those statements run in their written order.

  4. 4
    ExampleReach the failed check

    The next two passes print 2 and 1. After the last update, remaining is 0. The test remaining > 0 is now false, so the body does not run again.

    Four values printed, but the header was checked five times: four true checks and one final false check. Starting with remaining equal to 0 would have given no body passes.

  5. 5
    ChallengeChange the order

    In the countdown, move remaining -= 1 above print(remaining). What four values print, starting from 4?

    ---reveal---

    The output is 3, 2, 1, and 0. Each test still admits the old positive value, but the print uses the updated value. Making the condition false during the body does not interrupt that body; the header will test it on the next return.

  6. 6
    TipFind the missing progress

    If a countdown keeps printing 4, look for the update and its indentation. An update after the loop cannot help the loop finish, because it has not been reached yet.

    If the update adds 1 under while remaining > 0:, the value moves away from the exit. A temporary print after the update shows whether the value changes in the intended direction.

  7. 7
    ExampleChanging can still miss the target
    n = 2
    while n != 7:
        print(n)
        n += 2
    

    This visits 2, 4, 6, 8, and later even numbers. The variable changes every time, yet none of those values equals 7. If the job is to print even values below 7, while n < 7: matches it: the next check fails after n becomes 8.

  8. 8
    ChallengeRepair a skipped target

    A loop starts at 5, prints n while n != 12, and adds 2 at the end. The job is to print its odd values below 12. Why does it fail, and what header fixes it?

    ---reveal---

    The values stay odd and never equal 12. Use while n < 12:. It prints 5, 7, 9, and 11, then stops when n reaches 13. Changing the update to 1 would alter the required odd-number sequence.

  9. 9
    Key InsightCount decimal steps with integers

    Repeated decimal additions can miss an equality target: ten additions of 0.1 to 0.0 give 0.9999999999999999.

    For a fixed sequence of tenths, let integers control the passes:

    for i in range(11):
        x = i / 10
        print(x)
    

    This computes eleven values from 0.0 through 1.0 without asking a stored decimal to reach an exact equality stop.

  10. 10
    ExplanationRead before testing

    A sentinel means “no more data.” For a collection of positive counts, 0 can mark the end. A priming read gets the first number before the loop so its header has a value to test.

    total = 0
    number = int(input("Count (0 to stop): "))
    

    The conversion matters: input returns text, while this loop will compare numbers.

  11. 11
    ExampleProcess then read the next value
    while number != 0:
        total += number
        number = int(input("Count (0 to stop): "))
    print(total)
    

    Attach this below the setup. Inputs 6, 9, and 0 add 6 and then 9, leaving a total of 15. The new 0 fails the next header check before it is added. Without the final read inside the body, the first value would be processed repeatedly.

  12. 12
    ConnectionReject only unacceptable answers

    Input collection stops at a special value. Validation instead repeats until a value is acceptable. To accept an integer from 1 through 5, repeat while choice < 1 or choice > 5 and read a new choice inside the body.

    The condition must describe either violation. Using and would reject nothing: one number cannot be below 1 and above 5 at once.

  13. 13
    ChallengeHandle data and the stop signal

    Scores are nonnegative and -1 is the sentinel. For inputs 0, 9, and -1, what total and count should an average loop use? What if -1 arrives first?

    ---reveal---

    Use total 9 and count 2, giving average 4.5. Zero is data, while -1 is excluded. If -1 is first, count stays 0; report no data instead of dividing. The sentinel check must precede both updates.

  14. 14
    ChallengeCheck a complete input route

    A priming-read loop repeats on text != 0, but text comes directly from input. Entering 0 does not stop it. Explain the type problem and give two valid repairs.

    ---reveal---

    Input supplies "0", a string, which differs from integer 0. Compare with "0" to keep a text sentinel, or convert the input with int before comparing with 0. Both the first read and later reads must preserve that choice.

  15. 15
    RecapFollow one path before running

    For a new while loop, trace an ordinary pass, the intended stopping pass, and a case that should run zero times. On every repeating path, identify the next input or update that permits progress.

    For an input calculation, keep the stop test ahead of processing and decide how empty data should be reported. Those checks catch both a stuck loop and a misleading result.

2

Let items and ranges drive repetition

13 steps
Visit values directly, build ascending and descending ranges, and compare a counted for loop with while.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each item one turn
  2. 2
    ExplanationThe variable holds the current item
  3. 3
    ExampleCharacters include spaces
  4. 4
    ChallengeReassign the item variable
  5. 5
    ExplanationStart at zero when only a stop is given
  6. 6
    ExampleChoose a step and inspect it
  7. 7
    TipDescending values need a negative step
  8. 8
    ChallengeInclude the last required value
  9. 9
    ConnectionMatch the stopping rule to the task
  10. 10
    ExampleTranslate a descending count
  11. 11
    ChallengeA later assignment does not rebuild range
  12. 12
    ChallengeConvert the boundary and keep the data
  13. 13
    RecapCheck the supplied values first
3

Decide what happens after a match or a skip

14 steps
Follow break, continue, and loop else through searches and input loops.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionThree different next steps
  2. 2
    ExplanationBreak leaves the containing loop
  3. 3
    ExampleRead before a middle-of-body exit
  4. 4
    ChallengeLocate the exit
  5. 5
    ExplanationContinue leaves only this pass
  6. 6
    TipA skipped update can trap while
  7. 7
    Key InsightPass does no skipping
  8. 8
    ChallengePredict three versions
  9. 9
    ExplanationElse belongs to the loop
  10. 10
    Key InsightZero passes still finish normally
  11. 11
    ConnectionRecord the same event explicitly
  12. 12
    ChallengeSuccess on the last allowed attempt
  13. 13
    ChallengeCombine skipping with normal completion
  14. 14
    RecapDraw the destination of a jump
4

Build and preserve a loop result

14 steps
Follow a filtered average, a best-value search, and any/all decisions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA result survives the next pass
  2. 2
    ExplanationCount and total the same group
  3. 3
    ExampleFinish the average after collecting
  4. 4
    Key InsightStarting values fit the operation
  5. 5
    ChallengeFind the reset error
  6. 6
    ExplanationTake the first item as the first best
  7. 7
    ExampleSave where the best happened
  8. 8
    ChallengeHandle ties and empty data
  9. 9
    ExplanationA search flag remembers an event
  10. 10
    ExampleAll stops at a counterexample
  11. 11
    ChallengeKeep the first or keep the last
  12. 12
    ConnectionChoose the state the task needs
  13. 13
    ChallengeDescribe an empty filtered result
  14. 14
    RecapName the result before choosing updates
5

Build rows and control a nested search

11 steps
Trace inner restarts, growing work, per-row results, and an exit from both loops.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionOne complete inner run per outer pass
  2. 2
    ExampleKeep the row fixed
  3. 3
    ExplanationEnd each row at the outer level
  4. 4
    Key InsightCount fixed and growing inner work
  5. 5
    ChallengeReset a result per row
  6. 6
    ExplanationAn inner break does not stop the rows
  7. 7
    ExampleCarry success to the outer decision
  8. 8
    TipDo not mistake final variables for a saved match
  9. 9
    ChallengeRemove one exit
  10. 10
    ChallengeCombine a filter and a growing bound
  11. 11
    RecapTrace a row before multiplying counts
6

Trace a boundary error to its cause

10 steps
Record updates in order, distinguish checks from passes, and repair output separators.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the actual work visible
  2. 2
    ExplanationChoose when to record each value
  3. 3
    ExampleFollow all three updates
  4. 4
    ChallengeMove the increment
  5. 5
    TipUse a print as a trace point
  6. 6
    ExampleLet zero expose the extra pass
  7. 7
    ChallengeCheck both ends of a countdown
  8. 8
    ExplanationSeparate items from gaps
  9. 9
    ChallengeAudit a complete repair
  10. 10
    RecapVerify the intended endpoints

Python Loops practice questions

50 Practice Questions in 5 sets

Set 1: Follow the first steps of a loop10 Practice Questions

Question 1 of 10

How many times does the body of this loop run?

for ch in "up! ":
    print(ch)
  1. 2
  2. 3
  3. 4
  4. 5
Show answerHide answer
Answer: C
The string has four characters: two letters, an exclamation point, and a trailing space. The loop visits each character once, including the space. Counting only visible nonspace characters would give 3 and miss an actual iteration of the body.

Question 2 of 10

What values does list(range(3, 12, 4)) contain?
  1. [3, 7]
  2. [3, 7, 11]
  3. [3, 7, 11, 15]
  4. [4, 8, 12]
Show answerHide answer
Answer: B
The start is 3 and each step adds 4, giving 3, 7, and 11 before the next value would exceed the stop. The stop 12 is a boundary, not an extra supplied value. Starting at 4 would confuse the step size with the starting value.

Question 3 of 10

A display must show 8, 6, 4, 2, 0 in that order. What range supplies exactly those values?
  1. range(8, -1, -2)
  2. range(8, 0, -2)
  3. range(8, -2, 2)
  4. range(8, 1, -2)
Show answerHide answer
Answer: A
A step of -2 supplies descending even integers starting at 8, and a stop below 0 allows 0 to be included. With stop 0, the range excludes 0 and ends at 2. A positive step from 8 toward a lower stop would produce no values at all.

Question 4 of 10

What does this program print?

for n in [5, 11, 14, 18]:
    if n % 2 == 0:
        print(n)
        break
print("Finished")
  1. 14, then 18, then Finished
  2. 5, then Finished
  3. Only 14
  4. 14, then Finished
Show answerHide answer
Answer: D
The first even value is 14, so the body prints it and break ends the loop before 18 is examined. Control then reaches the print after the loop, which prints “Finished.” Break stops the containing loop; it does not end the whole program.

Question 5 of 10

What does this program print?

count = 0
for amount in [6, 13, 9, 17]:
    if amount >= 10:
        count += 1
print(count)
  1. 4
  2. 30
  3. 2
  4. 17
Show answerHide answer
Answer: C
Only 13 and 17 satisfy the condition, and each successful test adds 1 to count, so the final result is 2. Adding the matching amounts themselves would produce 30, but this update counts events. Values that fail the test leave the counter unchanged.

Question 6 of 10

How many times does the inner print run?

for row in range(2):
    for col in range(5):
        print("seat")
  1. 10
  2. 7
  3. 5
  4. 25
Show answerHide answer
Answer: A
There are two outer passes, and each begins a complete inner run of five passes. Multiplying the two counts gives ten executions of the print. Adding the counts to get seven would describe two separate loops running in sequence, not this nested structure.

Question 7 of 10

What are the final values of i and total?

i = 1
total = 0
while i < 5:
    i += 1
    total += i
  1. i is 4; total is 10.
  2. i is 5; total is 14.
  3. i is 5; total is 10.
  4. i is 6; total is 20.
Show answerHide answer
Answer: B
The true header checks use i values 1 through 4, but each increment happens before the addition, so total receives 2, 3, 4, and 5. That gives 14, and the next check with i equal to 5 fails. A total of 10 would use each old i instead of the updated value.

Question 8 of 10

What does this program print?

n = 0
while n > 0:
    print("Go")
    n -= 1
print("End")
  1. Go, then End
  2. Only End
  3. Nothing at all
  4. Go repeatedly
Show answerHide answer
Answer: B
The first test, 0 > 0, is false, so Python skips the entire loop body and reaches the final print. A while loop does not promise one pass before checking its condition. The unindented print("End") runs even when the body has no iterations.

Question 9 of 10

Why does this loop keep printing values?

n = 2
while n != 9:
    print(n)
    n += 2
  1. It visits every integer but skips the test.
  2. It resets n to 2 before every comparison.
  3. It stops updating n after it first passes 9.
  4. It visits even values and never reaches 9.
Show answerHide answer
Answer: D
The update visits 2, 4, 6, 8, 10, and later even integers, so n never equals 9. Passing 9 does not make n != 9 false. For the task of visiting these even values below 9, a bound such as n < 9 would stop once the next value crosses it.

Question 10 of 10

A loop reads nonnegative scores and uses -1 to stop. The inputs are 12, 0, 18, -1. What average should it report, excluding the sentinel?
  1. 10.0
  2. 7.25
  3. 15.0
  4. 9.666666666666666
Show answerHide answer
Answer: A
The three data values total 30, and 0 is a valid score, so the count is 3 and the average is 30 / 3, or 10.0. Using a count of 2 would incorrectly discard zero. The sentinel -1 contributes to neither the total nor the count.
Set 2: Keep input and results under control10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A text answer must be exactly "yes" or "no". What while condition asks again for every unacceptable answer and stops for either acceptable one?
  1. answer != "yes" and answer != "no"
  2. answer != "yes" or answer != "no"
  3. answer == "yes" or answer == "no"
  4. answer == "yes" and answer == "no"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

How many items does range(7, 2) supply?
  1. 2
  2. 5
  3. 6
  4. 0
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does this program print?

for n in [2, 5, 8]:
    if n == 5:
        continue
    print(n)
  1. Only 2
  2. 2, then 8
  3. 2, then 5, then 8
  4. Only 8
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does this program print?

for n in []:
    if n == 7:
        break
else:
    print("Absent")
  1. Absent once
  2. Nothing at all
  3. Absent seven times
  4. A TypeError message
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What starting value lets this loop multiply 2, 3, and 4 correctly?

product = ___
for n in [2, 3, 4]:
    product *= n
print(product)
  1. 0
  2. 2
  3. 1
  4. 24
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A maximum search begins with largest = 0 and replaces it only when an item is greater. What value does it incorrectly report for [-8, -3, -6]?
  1. -8
  2. -6
  3. -3
  4. 0
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does this program print?

n = 1
while n > 0:
    n -= 1
    print("Inside")
print(n)
  1. Only 0
  2. Only Inside
  3. Inside, then 0
  4. Inside repeatedly
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

This search has no break. What does it print, and why?

found = False
for label in ["East", "West", "North"]:
    if label == "West":
        found = True
    else:
        found = False
print(found)
  1. True, because a true flag cannot change later.
  2. False, because the final nonmatch resets the flag.
  3. False, because West is not the first item.
  4. True, because the loop stops at the matching label.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

How many pairs are printed?

for a in range(3):
    for b in range(4):
        if b == 2:
            break
        print(a, b)
  1. 2
  2. 9
  3. 6
  4. 12
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A counter starts at i equal to 0. The loop uses while i <= n: and adds 1 at the end of each pass, with no early exit. For every nonnegative integer n, how many body executions occur?
  1. n + 1
  2. n
  3. n - 1
  4. 2n
Show answerHide answer

Save this lesson to see this answer.

Set 3: Choose boundaries and preserve search results10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

How many stars does this program print in total?

for row in range(1, 6):
    for _ in range(row):
        print("*", end="")
    print()
  1. 10
  2. 15
  3. 20
  4. 25
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A loop must add every integer from 1 through 7. What range should supply its values?
  1. range(1, 7)
  2. range(0, 7)
  3. range(2, 8)
  4. range(1, 8)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program must display the tenths from 0.0 through 1.0. What design avoids controlling the loop with repeated floating-point addition and exact equality?
  1. Start x at 0.0 and repeat until x == 1.0.
  2. Count i from 0 through 10 and print i / 10.
  3. Start x at 0.0 and repeat while x != 1.0.
  4. Count i from 0 through 9 and print i / 10.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What final line does this program print?

values = [4, 7]
for value in values:
    value *= 3
print(values)
  1. [12, 21]
  2. [21, 21]
  3. [4, 7, 21]
  4. [4, 7]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What range supplies exactly the integers greater than -6 and at most 6 that are multiples of 3, in descending order?
  1. range(6, -6, -3)
  2. range(6, -7, -3)
  3. range(3, -6, -3)
  4. range(6, -3, -3)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

How many times does this loop print a value?

limit = 4
for i in range(limit):
    limit = 1
    print(i)
  1. 1
  2. 3
  3. 4
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What is the first number printed?

for n in range(32, 50):
    if n % 6 == 0:
        print(n)
        break
  1. 32
  2. 42
  3. 36
  4. 48
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What happens when this program runs?

n = 1
for divisor in range(2, n):
    if n % divisor == 0:
        break
else:
    print("Prime")
  1. It prints nothing because the range is empty.
  2. It prints Prime, incorrectly classifying 1.
  3. It raises an error when range starts above its stop.
  4. It finds divisor 1 and skips the else block.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

The code uses positions numbered from 1. What does it print?

largest = None
best_position = None
position = 0
for n in [9, 14, 6, 14, 8]:
    position += 1
    if largest is None or n >= largest:
        largest = n
        best_position = position
print(best_position)
  1. 2
  2. 5
  3. 3
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An all-positive check starts all_positive = True and changes it to False, then breaks, at the first value n <= 0. For [2, 7, 0, 9, -4], what result and number of examined items does it give?
  1. False after 3 items
  2. False after 5 items
  3. True after 2 items
  4. True after 3 items
Show answerHide answer

Save this lesson to see this answer.

Set 4: Trace updates, filters, and nested exits10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

How many times does the body run, and what final value does amount have?

amount = 3
while amount < 40:
    amount *= 2
  1. 3 passes; amount is 24.
  2. 4 passes; amount is 40.
  3. 5 passes; amount is 96.
  4. 4 passes; amount is 48.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A nonnegative integer is entered first. The loop below should reject values outside 2 through 8, including both endpoints as acceptable. What is wrong with its condition?

value = int(input("Value: "))
while value < 2 and value > 8:
    value = int(input("Value: "))
  1. It accepts only endpoints; replace < with <=.
  2. It rejects nothing; replace and with or.
  3. It rejects every value; replace and with or.
  4. It omits the last read; move the input before while.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

How many vowels does this loop count?

count = 0
for ch in "Orbit":
    if ch in "aeiou":
        count += 1
print(count)
  1. 1
  2. 2
  3. 0
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

The input text values are "6", "4", "stop". What does this program print after the prompts?

total = 0
while True:
    text = input("Amount or stop: ")
    if text == "stop":
        break
    total += int(text)
print(total)
  1. 4
  2. A ValueError message
  3. 10
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does this program print before it gets stuck?

i = 0
while i < 4:
    if i == 1:
        continue
    print(i)
    i += 1
  1. 0, then 1
  2. Only 0
  3. 0, then 2, then 3
  4. Nothing at all
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does this program print?

for n in [3, 8, 5]:
    total = 0
    total += n
print(total)
  1. 16
  2. 13
  3. 0
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does this program print?

match = None
for n in [9, 12, 7, 16, 5]:
    if n % 4 == 0:
        match = n
print(match)
  1. 12
  2. 5
  3. 16
  4. None
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

How many pairs are printed?

for a in range(1, 4):
    for b in range(1, 4):
        if a == b:
            continue
        print(a, b)
  1. 6
  2. 3
  3. 9
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What is the final value of total?

total = 0
for n in range(2, 7):
    if n == 4:
        continue
    total += n
    if total > 9:
        break
  1. 5
  2. 14
  3. 16
  4. 10
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A display has 6 values on one line with a comma only between neighboring values. How many commas should it print?
  1. 6
  2. 5
  3. 7
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine loop patterns and test the edges10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Both loops print 4, 2. What final values do their loop variables have?

for a in range(4, 0, -2):
    print(a)
b = 4
while b > 0:
    print(b)
    b -= 2
  1. a is 0; b is 0.
  2. a is 2; b is 2.
  3. a is 0; b is -2.
  4. a is 2; b is 0.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

In this loop, what is printed?

for n in [3, 6, 9]:
    if n == 6:
        pass
    print(n)
  1. 3, then 9
  2. 3, then 6, then 9
  3. Only 3
  4. Only 6
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A task needs all odd values below 20 starting at 3. This code never stops. What repair preserves those required printed values?

n = 3
while n != 20:
    print(n)
    n += 2
  1. Use while n <= 21:.
  2. Change the starting value to 2.
  3. Use while n < 20:.
  4. Change the update to n += 1.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A user enters an integer n, then a program must print "Ready" exactly n times for nonnegative n. What loop header expresses that count directly?
  1. for _ in range(n):
  2. while n >= 0:
  3. for _ in n:
  4. for _ in range(n + 1):
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The user enters "bad", "bad", then "key". What message prints after these prompts?

attempts = 0
while attempts < 3:
    guess = input("Code: ")
    if guess == "key":
        print("Open")
        break
    attempts += 1
else:
    print("Locked")
  1. Only Locked
  2. Open, then Locked
  3. Nothing at all
  4. Only Open
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A program must keep the first day with the highest temperature. Day numbers begin at 1. What comparison should replace the blank?

highest = None
best_day = None
day = 0
for temp in [-4, -1, -1, -3]:
    day += 1
    if highest is None or ___:
        highest = temp
        best_day = day
  1. temp > highest
  2. temp >= highest
  3. temp < highest
  4. temp <= highest
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does this program print, on two lines?

total = 0
for row in range(1, 3):
    for col in range(1, 4):
        total += row * col
    print(total)
  1. 6, then 12
  2. 6, then 18
  3. 18, then 18
  4. 1, then 4
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What does this nested search print?

found = False
for a in range(1, 5):
    for b in range(1, 5):
        if a + b == 7:
            found = True
            break
    if found:
        break
print(a, b)
  1. 4 3
  2. 4 4
  3. 3 4
  4. 1 4
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What text does this program print?

text = ""
for ch in "lamp":
    if ch == "a":
        continue
    text = ch + text
print(text)
  1. pml
  2. lmp
  3. pmal
  4. mlp
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What average does this program print?

total = 0
count = 0
for n in [3, 11, -1, 14, 6, 20]:
    if n <= 8:
        continue
    total += n
    count += 1
    if count == 2:
        break
if count > 0:
    print(total / count)
  1. 6.25
  2. 15.0
  3. 12.5
  4. 25.0
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

66 Key Terms, each with its definition

A

Accumulator
An accumulator is a variable that preserves and updates a result across iterations, such as a sum, product, or text.
The accumulator total keeps earlier additions when the next measurement arrives.
All check
An all check asks whether every item passes a condition and can finish unsuccessfully at the first failure.
The all check stops at zero when testing whether every recorded value is positive.
Any check
An any check asks whether at least one item passes a condition and can finish successfully as soon as one does.
The any check switches its flag to True at the first score above the required minimum.
Augmented assignment
Augmented assignment combines an operation and assignment, replacing a variable with its updated value.
The augmented assignment total += n adds the current number to the saved subtotal.
Average
An average here is the arithmetic mean, found by dividing the sum of selected values by the number of those values.
The average of the matching scores uses their count, excluding rejected inputs and the sentinel.

B

Boundary case
A boundary case tests an edge of a loop’s intended work, such as zero items, one item, or its final included value.
The boundary case n equal to zero reveals the extra pass caused by testing i <= n.
Break
Break is a Python statement that immediately ends its innermost containing loop and skips its remaining body and iterations.
Break ends the search as soon as the first qualifying value has been printed.

C

Continue
Continue is a Python statement that skips the remaining statements of the current iteration and proceeds to the next one.
Continue skips the addition for a negative value while leaving later values to be examined.
Counter
A counter is an accumulator that increases by one each time a particular event or accepted item occurs.
The counter increases only for scores above the selected threshold, not for every input.
Counting loop
A counting loop visits successive numeric values using a starting value, a boundary test, and a step.
A counting loop that starts at 10 and steps by -2 visits 10, 8, 6, 4, and 2, whether expressed with for or while.

D

Definite loop
A definite loop has a defined sequence of items or a count of repetitions, even when that count is computed at run time.
A definite loop repeats the greeting n times after n has been read from the user.
Diagnostic print
A diagnostic print is a temporary output statement used to inspect program state at a chosen execution point.
A diagnostic print after the updates shows the end-of-pass counter and total.

E

Early exit
An early exit leaves a loop before its normal end, such as when a search takes break after finding a match.
In a loop searching for a multiple of a number, an early exit avoids examining later numbers once the first multiple has been found.
Empty range
An empty range supplies no values because no starting value satisfies its boundary in the direction of its step.
The empty range range(5, 1) gives a for loop no body work and raises no error.

F

Fencepost error
A fencepost error confuses counts of items with counts of boundaries or gaps, such as separators between printed values.
A fencepost error prints six commas after six values when only five internal commas are needed.
Filtering
Filtering selects items that meet a condition so that only those items receive particular processing or contribute to a result.
Filtering out negative values lets the loop total only the accepted measurements.
Final value
A final value is the value a variable holds after the loop ends, which may differ from the last value printed.
When a counting loop prints i and stops once i reaches 5, the final value of i is 5 even though the last printed value was 4.
Flag
A flag is a Boolean variable that records whether an event or condition has occurred for later decisions.
The flag found stays True after a match so the program can report success after searching.
Floating-point approximation
A floating-point approximation stores many decimal fractions as nearby binary values, so repeated additions may not reach an exact target.
Floating-point approximation makes an exact equality stop unreliable after repeated additions of 0.1.
For loop
A for loop assigns successive items from a sequence to a variable and runs its body for each supplied item.
A for loop visits the recorded scores in order and prints twice each current value.

I

Indefinite loop
An indefinite loop repeats according to a condition whose stopping point is not given as a fixed repetition count.
An indefinite loop collects messages until the user types the chosen stop word.
Infinite loop
An infinite loop repeats without reaching an exit through its condition or another control statement.
A loop missing its update becomes an infinite loop that keeps printing the same positive number.
Initialization
Initialization assigns a variable its starting value before a calculation or a repeated process uses it.
Initialization sets the counter to zero before any matching values have been counted.
Inner loop
An inner loop sits within another loop’s body and begins a new run each time execution reaches its header.
The inner loop restarts at column 1 when the multiplication grid advances to a new row.
Innermost loop
The innermost loop is the nearest surrounding loop containing a statement, which is the loop break or continue affects.
The innermost loop moves to its next column when its body executes continue.
Input-validation loop
An input-validation loop repeats a request while the supplied answer fails the conditions for an acceptable value.
An input-validation loop asks again when an entered menu number falls outside 1 through 4.
Iteration
An iteration is one pass through a loop body, during which the statements on the executed path run in order.
Each iteration of a countdown loop prints one number before updating the remaining count.

K

KeyboardInterrupt
KeyboardInterrupt is the interruption Python normally reports when a user stops terminal execution with Ctrl+C.
Stopping a stuck terminal loop with Ctrl+C produces KeyboardInterrupt and a traceback.

L

Linear search
A linear search examines items one by one in their sequence order until it finds the required match or exhausts the items.
A linear search for the first even value in a mixed list stops as soon as it reaches one, such as 8.
Loop
A loop repeats a block of statements according to a condition or a sequence of items that supplies the work.
A countdown loop prints a value and decreases it before deciding whether to repeat.
Loop body
A loop body is the indented block of statements repeated for each item or successful condition check.
In a countdown loop, the loop body contains both the print and the update that moves the count toward zero.
Loop else
A loop else is a block that runs after normal loop completion and is skipped when that loop exits through break.
Loop else prints one failure message after every candidate has been checked without a match.
Loop variable
A loop variable holds the current item assigned by a for loop and can be used by statements in its body.
The loop variable score holds one score at a time, while scores names the full list.

M

Match
A match is an item that satisfies a search condition, which may ask for equality or another property such as divisibility.
When 18 is the first supplied number divisible by 6, the match 18 is saved.
Maximum
A maximum is the largest value in a set of data; a loop can find it by preserving the largest value seen so far.
The maximum of -8, -3, and -6 is -3, even though every candidate is below zero.
Membership test
A membership test checks whether a value occurs in a sequence and produces a Boolean result using in.
The membership test ch in "aeiou" decides whether to increase a vowel counter.
Minimum
A minimum is the smallest value in a set of data; a loop replaces its saved value whenever a smaller item appears.
The minimum temperature becomes -7 when that reading is lower than the saved best.

N

Nested loop
A nested loop is a loop placed inside another loop’s body, allowing inner work to repeat for every outer item.
A nested loop prints a separate set of columns for each row of the multiplication grid.
Nested search
A nested search checks combinations using one loop inside another and may carry a found flag across both levels.
The nested search uses two breaks to stop both loops at its first successful pair.
None
None is Python’s special value for no value, used in a best-value loop to mark that no item has been seen yet.
None remains the saved best when the maximum-search loop receives an empty list.
Normal completion
Normal completion ends a for loop by exhausting its items or a while loop by a false condition, without taking break.
Normal completion of an empty for loop still reaches its else block.

O

Off-by-one error
An off-by-one error gives one extra or missing pass or shifts an intended first or last value by one.
An off-by-one error leaves out 10 when a sum uses range(1, 10).
Ordered pair
An ordered pair records two values with distinct first and second roles, so reversing them can describe another outcome.
The ordered pair (2, 5) for two dice differs from (5, 2) because the first die changes.
Outer loop
An outer loop surrounds another loop and controls which group or row the inner loop processes on each run.
The outer loop keeps row fixed while the inner loop visits every column in that row.

P

Pass
Pass is a Python statement that performs no action and can occupy a block where a statement is required.
Pass fills an unfinished if body, but the print after that if still executes.
Per-row accumulator
A per-row accumulator builds a result for one outer iteration and resets before that iteration’s inner work begins.
The per-row accumulator starts fresh for row 2 so its sum does not include row 1.
Priming read
A priming read obtains the first input before a loop so that its initial condition has a value to examine.
The priming read lets an immediate stop value skip the data-processing body entirely.
Product accumulator
A product accumulator multiplies selected factors into a saved result and normally begins at one to preserve the first factor.
A product accumulator starting at one gives 24 after multiplying 2, 3, and 4.

R

Range
A range describes evenly spaced integers using a start, an excluded stop, and a nonzero step without building a full list.
The range range(2, 11, 2) supplies five even values from 2 through 10.
Running total
A running total is the accumulated sum at a particular stage of processing, before or at the final item.
Printing the running total inside the body shows how each item changes the subtotal.

S

Saved match
A saved match is a separate record of a successful candidate that remains available while current loop variables change.
A saved match of 3 and 4 still holds those values even after the search goes on to examine later pairs.
Sentinel
A sentinel is a special input value that signals the end of data and is kept separate from genuine data items.
The sentinel -1 ends score collection while allowing zero to remain a valid score.
Sentinel-controlled loop
A sentinel-controlled loop repeats input processing until it encounters a designated value that means to stop.
A sentinel-controlled loop can collect an unknown number of positive measurements.
Separator
A separator is text placed between adjacent output items; a nonempty sequence of n items needs n - 1 such gaps filled.
Printing a separator before each later item avoids leaving an extra dash after the last one.
Sequence
A sequence is an ordered collection of items, such as the characters of a string or the values in a list.
The sequence "a b" supplies three characters, including the space between the letters.
Short-circuit evaluation
Short-circuit evaluation skips a Boolean expression’s later part once the result is determined by the earlier part.
Short-circuit evaluation of or avoids comparing a first numeric item with None.
Start
The start of a range is its first candidate integer; it defaults to zero when only the stop is supplied.
A start of 3 makes range(3, 8) begin at 3 instead of the default zero.
Step
The step of a range is the nonzero integer change between consecutive supplied values; it defaults to positive one.
A step of -2 makes range(8, 0, -2) visit descending even values.
Stop
The stop of a range is its excluded boundary, which limits the values supplied in the direction of its step.
A stop of 11 allows range(1, 11) to include 10 as its final supplied value.

T

Termination
Termination is the end of loop execution, reached when repetition stops through a failed condition or an exit statement.
A countdown loop’s termination occurs after the update makes its next condition check false.
Tie
A tie occurs when multiple items have the same best value, so a position search needs a first-or-last choice.
The tie between two scores of 12 keeps the earlier position under a strict greater-than test.
Trace table
A trace table records variable states across loop passes, with columns labeled to identify when values are observed.
The trace table separates i before the body from i after the increment.
Tracing
Tracing follows code statement by statement, recording changes and executed paths to predict its values and output.
Tracing shows that incrementing before addition shifts every value used in the sum.
Type conversion
Type conversion changes a value into another type, such as converting numeric input text to an integer with int.
Type conversion lets the loop compare the entered string "0" with an integer sentinel.

W

While loop
A while loop tests a condition before each pass and repeats its indented body for as long as the condition is true.
A while loop can keep doubling a quantity until it reaches a required minimum.
While True loop
A while True loop has an always-true header and relies on a control statement in its body to exit when needed.
A while True loop reads one line, tests the sentinel, and echoes only genuine data.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started