Module - 2: 2.1 Iteration
Module - 2: 2.1 Iteration
MODULE – 2
2.1 ITERATION
Iteration is a processing repeating some task. In a real time programming, we require
a set of statements to be repeated certain number of times and/or till a condition is
met. Every programming language provides certain constructs to achieve the repetition of
tasks. In this section, we will discuss various such looping structures.
statements_after_while
Here, while is a keyword. The condition is evaluated first. Till its value remains true,
the statement_1 to statement_n will be executed. When the condition
becomes false, the loop is terminated and statements after the loop will be executed.
V
Consider an
example –
n=1
while n<=5:
print(n) #observe indentation
n=n+1
print("over")
n=1
while True:
print(n)
n=n+1
Here, the condition specified for the loop is the constant True, which will never get
terminated. Sometimes, the condition is given such a way that it will never become false
and hence by restricting the program control to go out of the loop. This situation
may happen either due to wrong condition or due to not updating the counter variable.
In some situations, we deliberately want to come out of the loop even before the
normal termination of the loop. For this purpose break statement is used. The following
example
depicts the usage of break. Here, the values are taken from keyboard until a negative
number
is entered. Once the input is found to be negative, the loop terminates.
while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
Sample output:
Enter a number:23
You have entered 23
Enter a number:12
You have entered 12
Enter a number:45
You have entered 45
Enter a number:0
You have entered 0
Enter a number:-2
You have entered a negative number!!
In the above example, we have used the constant True as condition for while-loop, which
will never become false. So, there was a possibility of infinite loop. This has been avoide
by using break statement with a condition. The condition is kept inside the loop such a
way that, if the user input is a negative number, the loop terminates. This indicates that, the
loop may terminate with just one iteration (if user gives negative number for the very first
time) or it may take thousands of iteration (if user keeps on giving only positive numbers as
input). Hence, the number of iterations here is unpredictable. But, we are making sure that it
will not be an infinite-loop, instead, the user has control on the loop.
Sometimes, programmer would like to move to next iteration by skipping few statements in
the loop, based on some condition. For this purpose continue statement is used.
For example, we would like to find the sum of 5 even numbers taken as input from
the keyboard. The logic is –
Read a number from the keyboard
If that number is odd, without doing anything else, just move to next iteration
for reading another number
If the number is even, add it to sum and increment the accumulator variable.
When accumulator crosses 5, stop the program
sum=0
count=0
while True:
x=int(input("Enter a number:"))
if x%2 !=0:
continue
else:
sum+=x
count+=1
if count==5:
break
Sample Output:
Enter a number:13
Enter a number:12
Enter a number:4
Enter a number:5
Enter a number:-3
Enter a number:8
Enter a number:7
Enter a number:16
Enter a number:6
Sum= 46
2.1.3 Definite Loops using for
The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop. When
we know total number of times the set of statements to be executed, for loop will be used.
This is called as a definite loop. The for-loop iterates over a set of numbers, a set of words,
lines in a file etc. The syntax of for-loop would be –
for var in list/sequence:
statement_1
statement_2
………………
statement_n
statements_after_for
Ex: In the below given example, a list names containing three strings has been created.
Then the counter variable x in the for-loop iterates over this list. The variable x takes the
elements in namesone by one and the body of the loop is executed.
NOTE: In Python, list is an important data type. It can take a sequence of elements
of different types. It can take values as a comma separated sequence enclosed within
square brackets. Elements in the list can be extracted using index (just similar to extracting
array elements in C/C++ language). Various operations like indexing, slicing, merging,
addition and deletion of elements etc. can be applied on lists. The details discussion on Lists
will be done in Module 3.
The for loop can be used to print (or extract) all the characters in a string as shown below
–
for i in "Hello":
print(i, end=’\t’)
Output:
H e l l o
When we have a fixed set of numbers to iterate in a for loop, we can use a
function
range(). The function range() takes the following format
–
range(start, end, steps)
The start and end indicates starting and ending values in the sequence, where end is
excluded in the sequence (That is, sequence is up to end-1). The default value of start is
0. The argument steps indicates the increment/decrement in the values of sequence
with the default value as 1. Hence, the argument steps is optional. Let us consider few
examples on usage of range() function.
Output:
0 1 2 3 4
Here, 0 is the default starting value. The statement range(5)is same as range(0,5)
and range(0,5,1).
Output:
0 2 4 6 8
The while-loop and for-loop are usually used to go through a list of items or the contents of a
file and to check maximum or minimum data value. These loops are generally
constructed by the following procedure –
Initializing one or more variables before the loop starts
Performing some computation on each item in the loop body, possibly changing the
variables in the body of the loop
Looking at the resulting variables when the loop completes
Here, the variable count is initialized before the loop. Though the counter variable iis not
being used inside the body of the loop, it controls the number of iterations. The variable
count is incremented in every iteration, and at the end of the loop the total number
of elements in the list is stored in it.
One more loop similar to the above is finding the sum of elements in the list
–
total = 0
for x in [4, -2, 41, 34, 25]:
total = total + x
print(“Total:”, total)
NOTE: In practice, both of the counting and summing loops are not necessary, because
there are built-in functions len()and sum()for the same tasks respectively.
Maximum and Minimum Loops: To find maximum element in the list, the following code
can be used –
big = None
print('Before Loop:', big)
for x in [12, 0, 21,-3]:
if big is None or x > big :
big = x
print('Iteration Variable:', x, 'Big:', big)
print('Biggest:', big)
Output:
Before Loop: None
Iteration Variable: 12 Big: 12
Iteration Variable: 0 Big: 12
Iteration Variable: 21 Big: 21
Iteration Variable: -3 Big: 21
Biggest: 21
Here, we initialize the variable big to None. It is a special constant indicating
empty. Hence, we cannot use relational operator == while comparing it with big. Instead,
the is operator must be used. In every iteration, the counter variable x is compared with
previous value of big. If x > big, then xis assigned to big.
Similarly, one can have a loop for finding smallest of elements in the list as given below
–
small = None
print('Before Loop:', small)
for x in [12, 0, 21,-3]:
if small is None or x < small :
small = x
print('Iteration Variable:', x, 'Small:', small)
print('Smallest:', small)
Output:
Before Loop: None
Iteration Variable: 12 Small: 12
Iteration Variable: 0 Small: 0
Iteration Variable: 21 Small: 0
Iteration Variable: -3 Small: -3
Smallest: -3
NOTE: In Python, there are built-in functions max() and min() to o compute maximum and
minimum values among. Hence, the above two loops need not be written by the
programmer
explicitly. The inbuilt function min()has the following code in Python –
def min(values):
smallest = None
for value in values:
if smallest is None or value < smallest:
smallest = value
return smallest
2.2 STRINGS
A string is a sequence of characters, enclosed either within a pair of single quotes
or double quotes. Each character of a string corresponds to an index number, starting
with zero as shown below –
S= “Hello World”
character H e l l o w o r l d
index 0 1 2 3 4 5 6 7 8 9 10
The characters of a string can be accessed using index enclosed within square brackets.
For example,
>>> word1="Hello"
>>> word2='hi'
>>> x=word1[1] #2nd character of word1 is extracted
>>> print(x)
e
>>> y=word2[0] #1st character of word1 is extracted
>>> print(y)
h
Python supports negative indexing of string starting from the end of the string as shown
below –
S= “Hello World”
character H e l l o w o r l D
Negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
The characters can be extracted using negative index also. For example,
>>> var=“Hello”
>>> print(var[-1])
Whenever the string is too big to remember last positive index, one can use negative index
to extract characters at the end of string.
The index for string varies from 0 to length-1. Trying to use the index value beyond
this range generates error.
>>> var="Hello"
>>> ln=len(var)
>>> ch=var[ln]
IndexError: string index out of range
2.2.2 Traversal through String with a Loop
Extracting every character of a string one at a time and then performing some action
on that character is known as traversal. A string can be traversed either using while
loop or using for loop in different ways. Few of such methods is shown here –
Output:
H e l l o
In the above example, the for loop is iterated from first to last character of the string st.
That is, in every iteration, the counter variable i takes the values as H, e, l, l and o. The
loop terminates when no character is left in st.
H
Output:
e l l o
In this example, the variable i is initialized to 0 and it is iterated till the length of the
string. In every iteration, the value of i is incremented by 1 and the character in a string
is extracted using ias index.
st[i:j:k]
th th
This will extract character from i character of st till (j-1) character in steps of k. If first
index iis not present, it means that slice should start from the beginning of the string. If the
second index j is not mentioned, it indicates the slice should be till the end of the string.
The third parameter k, also known as stride, is used to indicate number of steps to
be incremented after extracting first character. The default value of stride is 1.
Consider following examples along with their outputs to understand string slicing.
st="Hello World" #refer this string for all examples
1. print("st[:] is", st[:]) #output Hello World
As both index values are not given, it assumed to be a full string.
2. print("st[0:5] is ", st[0:5]) #output is Hello
th th
Starting from 0 index to 4 index (5 is exclusive), characters will be printed.
8. print(st[3:8:2]) #output is l o
Starting from 3rd character, till 7th character, every alternative index is
considered.
By the above set of examples, one can understand the power of string slicing and
of Python script. The slicing is a powerful tool of Python which makes many task
simple pertaining to data types like strings, Lists, Tuple, Dictionary etc. (Other types
will be discussed in later Modules)
2.2.4Strings are Immutable
The objects of string class are immutable. That is, once the strings are created (or
initialized), they cannot be modified. No character in the string can be
edited/deleted/added. Instead, one can create a new string using an existing string
by
imposing any modification required.
def countChar(st,ch):
count=0
for i in st:
if i==ch:
count+=1
return count
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=countChar(st,ch)
print("{0} appeared {1} times in {2}".format(ch,c,st))
Sample Output:
The in operator of Python is a Boolean operator which takes two string operands. It returns
True, if the first operand appears in second operand, otherwise returns False. For example,
Basic comparison operators like < (less than), > (greater than), == (equals) etc. can
be applied on string objects. Such comparison results in a Boolean value True or
False. Internally, such comparison happens using ASCII codes of respective characters.
Consider following examples –
Output is same. As the value contained in st and hello both are same, the
equality results in True.
EX2. st= “hello”
if st<= ‘Hello’:
print(‘lesser’)
else:
print(‘greater’)
Output is greater. The ASCII value of h is greater than ASCII value of H. Hence, hello
is greater than Hello.
NOTE: A programmer must know ASCII values of some of the basic characters. Here are
few –
A–Z : 65 – 90
a–z : 97 – 122
0–9 : 48 – 57
Space : 32
Enter Key : 13
The built-in set of members of any class can be accessed using the dot operator
as shown–
objName.memberMethod(arguments)
The dot operator always binds the member name with the respective object name. This is
very essential because, there is a chance that more than one class has members
with same name. To avoid that conflict, almost all Object oriented languages have
been designed with this common syntax of using dot operator. (Detailed discussion on
classes and objects will be done in later Modules.)
Python provides a function (or method) dir to list all the variables and methods of
a particular class object. Observe the following statements –
>>> s="hello" #string object is created with the name
s
>>> type(s) #checking type of s
<class ‘str’> #s is object of type class
str
>>> dir(s) #display all methods and variables of object
s
[' add ', ' class ', ' contains ', ' delattr ', ' dir ',
' doc ', ' eq ', ' format ', ' ge ', ' getattribute
',
' getitem ', ' getnewargs ', ' gt ', ' hash ', ' init ',
' init_subclass ', ' iter ', ' le ', ' len ', ' lt ',
' mod ', ' mul ', ' ne ', ' new ', ' reduce
',
' reduce_ex ', ' repr ', ' rmod ', ' rmul ', ' setattr ',
' sizeof ', ' str ', ' subclasshook ', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join',
'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace',
'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase',
'title',
'translate', 'upper', 'zfill']
Note that, the above set of variables and methods are common for any object of
string class that we create. Each built-in method has a predefined set of arguments and
return type. To know the usage, working and behavior of any built-in method, one can
use the command help. For example, if we would like to know what is the purpose of
islower() function (refer above list to check its existence!!), how it behaves etc,
we can use the statement –
>>> help(str.islower)
Help on method_descriptor:
islower(...)
S.islower() -> bool
The methods are usually called using the object name. This is known as method
invocation. We say that a method is invoked using an object.
Now, we will discuss some of the important methods of string class.
Observe in Ex2 that the first character is converted to uppercase, and an in-between
uppercase letter W of the original string is converted to lowercase.
use.com
>>> print( st) #no change in original string
'hello'
>>> st='HELLO'
>>> st1=st.lower()
>>> print(st1)
hello
>>> print(st) #no change in original string
HELLO
s.find(s1) : The find() function is used to search for a substring s1 in the string s. If
found, the index position of first occurrence of s1 in s, is returned. If s1 is not found in s,
then -1 is returned.
>>> st='hello'
>>> i=st.find('l')
>>> print(i) #output is 2
>>> i=st.find('lo')
>>> print(i) #output is 3
>>> print(st.find(‘x’)) #output is -1
The find() function can take one more form with two additional arguments viz. start
and end positions for search.
Here, the substring ‘cal’is found in the very first position of st, hence the result is 0.
>>> i=st.find('cal',10,20)
>>> print(i) #output is 17
th th
Here, the substring cal is searched in the string stbetween 10 and 20 position and
hence the result is 17.
>>> i=st.find('cal',10,15)
>>> print(i) #ouput is -1
th th
In this example, the substring 'cal' has not appeared between 10 and 15
character of st. Hence, the result is -1.
s.strip(): Returns a copy of string s by removing leading and trailing white spaces.
use.com
>>> print(st1)
hello world
The strip() function can be used with an argument chars, so that specified chars are
removed from beginning or ending of s as shown below –
>>> st="###Hello##"
>>> st1=st.strip('#')
>>> print(st1) #all hash symbols are removed
Hello
We can give more than one character for removal as shown below –
S.startswith(prefix, start, end): This function has 3 arguments of which start and end
are option. This function returns True if S starts with the specified prefix, False
otherwise.
When both start and end arguments are given, search begins at start and ends at
end.
>>> st="xyz abc pqr ab mn gh“
>>> st.startswith("pqr ab mn",8,12) #returns False
>>> st.startswith("pqr ab mn",8,18) #returns True
The startswith() function requires case of the alphabet to match. So, when we are
not sure about the case of the argument, we can convert it to either upper case
or lowercase and then use startswith()function as below –
>>> st="Hello"
>>> st.startswith("he") #returns False
>>> st.lower().startswith("he") #returns True
S.count(s1, start, end): The count() function takes three arguments – string, starting
position and ending position. This function returns the number of non-overlapping
occurrences of substring s1 in string S in the range of start and end.
.
>>> st.count('h') #output is 3
>>> st.count(‘how’) #output is 2
>>> st.count(‘how’,3,10) #output is 1 because of range given
There are many more built-in methods for string class. Students are advised to
explore more for further study.
Sometimes, we may want to search for a substring matching certain criteria. For example,
finding domain names from email-Ids in the list of messages is a useful task in some
projects. Consider a string below and we are interested in extracting only the domain name.
Now, our aim is to extract only ieee.org, which is the domain name. We can think of logic
as–
o Identify the position of @, because all domain names in email IDs will be after
the symbol @
o Identify a white space which appears after @ symbol, because that will be the
end of domain name.
o Extract the substring between @ and white-space.
The concept of string slicing and find() function will be useful here.Consider the code given
below –
Execute above program to get the output as ieee.org. One can apply this logic in a loop,
when our string contains series of email IDs, and we may want to extract all those mail IDs.
The format operator, % allows us to construct strings, replacing parts of the strings with the
data stored in variables. The first operand is the format string, which contains one or more
format sequences that specify how the second operand is formatted. The result is a string.
>>> sum=20
>>> '%d' %sum
‘20’ #string ‘20’, but not integer 20
Note that, when applied on both integer operands, the % symbol acts as a modulus
operator. When the first operand is a string, then it is a format operator. Consider
few examples illustrating usage of format operator.