Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • write basic for loops with range
  • iterate over strings/lists directly
  • compare for and while usage

Syntax

for variable in iterable:
    # body

First examples

for i in range(5):
    print(i)
Output: 0 1 2 3 4
for ch in "python":
    print(ch)

for vs while

Use for when:
  • number of iterations is known
  • iterating over sequence elements
Use while when:
  • loop depends on dynamic condition
  • iterations are unknown in advance

range quick forms

  • range(stop) -> 0 to stop-1
  • range(start, stop) -> start to stop-1
  • range(start, stop, step) -> controlled step

Dry run

for i in range(2, 8, 2):
    print(i)
Output: 2 4 6

Exam hints and traps

  • range(1, 5) does not include 5
  • negative step requires descending boundaries
  • variable updates automatically in for

Practice

  1. Print numbers 1 to 10 using for.
  2. Print characters of "code" one per line.
  3. Predict output:
for i in range(5, 0, -2):
    print(i)

Answers

for i in range(1, 11):
    print(i)
for ch in "code":
    print(ch)
  1. 5 3 1