0% found this document useful (0 votes)
2 views79 pages

6 LoopStructure

The document discusses loop structures in Python, focusing on the For Loop and While Loop statements. It explains their syntax, usage, and provides examples of how to implement them for repetitive tasks, including exercises for practice. The document also highlights the importance of controlling flow in programming to create more sophisticated applications.

Uploaded by

bambipaga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views79 pages

6 LoopStructure

The document discusses loop structures in Python, focusing on the For Loop and While Loop statements. It explains their syntax, usage, and provides examples of how to implement them for repetitive tasks, including exercises for practice. The document also highlights the importance of controlling flow in programming to create more sophisticated applications.

Uploaded by

bambipaga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

Loop Structure

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

• Will talk about loop structure in this slide


Loop Structure
• Used to repeat some block of code

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

• for <variable> in <sequence>:


<code block>
colon
indentation

• <sequence>  list, string, dictionary,…


For Loop
• Example
Output Window

for i in [0, 1, 2, 3]: 0


print(i) 1
2
3

• Think it as i is iterating over [0,1,2,3]


For Loop
• Example

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)

• Think it as i is iterating over [0,1,2,3]


For Loop
• Inside for loop, indentation is required
Output Window

for i in [0, 1, 2, 3]: 1


x = i + 1 2
print(x) 3
4

indentation
For Loop
• Of course, you can use list with various types
Output Window

for i in [“Hey”, 1, “Aha”]: Hey


print(i) 1
Aha
For Loop
• Inside for loop, indentation is required
Output Window

for i in [0, 1, 2, 3]: 1


x = i + 1 2
print(x) 3
print(“Hello”) 4
Hello
Inside for loop
Outside for loop
For Loop
• Exercise
• Write a program that performs summation 1+2+3+
…+9

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

• Example: range(2, 10)


• Returns sequence of numbers from 2 to 9
• 2, 3, 4, 5, 6, 7, 8, 9
range()
• Returns sequence of numbers

• 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
...

with while loop


X = X + 9
print(X)
While Loop
• One solution: simply repeat adding numbers until it
passes 100
• 0+1+2+3+4+

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
...

Needs new variable Y which will be


incremented by 1 in each iteration
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
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
...

Will give error because Y is not defined


While Loop
• One solution: simply repeat adding numbers until it
passes 100
• 0+1+2+3+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)

• We will have 105 as the result!


While Loop
• Risk of having infinite loop
i = 1
while i > 0:
i = i +
1
• i will always satisfy i > 0  loop does not stop

• Be careful when setting condition of while loop


While Loop
• Exercise. Simple Pokémon battle program

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

• Implement a program where Pikachu repeatedly


attacks an enemy until it has empty energy
While Loop
• Exercise. Simple Pokemon battle program

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
...

Repeats until enemyEnergy is less than or equal to 0 HP: 50


While Loop
• Exercise. Simple Pokemon battle program
• Assume that we have pikachuAttack() function
• pikachuAttack(): returns random attack damage
enemyEnergy = 100 enemyEnergy = 100

attkDamage = pikachuAttack() while enemyEnergy > 0:


enemyEnergy = enemyEnergy - attkDamage attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamag
attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
...
pikachuAttack()
• Generate random number as damage amount after
each call of pikachuAttack()
• Example. 3, 45, 14, 2, 367…

• How to generate random numbers in


Python?
• Use random module
• https://www.pythonforbeginners.com/random/
how-to-use-the-random-module-in-python
Random Module
• Module that includes random number generator
functions
Output Window

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

while enemyEnergy > 0:


attkDamage = pikachuAttack()
enemyEnergy = enemyEnergy - attkDamage
While Loop
• Exercise. Simple Pokemon battle program

import random

enemyEnergy = 100

while enemyEnergy > 0:


attkDamage = random.randint(0,30)
enemyEnergy = enemyEnergy - attkDamage
While Loop
• Exercise. Simple Pokemon battle program
• Let’s print information about this battle

import random

enemyEnergy = 100

while enemyEnergy > 0:


attkDamage = random.randint(0,30)
enemyEnergy = enemyEnergy – attkDamage
print(“Pikachu’s attack damage: ”,attkDamage,
“Enemy’s remaining energy: ”,enemyEnergy)
Output Window

Pikachu's attack damage: 23 Enemy's remaining energy: 77


Pikachu's attack damage: 17 Enemy's remaining energy: 60
Pikachu's attack damage: 26 Enemy's remaining energy: 34
Pikachu's attack damage: 24 Enemy's remaining energy: 10
Pikachu's attack damage: 5 Enemy's remaining energy: 5
Pikachu's attack damage: 18 Enemy's remaining energy: -13
While Loop
• Exercise. Simple Pokemon battle program
• What if we want to know how many times Pikachu
attacked its enemy?
import random

enemyEnergy = 100

while enemyEnergy > 0:


attkDamage = random.randint(0,30)
enemyEnergy = enemyEnergy – attkDamage
print(“Pikachu’s attack damage: ”,attkDamage,
“Enemy’s remaining energy: ”,enemyEnergy)
While Loop
• Exercise. Simple Pokemon battle program
• What if we want to know how many times Pikachu
attacked its enemy?
import random

enemyEnergy = 100
attkCount = 0

while enemyEnergy > 0:


attkDamage = random.randint(0,30)
enemyEnergy = enemyEnergy – attkDamage
attkCount = attkCount + 1

print(“Pikachu’s attack damage:


”,attkDamage,
“Enemy’s remaining energy:
Output Window

Pikachu's attack damage: 23 Enemy's remaining energy: 77


Pikachu's attack damage: 17 Enemy's remaining energy: 60
Pikachu's attack damage: 26 Enemy's remaining energy: 34
Pikachu's attack damage: 24 Enemy's remaining energy: 10
Pikachu's attack damage: 5 Enemy's remaining energy: 5
Pikachu's attack damage: 18 Enemy's remaining energy: -13
Pikachu attacked 6 times.
Loop Structure
• For Loop Statement
• While Loop Statement
• Nested Loop
Nested Loop
• So far, we’ve talked about single loop
• Loop structure with nested loop
 Inside a loop, there is another loop
Output Window
Paul & 1
for i in [“Paul”, “Kim”]:
Paul & 2
for j in [1, 2, 3]:
Paul & 3
Outer Loop print(i, “&”, j)
Inner Loop
Kim & 1
Kim & 2
Kim & 3
Nested Loop
• Multiple loops can be nested
for i in [“Paul”, “Kim”]:
for j in [1, 2, 3]:
for k in [“!”, “$”]:
print(i, “&”, j, “&”, k)

• While loop and for loop can be combined

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
!

• How to avoid typing length of string manually?


• Use len()
Iterating over string
• Example (old-fashioned way)
Output Window

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

origStr revStr origStr = “Hello!”


H e l l o ! Empty String revStr = “”

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[0]+revStr for i in range(6):


revStr = origStr[i]+revStr
revStr = origStr[1]+revStr
print(revStr)
revStr = origStr[2]+revStr

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)

You might also like