0% found this document useful (0 votes)
20 views29 pages

Chapter3 - Iterations

sasd

Uploaded by

fzrish
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)
20 views29 pages

Chapter3 - Iterations

sasd

Uploaded by

fzrish
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/ 29

BERV 1313

Computer
Programming
Iterations
Prepared by Dayanasari binti Abdul Hadi
Learning Objective

• Using while loop.


• Using for loop and range() function.
• Loop control via else, break and continue.
• Nested loops.

2024/2025 SEM II BERV 1313 Computer Programming 2


Iteration
• In python, iteration refer to the process of repeatedly
execute a block of code named as repetition.
• Its loop through elements in an iterable object such as a
list, tuple, dictionary, string, or set.
• Basically there are 2 type of loops in Python:
 for loop
 while loop

2024/2025 SEM II BERV 1313 Computer Programming 3


while
statement

2024/2025 SEM II BERV 1313 Computer Programming 4


while loop
• A while loop continues to execute as long as the condition remains True.
• Syntax:

while< expression/condition >:


< statement(s) >

• Example:
i = 1
while i <= 5:
print(i)
i += 1 # Increment i to avoid infinite
loop
2024/2025 SEM II BERV 1313 Computer Programming 5
while loop with FLowchart
Flow chart
i = 1
Variable name i
START
while
while ii <=
<= 3: Variable value 21
34
3: print(i
print(i)
)i +=
i += 1  i = i + 1 i=1

1
FALSE
i <= 3

1 TRUE

2 FALSE Print i STOP

3
i+=1
Exercise:
Change the code so that its print the number 1,
3, 5,7 and 9
2024/2025 SEM II BERV 1313 Computer Programming 6
Sentinel controlled loop
• A sentinel controlled loop continues to loop until reaching a special value that signal the end.
• The special values is called sentinel and any values might be.
• In this example, variable txt is the sentinel as it is used to signal when to stop the loop.
count = 0
say = ""
txt = ""

print ("If you want to stop, type 's'.")

while txt != "s" :


txt = input("Enter some text: ")
count += 1
say += txt

print ("You have stop the input.")


print ("total input count is ", count)
print ("You said: ", say)
2024/2025 SEM II BERV 1313 Computer Programming 7
Example of sentinel controlled
loop
count = 0 count say txt
say
0 = ""
txt
"" = "" 0432
1 10
10UTe
10UTeMk
10UTeMk UTeM
10
sk
"" s
M
0x1000 0x1004 0x1008
print ("If you want to stop, type 's'.") TRUE
TRUE
FALSE
's'.")
while txt
while txt !=
!= "s":
txt
tx =input("Enter
"s":tx
txt input("Entersome
input("Enter sometext:
some text: ")
text:
tcount
t
count ")+= 11
")
+= => say = say + txt
say +=
say += txt
txt => say = 10 + UTeM
txt
print ("You have stop the input.") If you want to stop, type 's'.
(“Total input count is ", count)Enter some text:10
input.")
print
print ("You said: ", say)
count)
say) Enter some text:UTeM
Enter some text:k
First loop done
Enter some text:s
Second loop done
You have stop the input.
Third loop done Total input count is 4
FourthSEM
2024/2025 loop
II done You said:
BERV 1313 Computer10UTeMks
Programming 8
in operator
• In Python, in operator is use to check if a value exists in an iterable, such as a list, tuple, set,
string, or dictionary.
• It returns True if the value is found and False otherwise.
• Syntax:
< value > in < iterable >
• value  The element you want to check for in the iterable.
• iterable The collection in which you're checking for the element (list, tuple, string, dictionary,
etc.).
• Example:

result = "th" in
True
"Python"
print (result)

2024/2025 SEM II BERV 1313 Computer Programming 9


for
statement

2024/2025 SEM II BERV 1313 Computer Programming 10


for - in loop
• The for loop is used to iterate over a sequence of elements and execute a
block of code for each element in that sequence.
• It allows you to loop through all items in the iterable until there are no more
items left.
• Syntax:

for< variable >in< iterable >:

• variable  Represents the current item from the iterable.


• iterable The collection in which you're checking for the element (list, tuple,
string, dictionary, etc.).

2024/2025 SEM II BERV 1313 Computer Programming 11


The for loop is used to iterate over a sequence of elements and execute a block
of code for each element in that sequence.

for - in loop: Example


• Example: text letter I
text = “Its Me" I t s M t
e
I t
M
s
Me"
for letter
for
for letter in
letter in text
in text:
text 0x1000
e 0x1004 s
print
print (letter)
print
print (letter)
(letter)
(letter) M
e

student = ["ali", "mutu",


"wong"]
ali
for student in student: mutu
print(student) Wong

2024/2025 SEM II BERV 1313 Computer Programming 12


for loop using a range of
numbers
• The range() function is used to iterate a specific number of times..
• Syntax:

range( < start , < stop > , < step > )


>
• start  The number where the range starts (inclusive). Default is 0 if not provided.
• stop  The number where the range ends (exclusive). The loop runs until this number, but
does not include it.
• step (optional)  The difference between each number in the range. Default is 1 if not
provided.
• Example: i
0 First for loop  by default, start i with 0
range(3):
for i in range(3) 1 Second for loop  next, i become 1 2
1
0
print(i)
print(i Third for loop  next, i become 2 0x1000
range(3)
print(i) 2
)
for loop stop at i = 2
2024/2025 SEM II BERV 1313 Computer Programming 13
Example for loop using a range
of numbers
Example 1: The starting number. 5
Default is zero. 6
for i in range( 5 , 9 ): 7
8
print(i) The end number but not
include the number (9-1)

Can use negative step size if


Example 2: we want to count down start stop
2 3 4 5 6 7 8 9 10 11 12 13
for
for ii in
in range(
range( 2,
2, 14, 14, 3 3 i
3 ):print(i)
)
) 2
print(i
Step size (default is 1) 5 11
8
2
5
)print(i) 0x1000
8

Here, the loop starts at 2, and increments by 1


3 each
2024/2025 SEM II time until it reaches just below 1313 Computer Programming1
BERV14. for loop stop at i = 1114
Exercise for loop
1. Use for loop and range function to print multiples of 3, starting at 27,
counting down to 3, in just 2 line of code.
2. Use for loop and range function to print multiples of 3, starting at any
number that enter by user, counting up to 20.

2024/2025 SEM II BERV 1313 Computer Programming 15


Loop control
statement

2024/2025 SEM II BERV 1313 Computer Programming 16


Loop control statements
• Basically there extra keyword to control the flow in the
loop.
 else
 break
 continue
• They work with while and for loops.

2024/2025 SEM II BERV 1313 Computer Programming 17


1. break statement
• The break statement allow you to break out of a loop
prematurely when a certain condition is met.
• When Python encounter the break statement, it will not
process the remainder of the code.

2024/2025 SEM II BERV 1313 Computer Programming 18


Example on break statement in
for loop
• Example:
Current Letter: D
for
forletter
letterinin‘Dayanasari
‘DayanasariAbdul
AbdulHadi'
Hadi':
Current Letter: a
ifif
Hadi'ifletter
letter====
letter ==‘y'
‘y'oror
‘y' orletter
letter====
letter ==‘n'
‘n':
FALSE
TRUE ‘n' break
break DONE
print("Current Letter:
Letter:",",
print("CurrentLetter:
print("Current ",letter)
letter)
letter)
print("DONE")
print("DONE")

lette
D a y a n a s a r i A b d u l H a d i r
D
a
y
Exit for loop at letter = y 0x100
0
Exercise:
Break when letter is y or n Change or to and in the if
condition
2024/2025 SEM II BERV 1313 Computer Programming 19
Example on break statement in
while loop i
• Example 1: 3
4
0
1
2
TRUE
i = 0 0x1000
while i < 10 :
: :
10 :print(
print( ii )
print( 0
i
if
)
iff ii ==
== 4 :  End of while loop at i = 4 1
4 : break
break 2
i+=1
i+=1 3
4

Exercise:
Change the coding above to implement for loop

2024/2025 SEM II BERV 1313 Computer Programming 20


2. continue statement
• The continue statement allow you to skip the current iteration of a loop and
continue with the next iteration.
num
• Example:
10
1
0
9
4
2
3
5
TRUE
FALSE EXIT while loop
num = 0 0x1000
0
while
while 10:
num << 10:
num
FALSE
TRUE
False
num += 1  num = num +1 10: num
num
num +=
+=
+= 11
14
23 %% %22 2 remainder
5
10 remainder 1
remainder0 if
1ifnum
if num
num%%%222==
==
==00 : 1
0
1 0 : :
0 : continue
continu 3
econtinue
print(
print( num )
num 5
1. Complete first while loop
)print( num ) .
2. Complete second while loop
3. Complete third while loop
.
4. Complete fourth while loop
.
5. Complete fifth while loop
9
.
.
.
2024/2025 SEM II while loop
10. Complete tenth BERV 1313 Computer Programming 21
3. else statement
• In python, else statement allow after while and for loops.
• If the while and for loops end normally, then else statement is executed.
• If the while and for loops interrupted by a break statement, then else statement is NOT executed.
• Example:
count
count == 00 TRUE of count
FALSE
1
20
while
while count 4:
count << 4:
print("Count is:", is:", count)
count) 0x1000
4: print("Count
print("Count is:",
TRUE of count
count +=
count
count) += 11
+= Count is: 0
FALSE if
if count
1
if count ==
count == 2:
== 2: Count is: 1
2: print("Breaking
print("Breaking the the loop")
Breaking the loop
loop")
break
break EXIT while loop
Loop has ended.
else:
print("Loop completed without Skipped this
break") else statement
print("Loop has ended.")
print("Loop has ended.")

2024/2025 SEM II
When count reaches 2, the break statement is triggered, ending the loop immediately.
BERV 1313 Computer Programming 22
3. else statement
• Using same example as before, remove break statement

count = 0 If the while and for loops end normally, then else statement is executed.
FALSE count
while count
while
while count <<< 4:
count 4:
print("Countis:",
4: print("Count
print("Count is:",count)
is:", count) 4
0
1
2
3
count
count
count) +=
count +=
+= 11 0x1000
1if count
if
if count ==
count == 2:
== 2:
2: print("Breaking
print("Breakingthetheloop")
loop")
Count is: 0
break
else:
else: Count is: 1
print("Loopcompleted
print("Loop completedwithout
withoutbreak") Breaking the loop
break") Count is: 2
print("Loop has ended.")
Count is: 3
print("Loop has ended.")
Loop completed without break
Loop has ended.

2024/2025 SEM II BERV 1313 Computer Programming 23


4. pass statement
• In python, pass statement used as a placeholder when code is syntactically required, but you don’t want
to execute any code at that point.
• In a while loop, pass can be used to create an empty loop or as a placeholder to implement the body
of the loop later.
• Example:
count
count == 00 count

2
0
3
41
FALSE while count
while
while count <<< 4:
count 4: when count = 4, EXIT while loop
print("Count is:",
is:", count)
count) 0x1000
4: print("Count
print("Count is:",
count
count +=
count
count) += 11
+= Count is: 0
if
1if count
if count ==
count == 2:
== 2: Count is: 1
2: pass
Count is: 2
print(“Count
print(“Countis:“,
is:“,count)
count) Count is: 3
Count is: 4
When count is 2, the pass statement is encountered, so nothing
happens, and the loop moves to the next iteration.
2024/2025 SEM II BERV 1313 Computer Programming 24
Nested loop

2024/2025 SEM II BERV 1313 Computer Programming 25


Nested loops 3: for loop in
while loop
• You can put loop inside loop.
• Example: i j

i = 1 12
3 1
2
When i = 3, it EXIT while loop 0x1000 0x1004
# Outer while loop FALSE
while ii <=
while 2:
<= 2:
Outer loop print("WhileLoop
2: print("While
print("While LoopIteration
Loop Iteration{i}:")
Iteration {i}:")
{i}:")
# Inner for loop While Loop Iteration 1
forj jin
for inrange(1,
range(1,3): 3): For Loop Iteration 1
Inner loop
print(" For
print(" For Loop
Loop Iteration
Iteration {j}")
{j}") For Loop Iteration 2
While Loop Iteration 2
i +=
ii += 11
+= Start at 1 For Loop Iteration 1
1 (inclusive)
End at 3 For Loop Iteration 2
When j = 2, it EXIT for loop (exclusive)
Repeat the for
2024/2025 SEM II
loop same as
BERV 1313 Computer Programming 26
previous
Nested loops 1: while loop in
while loop
# Initialize row number
row = 1

# Outer while loop for rows


while row <= 5:
# Initialize column number
col = 1

# Inner while loop for columns in each row


while col <= row:
print("*", end="") # Print star without a
newline
col += 1

print() # Move to the next line after each row


row += 1 Exercise:
Change the coding to implement for loop
2024/2025 SEM II BERV 1313 Computer Programming 27
Nested loops 2: for loop in for
loop
# Outer for loop for rows
for row in range(1, 6): # Iterates from 1 to 5
# Inner for loop for columns in each row
for col in range(1, row + 1): # Iterates from 1 to
the current row number
print("*", end="") # Print star without a
newline

print() # Move to the next line after each row

2024/2025 SEM II BERV 1313 Computer Programming 28


Exercise to try
1. Write a countdown code whereby user input the start number and count it down to zero. It
does not print 0, instead its print “Blast off!!”. Error massage will appear when user enter 0 and
negative number as start number. Draw flow chart for your code.

2024/2025 SEM II BERV 1313 Computer Programming 29

You might also like