Topic 5 - Repetition Structures_Student
Topic 5 - Repetition Structures_Student
Introduction to programming
COMP102
Term 2-2024-2025
Lesson Outcomes
2
Looping
▫ while loop
▫ for loop
3
while loop
4
while loop
5
General way to write a while loop
Initialize your
• A variable is initialized outside of the loop Example: 1
counter
1 x=1
2 while x < 5:
• While loop executes while the condition is True
while
<condition>: 3 print(x)
4 x=x +1
• Executes the code within the block of code
Statements Output: 1
1
counter
• Counter is updated inside the loop 2
update 3
4
Instructions
• More instructions after the while loop(optional)
6
Updating variables
7
Examples:
Example1: 1 Output: 1
x = 10 10
while (x != 0): 9
8
print(x)
7
x -= 1 6
5
Example2: 1 4
sum1 = 0 3
2
count = 1 1
while (count < 10):
sum1 = sum1 + count Output:
count += 1
print(count) 10
45
print(sum1)
8
Examples:
Example3: 1 ▪ Program
▪ Displaying “Thank you” 3 times # initialization
n = 1
n=1 # Condition of the while loop
while n <= 3:
print ("Thank you")
No While
Yes # Increment the value of the variable "n by 1"
n <=3 ? n=n+1
9
Stop
An Infinite Loop (no counter update)
▪ Program
n=5
n = 5
No while n > 0:
While Yes
print ("Lather")
n > 0 ? print ("Rinse")
print('Lather') print ("Dry off")
print('Rinse')
▪ Output
Lather
Rinse
Lather
print('Dry off!') Rinse
... Will be infinitely displayed
and “Dry off” will never be displayed 10
Another loop
▪ Program
n=0
n = 0
No
while n > 0:
Yes
While n print ("Lather")
> 0 ? print ("Rinse")
print ("Dry off")
print('Lather')
▪ Output
print('Rinse') Dry off
▪ Example:
Write a Python program to print odd numbers
▪ Output
from 1 to 10
1
3
5
7
9 13
Difference Between break and continue
BREAK CONTINUE
It terminates the execution of It terminates only the current iteration of
remaining iteration of the loop. the loop.
'break' resumes the control of the 'continue' resumes the control of the
program to the end of loop enclosing program to the next iteration of that loop
that 'break'. enclosing 'continue'.
It causes early termination of loop. It causes early execution of the next
iteration.
'break' stops the continuation of loop. 'continue' do not stops the continuation of
loop, it only stops the current iteration.
14
Output?
▪ Example1: ▪ Example2:
var = 10 var = 10
while var > 0: while var > 0:
print ('Current variable value :', var) var = var -1
var = var -1
if var == 5:
if var == 5:
continue
break
print ('Current variable value :', var)
print("Good bye!")
print ("Good bye!")
15
Try
Write a python program to ask the user to enter a valid response. If the user enter “yes” or “no”
the message: "Thank you for your response. " will be shown on the screen otherwise the message:
"Invalid response. Please try again.“ will be shown on the screen and ask the user to enter a valid
response.
Simple Run1:
Please enter a valid response: y
▪ Solution:
Invalid response. Please try again. while True:
Please enter a valid response: n user_input = input("Please enter a valid response: ")
Invalid response. Please try again.
if user_input == "yes“ or user_input == “no“ :
Please enter a valid response: yes
Thank you for your response. print("Thank you for your response.")
break
Simple Run2:
else:
Please enter a valid response: y
Invalid response. Please try again. print("Invalid response. Please try again.")
Please enter a valid response: n continue
Invalid response. Please try again.
Please enter a valid response: no 16
Thank you for your response.
for loop
▪ In Python, the for loop is designed to work with a sequence of data items.
When the statement executes, it iterates once for each item in the sequence.
Syntax:
for variable in [value1, value2, ...]:
statements
▪ The for statement executes in the following manner:
▫ The variable is assigned the first value in the list, then the statements
that appear in the block are executed.
▫ Then, variable is assigned the next value in the list, and the statements
in the block are executed again.
▫ This continues until variable has been assigned the last value in the list. 17
for loop
▪ Examples:
▪ Output: Su
Mo
1
2
Tu 3
We 4
Th 5
Fr
Sa
▪ Output:
30
19
for loop
▪ Output1: ▪ Output2:
Good Morning: Ahmad g
Good Morning: Ali r
Good Morning: Saad e
Done! a
t 21
range() function
▪ The range() function generates a list of numbers, which is generally
used to iterate over within for loops.
▪ Syntax: range(start, stop, step)
▪ Examples: for n in range(10): for n in range(1,10): for n in range(1,10,2):
print(n) print(n) print(n)
Output: Output: Output:
0 1 1
1 2 3
2 3 5
3 4 7
4 5 9
5 6
6 7
7 8
8 9
22
9
range() function
▪ Program 1: ▪ Output 1:
#
for j in range(4): #
print(“# “) #
#
▪ Program 2: ▪ Output 2:
# # # #
for j in range(4): To print in horizontal not vertical line
we use (end=“”)
print(“# “,end=“”)
23
Try out
▪ Output
▪ Write a program that displays the
Number Square
numbers 1 through 10 and their 1 1
respective squares. 2 4
3 9
4 16
5 25
▪ Solution:
6 36
7 49
8 64
9 81
10 100 24
Quiz
What will the following codes display?
Q1: for number in range(6):
print(number)
▪ Output 0
1
2
3
4
27
else of for loop is executed
Counting the number of items in a list
▪ Program
▪ Output
Count: 6
28
Finding the largest –Maximum value in a list or sequence
▪ Program
• Before the loop, we set
largest to the constant
None.
• None is a special constant
value which we can store in
a variable to mark the
variable as “empty”
▪ Output
Largest: 74
29
Finding the smallest –Minimum value in a list or sequence
▪ Program
▪ Output
Smallest: 3
30
Nested for loop
▪ A nested loop is a loop that is inside another loop.
▪ Program:
▪ Output
# # # #
# # # #
# # # #
31
Nested for loop
▪ What will the below code produce?
32
Exercises
33
Exercise 1
Write a python program to print the square of all numbers from 0 to 10.
for i in range(11):
print("Square of",i,"=",i ** 2)
i=0
while i<=10:
print(“Square of", i,"=", I ** 2)
i = i + 1
34
Exercise 2
Write a python program to find the sum of all even numbers from 0 to 10.
SUM = 0 SUM = 0
for x in range(11): x = 0
if x % 2 == 0: while x <= 10:
SUM = SUM + x if x % 2 == 0:
print(SUM) SUM = SUM + x
x = x + 1
print(SUM)
35
Exercise 3
▪ Write a python program to read three numbers (a,b,c) and check how many
numbers between ‘a’ and ‘b’ are divisible by ‘c’. Note: use the highest value for a .
▪ Simple Run: Enter the three numbers:10,2,5
Between 2 and 10 there is 2 numbers divisible by 5 [5, 10]
37