Python Programming · Week 5
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
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
lines that run again and again · a loop
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
if week 4
count = 1
if count <= 3:
print(count)
count = count + 1
print("Done")
1
Done
while
count = 1
while count <= 3:
print(count)
count = count + 1
print("Done")
1
2
3
Done
while: after the block, back to the condition · again and again, while it is True
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
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
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
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
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 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 i in …
i takes
range(5)
start 0 · stops before 5
range(1, 6)
start 1 · stops before 6
range(0, 10, 2)
step 2
range(5, 0, -1)
step -1: counting down
the stop value is never included
so 1 to n → range(1, n + 1)
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
Augmented assignment: a shorter way to write it.
>>> total = 10
>>> total += 5
>>> total
15
total += 5
is the same as total = total + 5
also -=*=/=//=%=**=
count = 0
for i in range(1, 21):
if i % 3 == 0:
count += 1
print(count)
i from 1 to 20
six multiples of 3 from 1 to 20
a total adds a value · a count adds 1
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
break: out of the loop at once
to the line after it
for i in range(1, 8):
if i % 3 == 0:
break
print(i)
print("Done")
1
2
Done
at 3: the loop ends
for i in range(1, 8):
if i % 3 == 0:
continue
print(i)
print("Done")
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
print("Hi", end=" ")
print("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
for row in range(1, 4):
for col in range(1, 6):
print(row * col, end=" ")
print()
one outer iteration: all 5 inner iterations · 3 × 5 = 15 numbers
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
break, continue: the innermost loop only · not every loop at once
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
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
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
Have Python open. Type everything with me.
See you in class.