What does a Python while loop do?
A while loop repeats its indented body as long as its condition remains true.
Study 4 Loops and Iteration with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What does a Python while loop do?
A while loop repeats its indented body as long as its condition remains true.
What does a Python for loop iterate over?
A for loop visits each item supplied by an iterable, such as a list, string, tuple, dictionary, set, or range object.
Why can a while loop run forever?
A while loop may never terminate if its controlling condition never becomes false and no break statement executes.
What is a sentinel in a loop?
A sentinel is a special value that signals the end of input, often allowing a loop to stop with break.
Which values does range(2, 6) supply?
The stop value is excluded. Therefore, range(2, 6) supplies 2, 3, 4, and 5.
What happens when range() has a zero step?
A range with step zero is invalid. A positive-step range can also be empty when start is greater than or equal to stop.
When should you use enumerate()?
Use enumerate() when both the index and the item are needed; it is generally clearer than manually indexing with range(len(...)).
What does break do?
break immediately terminates the innermost enclosing loop, then execution continues with the first statement after that loop.
When does a loop else clause run?
A loop else clause runs when the loop finishes normally, without executing break. For a for loop, this means the iterable is exhausted.
How does a loop accumulate a result?
Initialize the accumulator before the loop and update it during each iteration, such as total += value.
How can a loop count matching items?
Use a counter initialized before the loop, then increment it whenever an item satisfies the condition.
What is a safe way to filter a collection?
Build a new collection, such as with append(), instead of changing the collection currently being traversed.