Python Programming · Week 5

Loops: while and for
Practice

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Setup

Before we start

The same steps as last week.

  1. 1 VS Code → open your python_course folder
  2. 2 New Folder → week05
  3. 3 Terminal → python3 → the >>> prompt

This video is all typing. Pause whenever you need to catch up.

Drill

Trace first, then run

On paper: what comes out? Then type it at the prompt. An empty line runs the loop.

>>>for i in range(1, 10, 3):

... print(i)

...

>>>x = 1

>>>while x < 50:

... x = x * 2

...

>>>x

>>>total = 0

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

... if i == 3:

... continue

... total += i

...

>>>total

Files

Now a file: avg.py

In your week05 folder: the nine lines from the theory video.

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

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

run again0 and 100 are scores too

How many scores? 2

Score 1: 0

Score 2: 100

Average: 50.0

Debugger

Watch a loop, one line at a time

A new file, total.py: the sum of 1 to 5 from the theory video.

1total = 0

2for i in range(1, 6):

3 total = total + i

4print(total)

what VARIABLES shows, in each iteration

i 12345 total 1361015
  1. 1 click just left of line 1's number: a red dot, a breakpoint (stop here)
  2. 2 the small arrow next to ▷ (top right) → Python Debugger: Debug Python File
  3. 3 the program stops at line 1 · VARIABLES on the left
  4. 4 Step Over (F10) again and again: one line each time · watch i and total
  5. 5 ■ Stop · or ▷ Continue to run to the end
  6. Mac: F10 may need fn · or click the Step Over icon (a curved arrow over a dot)

the trace table from the theory video · live, one step at a time

Drill

Break three things

In avg.py, on purpose. After each one, undo it: ⌘Z (Windows: Ctrl+Z).

avg.py, line 7

delete the line that asks again · type 3, 95, 150

A score is from 0 to 100. (again and again)

stop it with Ctrl+C

infinite loop

avg.py, line 3

change n + 1 to n · type 3, 95, 72

Average: 55.666666666666664

an off-by-one error: Score 3 is never asked

silent

avg.py, line 9

indent the last line · type 3, 95, 72, 88

Average: 31.666666666666668 … after every score

inside the loop now

silent

an infinite loop: Ctrl+C · two silent wrong answers: the worst case

Files

Add the highest score

Four new lines in avg.py.

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

total = 0

highest = 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

if score > highest:

highest = score

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

print(f"Highest: {highest}")

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

Highest: 95

the maximum: start low, replace when bigger
0 is low enough: every score is from 0 to 100

Example · 1

Digit sum

digits.py

Ask for an integer, 0 or more. Print the sum of its digits.

n % 10: the remainder, the last digit · n // 10: the quotient, n without its last digit

on the screen

Number: 2026

Digit sum: 10

Number: 99999

Digit sum: 45

the code

n = int(input("Number: "))
total = 0
while n > 0:
    total += n % 10
    n = n // 10
print(f"Digit sum: {total}")
Example · 2

A number triangle

triangle.py

Ask for a number of rows. Row 1 shows 1, row 2 shows 1 2, row 3 shows 1 2 3, and so on.

each row is a loop of its own: a loop inside a loop

on the screen

Rows: 4

1

1 2

1 2 3

1 2 3 4

the code

n = int(input("Rows: "))
for row in range(1, n + 1):
    for k in range(1, row + 1):
        print(k, end=" ")
    print()
Example · 3

Is it prime?

prime.py

Ask for an integer, 2 or more. Print whether it is prime: divisible only by 1 and by itself.

count the divisors from 1 to n · a prime has exactly 2

on the screen

Number: 7

7 is prime

Number: 91

91 is not prime

the code

n = int(input("Number: "))
count = 0
for d in range(1, n + 1):
    if n % d == 0:
        count += 1
if count == 2:
    print(f"{n} is prime")
else:
    print(f"{n} is not prime")
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

the values after the prompts are typed · the prompt words are up to you

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

the values after the prompts are typed · the prompt words are up to you

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

the values after the prompts are typed · the prompt words are up to you

examples · typed values in order

typed

prints

1

Prime #1: 2

5

Prime #5: 11

10

Prime #10: 29

100

Prime #100: 541

Exercise 4

How to submit

  1. 1 download week05_exercise.zip from e-Class · unzip it: three files, one per problem
  2. 2 put the three files in python_course/week05 · open them in VS Code
  3. 3 in each file: write the code · save · run it and try every example
  4. 4 zip the three files · upload the zip on e-Class · the deadline is in the post
10 points: 2 · 3 · 5attempted: full points, right or wronglate: half the pointsAI: allowed, but try alone first

Next steps

Now: exercise 4.

Before class. Everything you need is on e-Class.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space