Programming fundamentalsLesson 2 of 5 in the course Loops

Python for Loops: Iteration and range()

5 flashcards · 5 quiz questions · 5 match pairs · 5 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

A for loop repeats a block of code once for each item in a container or sequence. In Python, this makes it useful both for processing collections of values and for repeating a task a specific number of times.

A container is an object that holds or provides a sequence of items. Examples include strings, lists, and ranges. A for loop takes each item in turn, assigns it to a loop variable, and runs the indented loop body.

All flashcards

What is a for loop?
A control structure that runs its indented body once for each item in an iterable sequence or container.
How does a for loop iterate over a string?
It assigns each character in turn to the loop variable. Spaces are characters too, so they are visited and can be counted.
What are the start and end rules for range()?
The start value is included, while the end value is excluded. The step determines how the sequence advances.
How does range(start, end, step) count downward?
Give it a negative step, such as range(3, -2, -1), which produces 3, 2, 1, 0, and -1; the end is still excluded.
How can a program count spaces in a string?
Initialize a counter, loop through each character, increase the counter when the character equals a space, and print the counter.

Quiz questions

  1. What does a while loop generally require that a for loop using range() can express directly?Answer: An initialization, a condition, and an update.
  2. In a Python loop over the string "A B", what does the loop variable represent on each iteration?Answer: One character at a time, including the space.
  3. Which values are produced by range(2, 6)?Answer: 2, 3, 4, and 5.
  4. What does range(10, 0, -4) produce?Answer: 10, 6, and 2.
  5. A task requires generating sequences only when n1 < n2. What should a program do if n1 is not less than n2?Answer: Report an error instead of generating the sequences.

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons