Back

Activity 1.16: For Loops

divider

Activity 1.16

For Loops

Key Concepts

The for Loop

range()

Counting a Known Number of Times

When you already know how many times to repeat something, a while loop needs some bookkeeping.

i = 0
while i < 5:
print(i)
i = i + 1

The for Loop

A for loop does that counting for you.

for i in range(5):
print(i)

Same result as the while version — no counter variable to manage yourself.

The for Loop

Terminal window
0
1
2
3
4

range()

range(5) counts 0 through 4 — 5 numbers, starting at 0. range(start, stop) lets you pick both ends.

for i in range(1, 11):
print(i)

Counts 1 through 10.

Counting Backwards

A third number in range() sets the step — negative counts down.

for i in range(10, 0, -1):
print(i)

Counts 10 down to 1.

Today's Objectives

  • Writing a for loop with range()
  • Choosing between range(n) and range(start, stop)
  • Printing on the same line with end=" "

Key Terms

for Loop
Repeats its block once for each value in a sequence.
range()
Generates a sequence of numbers for a for loop to count through.

'F' → Fullscreen

divider

Build

Create a new Python program named 1-16-for-loops.


Task 1: Counting Multiples

  • Ask for a number and a count, then print that many multiples of it, one per line.
For Loops
number = int(input("Choose a number: "))
count = int(input("List how many multiples of the number? "))
total = number # Tracks the current multiple
for i in range(count):
print(total)
total = total + number
input("Press enter to continue...")

Task 2: Display on One Line

  • Change the loop to print the multiples on a single line, separated by spaces.
For Loops
number = int(input("Choose a number: "))
count = int(input("List how many multiples of the number? "))
total = number # Tracks the current multiple
for i in range(count):
print(total, end=" ")
total = total + number
print()
input("Press enter to continue...")
divider

Checkpoint

Verify your program works correctly.

Example Output
Choose a number: 3 [Enter]
List how many multiples of the number? 5 [Enter]
3 6 9 12 15
Press enter to continue...
divider

Reflection

Answer the following questions before submitting your work.

  1. What does range(count) actually produce, and what does the loop use it for if i is never printed?
  2. Why doesn't a for loop need you to write your own counter variable and increment it, the way a while loop does?
  3. What does end=" " change about how print() behaves?
divider

Submit

Submit the required files to the appropriate dropbox.

Activity Complete