Python Programming · Week 5

Loops: while and for
In class

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Today

Three things

  1. 1 Recap and quiz: the week 5 videos
  2. 2 Exercise 4: all three problems, solved live
  3. 3 A first look at week 6
Recap · 1

while: back to the condition

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")

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

Recap · 2

A counter: three parts

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

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

←initial value

←condition

←update

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

i = 0

while i < n:

print(f"Hello {i}")

i = i + 1

no update: i < n stays True

How many times? 3

Hello 0

Hello 0

⋮ forever

^C

KeyboardInterrupt

Ctrl+C stops a running program

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

Recap · 3

Input validation

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}")

←ask once, before the loop

←while the answer is not valid

←ask again, inside

Score: 150

A score is from 0 to 100.

Score: 85

Your score: 85

ask once before the loop · ask again inside it, until the answer is valid

Recap · 4

for: one iteration for each value

for i in …i takes

range(5)

01234 5

range(1, 6)

12345 6

range(0, 10, 2)

02468 10

range(5, 0, -1)

54321 0

the stop value is never included

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

Recap · 5

Adding up and counting

a total adds a value

total = 0

for i in range(1, 6):

total += i

print(total)

15

a count adds 1

count = 0

for i in range(1, 21):

if i % 3 == 0:

count += 1

print(count)

6

total += i is total = total + i·also -=*=/=//=%=**=

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

Recap · 6

A loop inside a loop

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

Recap · 7

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

for i in range(1, 8):

if i % 3 == 0:

continue

print(i)

print("Done")

next iteration

1

2

4

5

7

Done

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

a loop inside a loop: only the innermost loop

Recap · 8

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

Quiz

What comes out?

No computer. Say the answer, then I press Enter.

1

>>>for i in range(10, 0, -3):

... print(i)

...

2

>>>n = 10

>>>while n > 0:

... n -= 4

...

>>>n

3

>>>total = 0

>>>for i in range(4):

... total += i

...

>>>total

4

>>>for i in range(3):

... for j in range(3):

... if j == 1:

... break

... print(f"{i}{j}")

...

5

>>>count = 0

>>>for i in range(1, 4):

... for j in range(i):

... count += 1

...

>>>count

Exercise 4 · Problem 1

Times table

week05_problem1.py 2 points

Ask for a number from 2 to 9. Anything else: From 2 to 9, please. and ask again, until it is. Then print its times table, from n x 1 up to n x 9.

on the screen · one run

Number (2 to 9): 12

From 2 to 9, please.

Number (2 to 9): 7

7 x 1 = 7

7 x 2 = 14

7 x 3 = 21

7 x 4 = 28

7 x 5 = 35

7 x 6 = 42

7 x 7 = 49

7 x 8 = 56

7 x 9 = 63

examples · typed values in order

typed

prints

7

7 x 1 = 7 … 7 x 9 = 63

12, 3

From 2 to 9, please. then 3 x 1 = 3 … 3 x 9 = 27

1, 0, 9

the message twice, then 9 x 1 = 9 … 9 x 9 = 81

Exercise 4 · Problem 2

Fibonacci numbers

week05_problem2.py 3 points

Ask for n (1 or more). Print the first n Fibonacci numbers on one line. The first two are 1 and 1. Each next number is the sum of the two before it. Hint: keep the last two numbers in two variables.

on the screen · one run

How many? 10

1 1 2 3 5 8 13 21 34 55

examples · typed values in order

typed

prints

1

1

2

1 1

10

1 1 2 3 5 8 13 21 34 55

15

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Exercise 4 · Problem 3

The n-th prime

week05_problem3.py 5 points

Ask for n (1 or more). Print the n-th prime number: 2, 3, 5, 7, 11, 13, … Hint: example 3 checks one number. Check 2, 3, 4, … in turn, count the primes, and stop when the count reaches n.

on the screen · one run

n: 10

Prime #10: 29

examples · typed values in order

typed

prints

1

Prime #1: 2

5

Prime #5: 11

10

Prime #10: 29

100

Prime #100: 541

Next week

Week 6: Functions

Videos and exercise 5: up Tuesday–Wednesday.
Exercise 5: due Monday, October 12, 11:59 a.m.
Midterm: Monday, October 26, 8:00–8:50 a.m.

Slides: hyeongminlee.github.io/slides/python-programming

← All weeks
01 / 00
Scroll · ↓ · Space