6 LoopStructure
6 LoopStructure
Paul Kim
So far
• We’ve learned…
• Assignment Statement
• Output Statement
• Input Statement
• File I/O
• Data Types
• Using the knowledges, able to write python
program
• But…
Flow Control
• Statements are always executed sequentially
Python Code
Flow Control
• To have sophisticated program, we need to control
(change) flow of execution
Jump Repeat
Flow Control
• Jump: Decision Structure
• Repeat: Loop Structure
Repeat
Goomba setting example
(with List)
Stage1.py
f=open(“Setting.txt”, “r”)
strLine = f.readline()
goomNames = [] • Repeated code blocks
goomAges = []
#Goomba 1
strLine = f.readline()
gList = strLine.split() • Of course, you can
goomNames.append(gList[0])
goomAges.append(int(gList[1])) manually type the
#Goomba 2 repeated ones
strLine = f.readline()
gList = strLine.split() • Loop structure gives
goomNames.append(gList[0])
goomAges.append(int(gList[1])) you simpler code
#Goomba 3
strLine = f.readline()
gList = strLine.split()
goomNames.append(gList[0])
goomAges.append(int(gList[1]))
f.close()
Loop Structure
• For Loop Statement
• While Loop Statement
• Nested Loop
For Loop
• Basic Syntax
i = 0
for i in [0, 1, 2, 3]: print(i)
print(i) i = 1
print(i)
i = 2
print(i)
i = 3
print(i)
indentation
For Loop
• Of course, you can use list with various types
Output Window
X = 1+2+3+…+9
print(X)
For Loop
• Exercise
• Write a program that performs summation 1+2+3+
…+9
X = 0
X = X + 1
X = X + 2
X = X + 3
...
X = X + 9
print(X)
For Loop
• Exercise
• Write a program that performs summation 1+2+3+
…+9
X = 0
For i in [1,2,3,…,9]:
X = X + i
print(X)
For Loop
• Exercise
• What if we want 1+2+3+…+99?
• Need to write long list
X = 0
For i in [1,2,3,…,9,…,99]:
X = X + i
print(X)
For Loop
• Exercise
• What if we want 1+2+3+…+99?
• Instead use range() function
X = 0
For i in range(100):
X = X + i
print(X)
range()
• Returns sequence of numbers
• range(<stop>)
• Returns sequence of numbers from 0 to <stop> - 1
• Example: range(10)
• Returns sequence of numbers from 0 to 9 (not 10!)
• 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range()
• Returns sequence of numbers
• range(<start>,<stop>)
• Returns sequence of numbers from <start> to <stop> - 1
• range(<start>,<stop>,<step>)
• Returns sequence of numbers from <start> to <stop> - 1
with <step> incrementations
• Example: range(2,10,2)
• Returns sequence of numbers from 2 to 9 with 2
incrementations
• 2, 4, 6, 8
For Loop
• Exercise
• Print Hello World 1000 times using range()
For i in range(1000):
print(“Hello World”)
Goomba setting example
(with List)
f=open(“Setting.txt”, “r”) f=open(“Setting.txt”, “r”)
strLine = f.readline() strLine = f.readline()
goomNames = [] goomNames = []
goomAges = [] goomAges = []
#Goomba 1
strLine = f.readline() for i in range(3):
gList = strLine.split() strLine = f.readline()
goomNames.append(gList[0]) gList = strLine.split()
goomAges.append(int(gList[1])) goomNames.append(gList[0])
goomAges.append(int(gList[1]))
#Goomba 2
strLine = f.readline() f.close()
gList = strLine.split()
goomNames.append(gList[0])
goomAges.append(int(gList[1]))
#Goomba 3
strLine = f.readline()
gList = strLine.split()
goomNames.append(gList[0])
goomAges.append(int(gList[1]))
f.close()
Goomba setting example
(with List) If we have 1,000 goombas…
f=open(“Setting.txt”, “r”) f=open(“Setting.txt”, “r”)
strLine = f.readline() strLine = f.readline()
goomNames = [] goomNames = []
goomAges = [] goomAges = []
#Goomba 1
strLine = f.readline() for i in range(1000):
gList = strLine.split() strLine = f.readline()
goomNames.append(gList[0]) gList = strLine.split()
goomAges.append(int(gList[1])) goomNames.append(gList[0])
goomAges.append(int(gList[1]))
#Goomba 2
strLine = f.readline() f.close()
gList = strLine.split()
goomNames.append(gList[0])
goomAges.append(int(gList[1]))
#Goomba 3
strLine = f.readline()
gList = strLine.split()
goomNames.append(gList[0])
goomAges.append(int(gList[1]))
f.close()
Loop Structure
• For Loop Statement
• While Loop Statement
• Nested Loop
To use for loop
• Using for loop, you can implement repeated
process.
• To use for loop…
• Need to know the number of repetition (iteration)
• Example. Printing “Hello World” five times
for i in range(5):
print(“Hello World”)
To use for loop
• Using for loop, you can implement repeated
process.
• To use for loop…
• Need to know the sequence to iterate over
• Example. Iterating over the list [0, 1, 2, 3]
for i in [0,1,2,3]:
print(i)
While Loop
• Sometimes, you need to repeat process without
knowing details
• Assume that we add numbers from 0 sequentially
until the summed number is less than 100.
• Ex. 0 + 1 + 2 + 3 + 4 + 5 + ………
• What is the smallest number we can have after
passing 100?
While Loop
• What is the smallest number we can have after
passing 100?
• 0=0
• 0+1 = 1
• 0+1+2 = 3
• 0+1+2+3 = 6
....
• 0+1+2+3+4+…+13 = 91
• 0+1+2+3+4+…+13+14 = 105
• Hard to know the number of repetition in advance
• Hard to use for loop to find the answer
While Loop
• One solution: simply repeat adding numbers until it
passes 100
• If need to repeat process while something is
satisfied use While Loop Statement
While Loop
• Basic Syntax
• while <condition>:
<code block>
colon
indentation
• <condition> Boolean expression
(ex. 3<4, 18 != 82,…)
• <code block> repeats while <condition> is satisfied
While Loop
• example
Output Window
i = 0 Hello World
while i<5: Hello World
print(“Hello World”) Hello World
i = i + 1 Hello World
print(“Done”) Hello World
Done
While Loop
• example
Output Window
i=0
i = 0 Hello World
i=1
while i<5: Hello World
i=2
print(“Hello World”) Hello World
i=3
i = i + 1 Hello World
i=4
print(“Done”) Hello World
i=5
Done
While Loop
• One solution: simply repeat adding numbers until it
passes 100
•0=0
• 0+1 = 1
• 0+1+2 = 3
• 0+1+2+3 = 6
...
STOP!
• 0+1+2+3+4+5+ +14 = 105
• How do we represent the above process using
while loop?
Recall
• Recall the summation exercise of for-loop
• 1+2+3+4+5+ +9
X = 0
X = X + 1
X = X + 2
Will borrow this idea
X = X + 3 when writing program
...
X = 0
X = X + 0
X = X + 1
X = X + 2
X = X + 3
X = X + 4
...
While Loop
• One solution: simply repeat adding numbers until it
passes 100
• 0+1+2+3+4+
X = 0 X = 0
X = X + 0 while X<=100:
X = X + 1 X = X + ?
X = X + 2
X = X + 3
X = X + 4
...
While Loop
• One solution: simply repeat adding numbers until it
passes 100
• 0+1+2+3+4+
X = 0 X = 0
X = X + 0 while X<=100:
X = X + 1 X = X + ?
X = X + 2 0, 1, 2, 3, 4,
X = X + 3
X = X + 4
...
X = 0 X = 0
X = X + 0 while X<=100:
X = X + 1 X = X + Y
X = X + 2 Y = Y + 1
X = X + 3
X = X + 4
...
While Loop
• One solution: simply repeat adding numbers until it
passes 100
• 0+1+2+3+4+
X = 0 X = 0
X = X + 0 while X<=100:
X = X + 1 X = X + Y
X = X + 2 Y = Y + 1
X = X + 3 ERROR
X = X + 4
...
X = 0 X = 0
X = X + 0 Y = 0
X = X + 1 while X<=100:
X = X + 2 X = X + Y
X = X + 3 Y = Y + 1
X = X + 4
...
While Loop
• One solution: simply repeat adding numbers until it
passes 100
X = 0
Y = 0
while X<=100:
X = X + Y
Y = Y + 1
print(X)
https://www.youtube.com/watch?v=r11EmY6cKQE
While Loop
• Exercise. Simple Pokemon battle program
• Assumptions
• Simple action: Only Pikachu attacks its enemy
• The enemy has 100 as a full energy (HP)
• Pikachu’s attack damage is random
15
HP: 100
https://www.pinterest.com/pin/16325617382513296/ https://seeklogo.com/vector-logo/298927/psyduck
While Loop
• Exercise. Simple Pokemon battle program
35
HP: 85
https://www.pinterest.com/pin/16325617382513296/ https://seeklogo.com/vector-logo/298927/psyduck
While Loop
• Exercise. Simple Pokemon battle program
HP: 50
https://www.pinterest.com/pin/16325617382513296/ https://seeklogo.com/vector-logo/298927/psyduck
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100
HP: 100
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100 15
attkDamage = pikachuAttack()
HP: 100
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
HP: 85 = 100 - 15
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100 35
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
attkDamage = pikachuAttack()
HP: 85
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
HP: 50 = 85 - 35
While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
...
import random 19
25
for i in range(5): 29
randomInt = random.randint(0, 30) 1
print(randomInt) 17
Random Module
• randint(a, b): returns random number N such as
Output Window
import random 19
25
for i in range(5): 29
randomInt = random.randint(0, 30) 1
print(randomInt) 17
While Loop
• Exercise. Simple Pokemon battle program
enemyEnergy = 100
import random
enemyEnergy = 100
import random
enemyEnergy = 100
enemyEnergy = 100
enemyEnergy = 100
attkCount = 0
i = 0
while i < 2:
for j in [1, 2, 3]:
print(i, “&”, j)
i = i + 1
For Loop Example with
String
• Iterating over String
• Reversing String
Iterating over string
• Since string is sequence of characters, we can
iterate over string using for loop
Hello!
H e l l o !
Iterating over string
• Example
Output Window
testStr = “Hello!” H
for i in testStr: e
print(i) l
l
o
!
Iterating over string
• Example (old-fashioned way)
Output Window
testStr = “Hello!” H
for i in range(6): e
eachChr = testStr[i] l
print(eachChr) l
o
!
testStr = “Hello!” H
for i in range(len(testStr)): e
eachChr = testStr[i] l
print(eachChr) l
o
!
Iterating over string
• Exercise
• Let’s reverse string
• Hello olleH
• PaulKim miKlauP
Reversing String
H e l l o ! H revStr = origStr[0]+revStr
H e l l o ! e H revStr = origStr[1]+revStr
Reversing
origStr
String
revStr
H e l l o ! l e H revStr = origStr[2]+revStr
H e l l o ! l l e H revStr = origStr[3]+revStr
H e l l o ! o l l e H revStr = origStr[4]+revStr
H e l l o ! ! o l l e H revStr = origStr[5]+revStr
Reversing String
origStr = “Hello!” origStr = “Hello!”
revStr = “” revStr = “” len(origStr)
revStr = origStr[3]+revStr
revStr = origStr[4]+revStr
revStr = origStr[5]+revStr
print(revStr)
Reversing String
• Or… just directly iterate over origStr to use
each character
origStr = “Hello!”
revStr = “”
for i in origStr:
revStr = i + revStr
print(revStr)