livepython.net
CHAPTER 10For Loops
10.5  PRACTICE

Python for Loop Practice Questions for Beginners

Chapter 10 Recap and Practice

Your programs can now repeat work. Here is the chapter in one table:

You writeIt does
for name in names:runs the indented block once for every item in the list
for ch in word:goes through a string one character at a time, spaces included
4 spacesthe indentation that puts a line inside the loop
range(5)0, 1, 2, 3, 4: five numbers, starting at 0
range(1, 6)1 to 5: the stop is never included
range(10, 0, -2)10, 8, 6, 4, 2: a step, here counting backwards
for i in range(n): with input() insidereads n lines of input, one per iteration
total = 0 … total += na running total: start before, add inside, print after
count += 1 inside an ifcounts only the items that match
best = items[0] … if x > best:finds the largest value
items.append(x), text += chbuilds a new list or string
a for inside a fora nested loop: the inner one runs fully for each outer item
breakstops the loop at once
continueskips to the next item

And the checklist when a loop misbehaves: the colon, the indentation of each line (inside or after the loop?), the start value set before the loop, and the stop number of range().

Practice questions

Use input() with no prompt text. Many questions first read how many values follow, then read them one per line in a loop. The tests try several inputs, so test your program with a few of your own, including small ones like 0 or 1.

The for loop

  1. 80.Python Program to Print Each Letter of a WordEasySolve
  2. 81.Python Program to Remove Spaces from a SentenceMediumSolve

The range() function

  1. 82.Python Program to Print Numbers from 1 to NEasySolve
  2. 83.Python Program to Print a Multiplication TableEasySolve
  3. 84.Python Program to Print a CountdownMediumSolve

Sums and counters

  1. 85.Python Program to Find the Sum of N NumbersEasySolve
  2. 86.Python Program to Count the Vowels in a WordMediumSolve
  3. 87.Python Program to Find the Largest of N NumbersMediumSolve

Nested loops, break and continue

  1. 88.Python Program to Print a Star TriangleMediumSolve
  2. 89.Python Program to Print Prime Numbers up to NHardSolve

Now your programs can repeat. Next, while loops repeat until a condition changes, even when you don't know how many times in advance.