Professional Documents
Culture Documents
Sudharshan Welihinda(weli@iit.ac.lk)
Senior Lecturer, Department of Computing
Informatics Institute of Technology
Lecture 9
1
How To Determine If Loops Can Be Applied?
END GAME
Re-running the entire
program Pseudo code
While the player wants to play
Run the game again
slide 2 James Tam
Loops In Python
1. While
2. For
Characteristics:
1. The stopping condition is checked before the body executes.
2. These types of loops execute zero or more times.
Syntax :
(Simple condition)
(Compound condition)
i = 0
2) Check condition is No
while (i <= 3): i <= 3?
print("i =", i)
Yes
i = i + 1 3) Execute body
print i
print("Done!")
4) Update control
Let i = i + 1
No
print("Done!") Is i <= 3?
Execution : Yes
Print i
Variable i 0
is i <= 3? Yes
Let i = i + 1
Print i 0
i = i + 1 1
No
print("Done!") Is i <= 3?
Execution : Yes
Print i
Variable i 0 1 2 3 4
is i <= 3? Yes Yes
Let i = i + 1
Print i 0 1
i = i + 1 1 2
No
print("Done!") Is i <= 3?
Execution : Yes
Print i
Variable i 0 1 2 3 4
is i <= 3? Yes Yes Yes
Let i = i + 1
Print i 0 1 2
i = i + 1 1 2 3
No
print("Done!") Is i <= 3?
Execution : Yes
Print i
Variable i 0 1 2 3 4
is i <= 3? Yes Yes Yes Yes
Let i = i + 1
Print i 0 1 2 3
i = i + 1 1 2 3 4
No
print("Done!") Is i <= 3?
Execution : Yes
Print i
Variable i 0 1 2 3 4
is i <= 3? Yes Yes Yes Yes No
Let i = i + 1
Print i 0 1 2 3
i = i + 1 1 2 3 4
i = 1 1) Initialize control
while (i <= 3):
2) Check condition
print("i =", i)
3) Execute body
i = i + 1
print("Done!")
4) Update control
i = 0
while (i <= 6):
print("i =", i)
i = i + 1
print("Done!")
• Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
i = 0
while (i <= 6):
if ((i == 3) or (i == 6)):
print(‘’)
else
print("i =", i)
i = i + 1
slide 12
print("Done!") James Tam
• What is the output of the following code?
x=0
while (x < 10):
x=x+1
print(“Hi..”)
intNumber = 1
print(“Hello World…”)
If it is needed to print the message 5 times, what change(s) need to be done for the
above code segment?
i = 3
print("Done!")
print("i =", i)