Lesson 5: Loops
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a flow chart of a loop
statement.
Python programming language provides the following types of looping
constructs
a) while loop
b) for loop
c) nested loops .
while Loop Statements
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true. It tests the condition
before executing the loop body
Syntax
while expression:
statement(s)
Example
count = 0
while (count < 10):
print ('The count is:', count)
count = count + 1
A. Irungu
for Loop Statements
In Python, the for statement has the ability to iterate over the items of any sequence,
such as a list or a string.
Syntax
for iterator in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterator. Next, the statements block
is executed. Each item in the list is assigned to iterator, and the statement(s) block is
executed until the entire sequence is exhausted.
Example 1
for i in range (10): # using a range of numbers
print(i)
Example 2
name = 'university' # using a string
for letter in name:
print(letter)
Example 3
animals = ['lion', 'buffalo', 'hippo'] # using a list
for animal in animals:
print(animal)
Example 4
animals = ('lion', 'buffalo', 'hippo') # using a Tuple
for animal in animals:
print(animal)
Using else Statement with Loops
Python supports having an else statement associated with a loop statement.
If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else
statement gets executed.
num=1
while num !=0:
print (str(num) + " squared = "+ str(num*num))
num= int(input("Enter a number : "))
else:
print (" Number Zero Entered. STOP")
A. Irungu
Single Statement Loops
Similar to the if statement syntax, if a loop consists of a single statement only,
everything can be placed in a single line.
Example:
name = 'university'
for letter in name: print(letter)
Nested loops
A nested loop is a loop that is used inside the body of another loop.
Syntax for nested for loops
for iterator1 in sequence:
for iterator2 in sequence:
statements(s)
statements(s)
Syntax for nested while loops
while expression:
while expression:
statement(s)
statement(s)
Additionally, any type of loop can be nested inside any other type of loop. For
example, a for loop can be inside a while loop or vice versa.
Example: A nested-for loop to display multiplication tables from 1-6.
for i in range(1,6):
for j in range(1,6):
k=i*j
print (k, end='\t')
print()
The print() function inner loop has end=' \t' which appends a tab space
instead of default newline. Hence, the numbers will appear in one row. The
Last print() will be executed at the end of inner for loop.
Loop Control Statements
The Loop control statements change the execution from its normal sequence.
When the execution leaves a scope, all automatic objects that were created in
that scope are destroyed.
break statement - Terminates the loop statement and transfers execution to
the statement immediately following the loop.
A. Irungu
continue statement - Causes the loop to skip the remainder of its body during
the current iteration, and immediately retest its condition
prior to reiterating.
pass statement - It is used when a statement is required syntactically but you
do not want any command or code to execute.
break statement
The break statement is used for terminating of the current loop prematurely.
After terminating the loop, execution resumes at the next statement after the
loop.
Example 1
name = 'university'
for letter in name:
if letter=='r':
break
print(letter)
Example 1
num = 0
while num<10:
if num==6:
break
print(num*num)
num+=1
continue Statement
The continue statement causes the loop to start the next iteration without executing
the remaining statements in the current iteration.
Example 1
name = 'university'
for letter in name:
if letter=='r':
continue
print(letter)
Example 1
num = 0
while num<10:
num+=1
if num==6:
continue
print(num*num)
A. Irungu
pass Statement
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing
happens when it executes.
for letter in 'university':
if (letter == 'v'):
pass
print (letter)
Iterator and Generator
Iterators are something that help to loop over different objects in Python.
Iterator goes over all the values in the list. Iterators apply the iterator protocol
that contains basically two methods:
_iter_()
_next_()
Iterable objects are objects which you can iterate upon. Examples of iterables
are tuples, dictionaries, lists, strings, etc.These iterables use iter() method to
fetch the iterator.
Example:
fruits = ('avocado', 'beetroot', 'berries')
myiter = iter(fruits)
print(next(myiter))
print(next(myiter))
print(next(myiter))
A generator is a function that produces or yields a sequence of values using
yield method.
When a generator function is called, it returns a generator object without even
beginning execution of the function. When the next() method is called for the
first time, the function starts executing, until it reaches the yield statement,
which returns the yielded value. The yield keeps track i.e. remembe*rs the last
execution and the second next() call continues from previous value.
Example
square= (x ** 2 for x in range(5))
print (next(square))
print (next(square))
print (next(square))
print (next(square))
print (next(square))
A. Irungu
The following example defines a generator, which generates an iterator for all
the squares up to a given numbers.
import sys
def squares(n): #generator function
counter = 0
while True:
if (counter > n):
return
yield counter**2
counter += 1
sqr = squares(5) #sqr is iterator object
while True:
try:
print (next(sqr))
except StopIteration:
sys.exit()
A. Irungu