Python Programming · Week 5

Loops:
while and for

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

This week

Two lines, 300 times

from week 1

import turtle

t = turtle.Turtle()

t.speed(0)

for i in range(300):

t.forward(i * 0.5)

t.left(91)

300 times
The spiral the week-1 code draws

lines that run again and again · a loop

This week

A program that repeats

How many scores? 3

Score 1: 95

Score 2: 150

A score is from 0 to 100.

Score 2: 72

Score 3: 88

Average: 85.0

n = int(input("How many scores? "))

total = 0

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

while score < 0 or score > 100:

print("A score is from 0 to 100.")

score = int(input(f"Score {i}: "))

total += score

print(f"Average: {total / n}")

for one iteration per score

iterations: known, n

while again, until 0 to 100

iterations: not known in advance

two kinds of loops: while and for · this week's topic

while

Back to the condition

if week 4

count = 1

if count <= 3:

print(count)

count = count + 1

print("Done")

1

Done

True False count = 1 count <= 3 print(count)count = count + 1 print("Done")

while

count = 1

while count <= 3:

print(count)

count = count + 1

print("Done")

1

2

3

Done

True False count = 1 count <= 3 print(count)count = count + 1 print("Done")

while: after the block, back to the condition · again and again, while it is True

while

Iteration by iteration

count = 1

while count <= 3:

print(count)

count = count + 1

print("Done")

like if: a condition, a colon, an indented block

trace table

count

count <= 3

printed

1

True

1

2

True

2

3

True

3

4

False

the loop ends · Done

the condition is checked before every iteration · False: the loop ends

while

Repeat n times

n = int(input("How many times? "))

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

←initial value: i starts at 0

←condition: stops when i reaches n

←update: one more, each iteration

How many times? 3

Hello 0

Hello 1

Hello 2

How many times? 5

Hello 0

Hello 1

Hello 2

Hello 3

Hello 4

a counter: initial value · condition · update · as many iterations as you want

while

An infinite loop

n = int(input("How many times? "))

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

i never changes · i < n stays True

n = int(input("How many times? "))

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

not indented: outside the block · never runs

How many times? 3

Hello 0

Hello 0

Hello 0

⋮ forever

^C

KeyboardInterrupt

Ctrl+C stops a running program
on a Mac too: Control, not Command

while True:

print("Hello")

an infinite loop, on purpose

the block must change what the condition checks · or it is an infinite loop

while

Input validation

Ask again until the answer is valid.

score = int(input("Score: "))

while score < 0 or score > 100:

print("A score is from 0 to 100.")

score = int(input("Score: "))

print(f"Your score: {score}")

←before the loop: the first answer

←inside: a new answer, each iteration

Score: 150

A score is from 0 to 100.

Score: -5

A score is from 0 to 100.

Score: 85

Your score: 85

Score: 85

Your score: 85

valid at once: the block runs 0 times

as many iterations as it takes · even none

for

One line with for

with while

n = int(input("How many times? "))

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

How many times? 3

Hello 0

Hello 1

Hello 2

three things to write: initial value · condition · update

with for

n = int(input("How many times? "))

for i in range(n):

print(f"Hello {i}")

How many times? 3

Hello 0

Hello 1

Hello 2

one line · the same output

while: three things to write · for: one line

for

One iteration for each value

range(3) → 012 the values, in order

for i in range(3):i = 0i = 1i = 2

print(f"Hello {i}")

Hello 0

Hello 1

Hello 2

no more values: the loop ends

one iteration for each value · the loop variable i takes the values in turn

for

range

for i in …

i takes

range(5)

01234 5

start 0 · stops before 5

range(1, 6)

12345 6

start 1 · stops before 6

range(0, 10, 2)

02468 10

step 2

range(5, 0, -1)

54321 0

step -1: counting down

the stop value is never included

so 1 to n → range(1, n + 1)

Adding up

Adding up in a loop

total = 0

for i in range(1, 6):

total = total + i

print(total)

←before the loop: initialize to 0

←inside: add i, each iteration

←after the loop: use it

trace table

i

total + i

total

–

–

0

1

0 + 1

1

2

1 + 2

3

3

3 + 3

6

4

6 + 4

10

5

10 + 5

15

initialize before the loop · add inside it · use it after it

Adding up

+=

Augmented assignment: a shorter way to write it.

>>> total = 10

>>> total += 5

>>> total

15

total += 5

is the same as total = total + 5

also -=*=/=//=%=**=

Counting

Counting in a loop

count = 0

for i in range(1, 21):

if i % 3 == 0:

count += 1

print(count)

i from 1 to 20

1
2
3 +1
4
5
6 +1
7
8
9 +1
10
11
12 +1
13
14
15 +1
16
17
18 +1
19
20
6

six multiples of 3 from 1 to 20

a total adds a value · a count adds 1

break, continue

break

total = 0

while True:

text = input("Score (q to stop): ")

if text == "q":

break

total += int(text)

print(f"Total: {total}")

Score (q to stop): 95

Score (q to stop): 72

Score (q to stop): q

Total: 167

←an infinite loop, on purpose

out at once

break: out of the loop at once
to the line after it

break, continue

break or continue

for i in range(1, 8):

if i % 3 == 0:

break

print(i)

print("Done")

out of the loop

1

2

Done

at 3: the loop ends

for i in range(1, 8):

if i % 3 == 0:

continue

print(i)

print("Done")

next iteration

1

2

4

5

7

Done

at 3 and 6: that iteration is skipped

break: leave the loop · continue: go on to the next iteration

Nested loops

A loop inside a loop

print("Hi", end=" ")

print("there")

Hi there

end=" ": a space, not a new line

print() alone: only a new line

for row in range(1, 4):

for col in range(1, 6):

print(row * col, end=" ")

print()

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

inner loop: one row, col 1 to 5

outer loop: 3 rows, row 1 to 3

a loop inside a loop: a nested loop · rows and columns

Nested loops

Rows and columns

for row in range(1, 4):

for col in range(1, 6):

print(row * col, end=" ")

print()

col 1col 2col 3col 4col 5 row 1 12345↵ print() row 2 246810↵ print() row 3 3691215↵ print()

one outer iteration: all 5 inner iterations · 3 × 5 = 15 numbers

Nested loops

Where print() goes

in the inner loop

for row in range(1, 4):

for col in range(1, 6):

print(row * col, end=" ")

print()

1

2

3

4

5

2

⋮

15 lines

in the outer loop

for row in range(1, 4):

for col in range(1, 6):

print(row * col, end=" ")

print()

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

after both loops

for row in range(1, 4):

for col in range(1, 6):

print(row * col, end=" ")

print()

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15

the indent decides which loop print() belongs to

Nested loops

break and continue in a nested loop

outer loop inner loop break outer loop goes on
outer loop inner loop continue inner loop: next iteration

break, continue: the innermost loop only · not every loop at once

Choosing

while or for?

print 1 to 10

for

print Hello n times

for

ask again until the score is valid

while

add scores until the user types q

while

for · iterations known when the loop starts

while · ends when something changes

This week

The whole program

n = int(input("How many scores? "))

total = 0

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

while score < 0 or score > 100:

print("A score is from 0 to 100.")

score = int(input(f"Score {i}: "))

total += score

print(f"Average: {total / n}")

←n: how many iterations

←before the loop: initialize to 0

←for: n iterations · i is 1, 2, …, n

←while: input validation, 0 to 100

←inside: add this score

←after the loop: once

nine lines · every idea on them comes from this video

This week

Which lines run in each iteration

n = int(input("How many scores? "))

total = 0

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

while score < 0 or score > 100:

print("A score is from 0 to 100.")

score = int(input(f"Score {i}: "))

total += score

print(f"Average: {total / n}")

typed 3n is 3 · total is initialized to 0

i 1

typed 95

total 95

i 2

typed 15072

total 167

i 3

typed 88

total 255

no more iterations · Average: 85.0

last week, each line ran at most once
now lines run again, in every iteration

Next steps

Next: the practice video.

Have Python open. Type everything with me.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space