0% found this document useful (0 votes)
31 views

5-Intro To Python - Loop

The document discusses different types of repetition structures in Python including for and while loops, and how they can be used to repeatedly execute code a fixed or variable number of times. It also covers concepts like nested loops, breaking and continuing loops early, and using loops to process lists and tuples of data rather than repeating code for each individual value.

Uploaded by

Zakwan Ariff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

5-Intro To Python - Loop

The document discusses different types of repetition structures in Python including for and while loops, and how they can be used to repeatedly execute code a fixed or variable number of times. It also covers concepts like nested loops, breaking and continuing loops early, and using loops to process lists and tuples of data rather than repeating code for each individual value.

Uploaded by

Zakwan Ariff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

CHAPTER 5

REPETITION

Source:www.codermania.com
Learning Outcomes
Upon completion of this lecture, learners will be
able to:
– grasp the basic concept of repetition structures
and
– apply repetition structures (For) and (while) in
Python program
A loop is a statement that is used to:

execute one or more statements


repeatedly until a goal is reached.
Why Use Repetition?
• Examples:
– Evaluating the gross & net pay for the employees in a
company
– Evaluating the grades for all students in a class,...etc.

• We can write the Python program to process for one


individual and then repeat the process for all
participants
2 Kinds of Repetition

• It can be determined in advance how many times


Fixed a segment of code will be repeated
• The number of times the segment of code is
repetition repeated is independent of what happens inside
the loop

• It cannot be determined in advance how many


Variable times a segment of code will be repeated
• The value (true /false) of the condition
determining whether a segment of code will be
repetition repeated or not, changes as a result of what
happens inside the loop
Type of loops in Python:
For…do loop
While…do loop
Terminology
• Counter-controlled loops
– Also called “Counting loops”
– Repetition is controlled by a variable whose value
represents a counter
– E.g. the FOR and WHILE loop
– These loops implement fixed repetition
• Event-driven loops
– Also called “Conditional loops”
– Repetition is controlled by a condition (a Boolean variable
or expression) whose value changes as the loop is
executed
– E.g. the WHILE loop
– These loops implement variable repetition
While…do loop
Format: • The body of loop will be executed
{Initialize} and continue repeating, while the
condition is true. It will Exit from the
while {condition} loop (stop executing the body of
statements loop), if condition is false.
{increment/decrement}
• The condition is tested at the
beginning of the loop and not at any
time while the loop is running, as the
name suggests. You might want to
initialize a counter value or input
value before entering the loop, to be
tested in loop’s condition.
• The counter value should
increase/decrease or input value
shall change to and meet the false
condition, to avoid infinite loop.
Initialize counter
FLOWCHART

Condition
satisfied?

Yes
No
Execute statements between
while..loop block

Execute next statements


Pseudo-code (example 1 &2)
initialize i equals to 0
while i less than 10
add 1 to i {increment 1 to i}
display ‘Hello’
----------------------------------------------------------
initialize i equals to 10
while i more than 0
minus 1 from i {decrease 1 from i}
display ‘Hello’
Pseudo-code (example 3)
prompt and get i
while i is not equal to 0
display ‘Hello’
prompt and get i
Examples

12
Example 1:
Answer:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Example 2:

Output:
Example 3:

Output:
Example 4:
import random
ANY FLAW IN
#1.Generate two random single digit integers THE CODES?
number1=random.randint(0,9)
number2=random.randint(0,9)

#2. if number1 is smaller than number2, swap value for number1 with number2
if number1<number2:
number,number2= number2, number1

#3.prompt the student to answer "What is number1-number2?"


answer=eval(input(“What is "+ str(number1) + " - " + str(number2)+ "?"))

#4.repeatedly ask the question until the given answer is correct


while number1-number2 != answer:
answer=eval(input(“Wrong answer. Try again. What is "+ str(number1) + " - " + str(number2)+ "?"))
print(“You got it!")

Output:
For loop
Format:
for i in range({finalValue})
statements
for i in range({initalValue},{finalValue})
statements
for i in range({initialValue},{finalValue},{stepValue})
statements

• For uses a loop counter variable which adds step value to the loop
from a first number to a last number. It repeats while the sequence
number is less than the final value. Ends the loop when the final
number is equal or more than final value.
• The first number in the sequence is initial value. Each successive
number in the sequence will increase/decrease by the step value.
The last number in the sequence must be less than final value.
• range({finalValue}) is the same as range({0,finalValue}).
The For…Do Loop
• The value of <counter>
– Starts out by being the value of <initial value>
– Is incremented by a step value (if step value is positive) or
decremented by a step value(if step value is negative)
after each loop repetition
– Cannot be modified in the FOR statement
– After loop exit, the value of the <counter> is considered
undefined:
You shouldn’t attempt to use the value of <counter>
without reassigning to <counter> first.
– <initial value> and <final value> may be constants,
variables, or expressions of the same ordinal type as the
<counter>
The For…Do Loop
• <statements> comprises the loop body.
– It is executed once for each value of the counter between
<initial value> and <final value>, not inclusive
– It is not executed if
<final value> is smaller or equal to (for increment)
greater or equal to (for decrement) than the <initial value>
Eg:range (10,0,5)
10<0 is TRUE,
15<0 isTRUE


100<0 is still TRUE
Lead to infinite loop

– It is indented for clarity


– It is a single statement, simple or compound
Initialize counter
FLOWCHART

Condition
satisfied?

Yes
No
Execute statements between
for..loop block

Execute next statements


Pseudo-code (example 1&2)
set integer i as 1
for i is less than 11
display ‘Hello’
i is increased by 1
-----------------------------------------------------------
set integer i as 11
for i is more than 1
display ‘Hello’
i is reduced by 1
Examples

22
Example 1:
Answer:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Example 2:
Answer:

10
9
8
7
6
5
4
3
2
1
Example 3:
Answer:

1234515
0110
9
8
7
6
5
4
3
2
1
Example 4:
Example 5:
Keywords break and continue

✓ provide additional controls to a loop


✓ application of
✓ break keyword in a loop can immediately
terminate a loop.
✓ continue keyword ends the current iteration
and program control goes to the end of the loop.
Examples

29
break keyword (example 1)

Output:
continue keyword (example 2)

Output:
Nested Loop
✓ consist of an outer loop and one or more inner
loops
✓ each time the outer loop is repeated , the inner
loops are reentered and started anew
Examples

33
Nested for loop (example 1)
Answer:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
Finished!
Nested for loop (example 2)

Output:
Nested for loop (example 3)
Nested while loop (example 4)
Output:
More application of loops
• Programs commonly need to store a
large number of values.
• For instance, you need to read 3
numbers, compute their average and
find out how many of the numbers are
Loop in above the average.
• To do this, you would need to create 3
List and variables and repeated write almost
identical code for 3 times which is
Tuple impractical.
• Thus, Python provides a type called a
list that stores a sequential
collection of elements and access
them through a single list variable.
Loop in List and Tuple
Conventional method List method

Output:
Withno values
–list1 = list()
–list1 = []
Withstarting values
–list2 = list([2,3,4])
Creating –list2 =[2,3,4]
–list3 =
Lists list([“red”,”green”])
– list3=[“red’,”green”]
– list4 = list(range(3,6))
– list5 = list(“abcd”)
Index Operator [ ]
• An element in a list can be accessed through
the index operator, using following syntax:
myList[index]
• List indexes are 0 based: that is they range
from 0 to len(myList)-1, as illustrated in
next figure .
Index Operator [ ] (cont..)
List reference myList reference
variable

myList[0] 5.6

myList[1] 4.5

myList[2] 3.3

List element at myList[3] 13.2 Element value


Index 3

The list myList has 4 elements with indexes from 0 to 3

myList = [5.6, 4.5, 3.3, 13.2]


Index Operator [ ] (cont..)
• myList[index] can be used just like a variable, so it is also
known as an indexed variable.

• For example, the following code adds the values in myList[0]


and myList[1] to myList[2]

myList[2] = myList[0] + myList[1]

• The following loop assigns 0 to myList[0], 1 to


myList[1],.. and 9 to myList[9]:

for i in range(len(myList)):
myList[i] = i
Index Operator [ ] (cont..)
• Python also allows the use of negative
numbers as indexes to reference positions
relative to the end of the list.
• The actual position is obtained by adding the
length of the list with the negative index.
✓ list[-1] is same as
list[-1+len(list1)] , which
gives the last element in the list
✓ list[-3] is same as
list[-3+len(list1)], which
gives the third last element in
the list
List Slicing [start:end]
• The index operator allows you to select an
element at the specified index.
• The slicing operator returns a slice of the list
using the syntax list[start:end]. The
slice is a sublist from index start to index end-
1.
• Example:
List Slicing [start:end] (cont..)
• The starting index or ending index maybe
omitted. In this case, the starting index is 0
and the ending index is the last index.
• Example:
List Slicing [start:end] (cont..)
• You can use a negative index in slicing.
• Example:
✓list[1:-3] is the same as
list1[1:-3+len(list1)-1]
✓list1[-4:-2] is the same as
list1[-4+len(list1):-2+len(list1)-1]
The +,*, and in/not in Operators
• You can use the concatenation operator (+) to
join two lists and the repetition operator (*)
to replicate elements in a list.
• Example:
The +,*, and in/not in Operators
(cont..)
• You can determine whether an element is in a
list by using the in or not in operator.
• Example:
Traversing Elements in a for Loop
• The elements in a Python list are iterable.
• Python supports for loop, which enables you
to traverse the list sequentially without using
an index variable.
• For example, the following code displays all
the elements in the list list1:
Traversing Elements in a for Loop
(cont..)
• You still need to use an index variable if you
wish to traverse the list in a different order or
change the elements in the list.
• For example, the following code displays the
elements at odd-numbered positions.
List Methods
Python has a set of built-in methods to be use in lists.
Method Description
append() Adds an element at the end of list

clear() Removes all the elements from list

copy() Returns a copy of list

count() Returns the number of elements with specified value

extend() Add the elements of a list(or any iterable), to the end of the current list
insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


List Methods Examples
List Methods Examples (cont..)
Splitting String to List
• The str class contains the split method,
which is useful for splitting items in a string
into a list.
• For example:
Input Lists
• You may read data from console into list by
using to methods:
i.Entering one data item per line and append
it to a list in a loop.

ii. Entering data in one line separated by


spaces.
Tuples
Creating Tuples
• Tuples are like lists, but their elements are fixed.
• Once tuple is created, you CANNOT add new
elements, delete, replace or reorder the
elements in the tuple.
• You can create an empty tuple, create a tuple
with elements and create a tuple from a list
Tuples Examples
Tuples Examples (cont..)
Function for Lists and

Tuples
Len -return the number of elements in the list
• Max/min - return the elements with the
greatest and lowest values in the list
• Sum -return the sum of all elements in the list
• Shuffle -shuffle the elements randomly in
the list (a function in the random module ).
Summary
• There are two types of repetition statements: the while loop
and the for loop.
• The while loop and for loop checks the condition first. If the
condition is true, the statement(s) in the loop is/are executed,
otherwise the loop terminates.
• The for loop is a counter-controlled loop and is used to
execute the statements in the loop for a predictable number
of times.
• An infinite loop is a loop statement that executes infinitely.
• break keyword immediately ends the innermost loop, which
contains the break.
• continue keyword ends only the current iteration/loop.
Summary
• for loop can be used to traverse all elements in a
list and tuple.
• A list is mutable. Methods such as append,
extend, insert, pop and remove can be used to
add and remove elements to and from a list or a
set.
• A tuple is a fixed list that cannot be added, deleted
or replaced the elements in a tuple.
• Python built-in functions len, max, min, and sum can
be used to return the length, the maximum, minimum
and sum of all the elements in a list and tuple.

You might also like