Lesson 15 of 34

Loop Patterns: Totals, Counts and Shapes

10 min 35 XP

Pattern 1, the accumulator: set total = 0 before the loop and add to it in every round.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Pattern 2, the counter: add 1 to count only when a condition is true.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Pattern 3, shapes: "*" * 3 gives "***". Combine it with a loop to draw shapes.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Master these three patterns and many coding interview questions become easy.

Challenge

+35 XP

With n = 4, print this triangle: * ** *** ****

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.