Loops in Python
BeginnerLesson 3 of 10 in Python for Beginners: Introduction to Programming
What you will learn
- 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 updatesRead 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 stopsRecognize infinite loops, explain why they happen, fix them, and stop a program that is stuck in one.
- Read input until the user is doneUse while loops to keep reading values until a stop value appears, and to ask again until the user gives an acceptable answer.
- Write a while loop that counts and updates
- 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 sequenceWrite 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 rangeUse 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 loopDecide which kind of loop fits a task, and rewrite a counting loop from one form into the other.
- Loop over the items of a sequence
- 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 breakUse 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 continueUse 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 breakAttach 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.
- Leave a loop early with break
- 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 valuesUse 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 valueTrack 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 conditionCheck items one by one to find a match, decide "not found" only after checking everything, and answer "is there any…?" and "are all…?" questions.
- Count and accumulate values
- 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 loopWrite nested loops for grids, tables, combinations and growing patterns, and count how many times the inner body runs.
- Control the flow of nested loopsUse conditions, break, continue and flags inside nested loops, knowing that each statement affects only its own loop.
- Build a loop inside a loop
- 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 tableRun 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 errorsSpot loops that run one time too many or too few, use exact rules to count iterations, and fix the boundaries.
- Trace a loop with a trace table
Python Loops study guide
1Repeat 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 Trueloop exits through a reachablebreak.
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.
2Step 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,
intests membership; in a for header, it introduces the items to visit. - Use
range(5), not the integer5, 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
| Form | Meaning | Values |
|---|---|---|
range(5) | Start at 0; step by 1 | 0, 1, 2, 3, 4 |
range(2, 6) | Start at 2; step by 1 | 2, 3, 4, 5 |
range(1, 10, 2) | Start at 1; step by 2 | 1, 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 withlen().
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
| Task | Natural loop | Reason |
|---|---|---|
| Show every name in a list | for name in names: | The list supplies the items. |
| Repeat a message a user-chosen number of times | for _ in range(n): | The entered number supplies a count. |
| Read messages until “quit” | while | The stopping point depends on future input. |
| Grow a balance to a target | while 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.
3Control 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
| Statement | Effect when reached |
|---|---|
break | End the containing loop immediately. |
continue | Skip the rest of this pass and begin the next loop check or item. |
pass | Do 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.
4Use 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
| Result | Starting value | Update |
|---|---|---|
| Count | 0 | Add 1 for an event. |
| Sum | 0 | Add each selected value. |
| Product | 1 | Multiply 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
oravoids 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.
5Write 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 . 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.
6Trace 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:
| Pass | i before | total after | i after |
|---|---|---|---|
| 1 | 1 | 1 | 2 |
| 2 | 2 | 3 | 3 |
| 3 | 3 | 6 | 4 |
| 4 | 4 | 10 | 5 |
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 condition | Body 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
1Make a while loop progress and stop
15 steps
- 1IntroductionRepetition 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.
- 2ExplanationSet 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 -= 1Here the start is 4, the test asks whether any remain, and the update subtracts 1. The print happens before that subtraction.
- 3ExampleRun 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.
- 4ExampleReach the failed check
The next two passes print 2 and 1. After the last update, remaining is 0. The test
remaining > 0is 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.
- 5ChallengeChange the order
In the countdown, move
remaining -= 1aboveprint(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.
- 6TipFind 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. - 7ExampleChanging can still miss the target
n = 2 while n != 7: print(n) n += 2This 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. - 8ChallengeRepair 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. - 9Key InsightCount decimal steps with integers
Repeated decimal additions can miss an equality target: ten additions of
0.1to0.0give0.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.
- 10ExplanationRead 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.
- 11ExampleProcess 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.
- 12ConnectionReject 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 > 5and 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.
- 13ChallengeHandle 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.
- 14ChallengeCheck 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. - 15RecapFollow 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.
2Let items and ranges drive repetition
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each item one turn
- 2ExplanationThe variable holds the current item
- 3ExampleCharacters include spaces
- 4ChallengeReassign the item variable
- 5ExplanationStart at zero when only a stop is given
- 6ExampleChoose a step and inspect it
- 7TipDescending values need a negative step
- 8ChallengeInclude the last required value
- 9ConnectionMatch the stopping rule to the task
- 10ExampleTranslate a descending count
- 11ChallengeA later assignment does not rebuild range
- 12ChallengeConvert the boundary and keep the data
- 13RecapCheck the supplied values first
3Decide what happens after a match or a skip
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionThree different next steps
- 2ExplanationBreak leaves the containing loop
- 3ExampleRead before a middle-of-body exit
- 4ChallengeLocate the exit
- 5ExplanationContinue leaves only this pass
- 6TipA skipped update can trap while
- 7Key InsightPass does no skipping
- 8ChallengePredict three versions
- 9ExplanationElse belongs to the loop
- 10Key InsightZero passes still finish normally
- 11ConnectionRecord the same event explicitly
- 12ChallengeSuccess on the last allowed attempt
- 13ChallengeCombine skipping with normal completion
- 14RecapDraw the destination of a jump
4Build and preserve a loop result
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA result survives the next pass
- 2ExplanationCount and total the same group
- 3ExampleFinish the average after collecting
- 4Key InsightStarting values fit the operation
- 5ChallengeFind the reset error
- 6ExplanationTake the first item as the first best
- 7ExampleSave where the best happened
- 8ChallengeHandle ties and empty data
- 9ExplanationA search flag remembers an event
- 10ExampleAll stops at a counterexample
- 11ChallengeKeep the first or keep the last
- 12ConnectionChoose the state the task needs
- 13ChallengeDescribe an empty filtered result
- 14RecapName the result before choosing updates
5Build rows and control a nested search
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionOne complete inner run per outer pass
- 2ExampleKeep the row fixed
- 3ExplanationEnd each row at the outer level
- 4Key InsightCount fixed and growing inner work
- 5ChallengeReset a result per row
- 6ExplanationAn inner break does not stop the rows
- 7ExampleCarry success to the outer decision
- 8TipDo not mistake final variables for a saved match
- 9ChallengeRemove one exit
- 10ChallengeCombine a filter and a growing bound
- 11RecapTrace a row before multiplying counts
6Trace a boundary error to its cause
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the actual work visible
- 2ExplanationChoose when to record each value
- 3ExampleFollow all three updates
- 4ChallengeMove the increment
- 5TipUse a print as a trace point
- 6ExampleLet zero expose the extra pass
- 7ChallengeCheck both ends of a countdown
- 8ExplanationSeparate items from gaps
- 9ChallengeAudit a complete repair
- 10RecapVerify the intended endpoints
Python Loops practice questions
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)
Show answerHide answer
Question 2 of 10
list(range(3, 12, 4)) contain?Show answerHide answer
Question 3 of 10
Show answerHide answer
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")
Show answerHide answer
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)
Show answerHide answer
Question 6 of 10
How many times does the inner print run?
for row in range(2):
for col in range(5):
print("seat")
Show answerHide answer
Question 7 of 10
What are the final values of i and total?
i = 1
total = 0
while i < 5:
i += 1
total += i
Show answerHide answer
Question 8 of 10
What does this program print?
n = 0
while n > 0:
print("Go")
n -= 1
print("End")
Show answerHide answer
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
Show answerHide answer
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
Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
range(7, 2) supply?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)
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")
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)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
largest = 0 and replaces it only when an item is greater. What value does it incorrectly report for [-8, -3, -6]?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)
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)
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)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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()
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 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)
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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)
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
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")
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)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
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: "))
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)
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)
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
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)
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)
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)
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
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
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)
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
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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")
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
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)
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)
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)
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)
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
All check
Any check
Augmented assignment
total += n adds the current number to the saved subtotal.Average
B
Boundary case
Break
C
Continue
Counter
Counting loop
D
Definite loop
Diagnostic print
E
Early exit
Empty range
range(5, 1) gives a for loop no body work and raises no error.F
Fencepost error
Filtering
Final value
Flag
Floating-point approximation
For loop
I
Indefinite loop
Infinite loop
Initialization
Inner loop
Innermost loop
Input-validation loop
Iteration
K
KeyboardInterrupt
L
Linear search
Loop
Loop body
Loop else
Loop variable
M
Match
Maximum
Membership test
ch in "aeiou" decides whether to increase a vowel counter.Minimum
N
Nested loop
Nested search
None
Normal completion
O
Off-by-one error
Ordered pair
Outer loop
P
Pass
Per-row accumulator
Priming read
Product accumulator
R
Range
range(2, 11, 2) supplies five even values from 2 through 10.Running total
S
Saved match
Sentinel
Sentinel-controlled loop
Separator
Sequence
Short-circuit evaluation
Start
range(3, 8) begin at 3 instead of the default zero.Step
range(8, 0, -2) visit descending even values.Stop
range(1, 11) to include 10 as its final supplied value.T
Termination
Tie
Trace table
Tracing
Type conversion
W
While loop
While True loop
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.