5-Intro To Python - Loop
5-Intro To Python - Loop
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:
Condition
satisfied?
Yes
No
Execute statements between
while..loop block
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
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
Condition
satisfied?
Yes
No
Execute statements between
for..loop block
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
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
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
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