Programming fundamentalsLesson 2 of 2 in the course Loops

Nested Loops: Iteration, Control, and Pattern Generation

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

Lesson progress
0 / 5

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

Summary

Nested loops let a program repeat one process inside another. They are useful when working with combinations of values, such as hours and minutes, names within course rosters, or rows of a pattern.

A nested loop is a loop placed inside the body of another loop. The loop surrounding it is the outer loop; the loop inside it is the inner loop.

For each iteration of the outer loop, the inner loop runs through its complete set of iterations. If the outer loop repeats 3 times and the inner loop runs 4 times per outer iteration, the inner loop's body runs 3×4=123 \times 4 = 12 times in total.

All flashcards

What are the outer loop and inner loop?
The outer loop contains another loop. The inner loop is inside it and completes its iterations for each outer-loop iteration.
Why might an inner `while` loop's counter need to be reset?
Reset it inside the outer loop when the inner process needs to start fresh for each outer iteration.
When is a `for` loop a useful choice?
When iterating over a known range or a container, such as a list.
Can nested loops use different loop types?
Yes. A nested structure can combine `for` and `while` loops.
How can nested loops print a shrinking number triangle?
Use the outer loop to decrease the row length, the inner loop to print numbers up to that length, and a newline after each row.

Quiz questions

  1. What is a nested loop?Answer: A loop placed inside the body of another loop.
  2. What happens to the inner loop during each iteration of the outer loop?Answer: It runs through its full set of iterations.
  3. A nested `while` loop prints minutes 0 and 30 for each of two hours. Why should `minute` be set to 0 inside the outer loop?Answer: To start the minute sequence again for each hour.
  4. If an outer loop iterates 3 times and an inner loop runs 4 times per outer iteration, how many times does the inner-loop body run?Answer: 12 times.
  5. In a nested structure where a `for` loop visits each number in a list and a `while` loop prints even values below that number, what does the `for` loop do?Answer: It visits each number in the list.

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