Unit Iii
Unit Iii
2 For loop This type of loop executes a code block multiple times and abbreviates
the code that manages the loop variable.
Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known
as iteration.
In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
SRINIVASARAO G (PROF)-VITAP 1
PROBLEM SOLVING USING PYTHON
Code
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
As already said,a for loop executes the code block until the sequence element is reached. The
statement is written right after the for loop is executed after the execution of the for loop is
complete.
Only if the execution is complete does the else statement comes into play. It won't be executed if
we exit the loop or if an error is thrown.
Code
SRINIVASARAO G (PROF)-VITAP 2
PROBLEM SOLVING USING PYTHON
6. if s == "o":
SRINIVASARAO G (PROF)-VITAP 2
PROBLEM SOLVING USING PYTHON
7. print("If block")
8. # if condition is not satisfied then else block will be executed
9. else:
10. print(s)
Output:
P
y
t
h
If block
n
L
If block
If block
p
Syntax:
Code
1. # Python program to show how to use else statement with for loop
2. # Creating a sequence
3. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
4. # Initiating the loop
5. for value in tuple_:
6. if value % 2 != 0:
7. print(value)
8. # giving an else statement
9. else:
10. print("These are the odd numbers present in the tuple")
SRINIVASARAO G (PROF)-VITAP 3
PROBLEM SOLVING USING PYTHON
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
With the help of the range() function, we may produce a series of numbers. range(10) will produce
values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size).
If the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.
Code
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
SRINIVASARAO G (PROF)-VITAP 4
PROBLEM SOLVING USING PYTHON
To iterate through a sequence of items, we can apply the range() method in for loops. We can
use indexing to iterate through the given sequence by combining it with aniterable's len() function.
Here's an illustration.
Code
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the statement
in the program that follows the while loop is executed once the condition changes to false.
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code block. These statements
are intended with the same number of spaces. Python groups statements together with
indentation.
Code
SRINIVASARAO G (PROF)-VITAP 5
PROBLEM SOLVING USING PYTHON
6. print("Python Loops")
SRINIVASARAO G (PROF)-VITAP 5
PROBLEM SOLVING USING PYTHON
Output:
Python Loops
Python Loops
Python Loops
Python Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop
also. It has the same syntax.
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3. # Iterating through the while loop
4. while (counter < 10):
5. counter = counter + 3
6. print("Python Loops") # Executed until condition is met
7. # Once the condition of while loop gives False this statement will be executed
8. else:
9. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
SRINIVASARAO G (PROF)-VITAP 6
PROBLEM SOLVING USING PYTHON
The loop can be declared in asingle statement, as seen below. This is similar to the if-else block,
where we can write the code block in a single line.
Code
Nested Loops
. A nested loop is a loop inside the body of the outer loop. The inner or outer loop
can be any type, such as awhile looporfor loop. For example, the outer for
loop can contain a while loop and viceversa.
. The outer loop can contain more than one inner loop. There is no limitation on the
chaining of loops.
. In the nested loop, the number of iterations will be equal to the number of
iterations in the outer loop multiplied by the iterations in the inner loop.
. In each iteration of the outer loop inner loop execute all its iteration. For each
iteration of an outer loop the inner loop re-start and completes its execution before
the outer loop can continue to its next iteration.
. Nested loops are typically used for working with multidimensional data structures,
such as printing two-dimensional arrays, iterating a list that contains a nested list.
. In Python, the for loop is used to iterate over a sequence such as a list, string,
tuple, other iterable objects such as range.
SRINIVASARAO G (PROF)-VITAP 7
PROBLEM SOLVING USING PYTHON
In this example, we are using a for loop inside a for loop. In this example, we are
printing a multiplication table of the first ten numbers.
. The outer for loop uses therange()function to iterate over the first ten numbers
. The inner for loop will execute ten times for each outer number
. In the body of the inner loop, we will print the multiplication of the outer number and
current number
. The inner loop is nothing but a body of an outer loop.
# outer loop
for i in range(1, 11):
# nested loop
# to iterate from 1 to 10
for j in range(1, 11):
# print multiplication
SRINIVASARAO G (PROF)-VITAP 8
PROBLEM SOLVING USING PYTHON
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Pattern:
*
* *
* * *
* * * *
* * * * *
SRINIVASARAO G (PROF)-VITAP 9
PROBLEM SOLVING USING PYTHON
Program:
rows = 5
# outer loop
for i in range(1, rows + 1):
# inner loop
for j in range(1, i + 1):
. In each iteration of outer for loop, the inner for loop execute five times to print the
current name five times
# outer loop
for name in names:
# inner while loop
count = 0
while count < 5:
print(name, end=' ')
# increment counter
count = count + 1
print()
SRINIVASARAO G (PROF)-VITAP 10
PROBLEM SOLVING USING PYTHON
Output:
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.
SRINIVASARAO G (PROF)-VITAP 11
PROBLEM SOLVING USING PYTHON
Break
n-=5
while n>0:
n=n-1
if n==2:
break
print(n)
print(‘loop is finished’)
Output:
4
3
Loop is finished
Continue
n-=5
while n>0:
n=n-1
if n==2:
continue
print(n)
print(‘loop is finished’)
Output:
4
3
1
Loop is finished
SRINIVASARAO G (PROF)-VITAP 12
PROBLEM SOLVING USING PYTHON
Pass
. The null statement is another name for the pass statement. A Comment is not ignored
by the Python interpreter, whereas a pass statement is not. Hence, they two are
different Python keywords.
. We can use the pass statement as a placeholder when unsure what code to provide.
So, we only have to place the pass on that line.
. Pass may be used when we don't wish any code to be executed. We can simply
insert a pass in places where empty code is prohibited, such as loops, functions, class
definitions, or if- else statements.
3. if value == "Pass":
4. pass # leaving an empty if block using the pass keyword
5. else:
6. print("Not reached pass keyword: ", value)
Output:
Not reached keyword: Python
pa
Not reached keyword: Placeholder
ss
Not reached keyword: Statement
pa
SRINIVASARAO G (PROF)-VITAP 13
PROBLEM SOLVING USING PYTHON
Python Regex
. A regular expression is a set of characters with highly specialized syntax that we can
use to find or match other characters or groups of characters.
. In short, regular expressions, or Regex, are widely used in the UNIX world.
. There-module in Python gives full support for regular expressions of Pearl style.
. The re module raises the re.error exception whenever an error occurs while
implementing or using a regular expression.
re.match()
. Python's re.match() function finds and delivers the very first appearance of a
regular expression pattern.
. In Python, the RegEx Match function solely searches for a matching string at the
beginning of the provided text to be searched.
. The matching object is produced if one match is found in the first line.
. If a match is found in a subsequent line, the Python RegEx Match function gives
output as null.
. Examine the implementation for there.match() method in Python.
The expressions ".w*" and ".w*?" will match words that have the letter "w," and
anything that does not has the letter "w" will be ignored.
. The for loop is used in this Python re.match() illustration to inspect for matches for
every element in the list of words.
Matching Characters
. The majority of symbols and characters will easily match.
. The regular expression check, for instance, will match exactly the string check.
. There are some exceptions to this general rule; certain symbols are special
metacharacters that don't match.
. Rather, they indicate that they must compare something unusual, or they have an effect
on other parts of the RE by recurring or modifying their meaning.
.^$*+?{}[]\|()
SRINIVASARAO G (PROF)-VITAP 14
PROBLEM SOLVING USING PYTHON
Repeating Things
. The ability to match different sets of symbols will be the first feature regular
expressions can achieve that's not previously achievable with string techniques.
. On the other hand, Regexes isn't much of an improvement if that had been their
only extra capacity. We can also define that some sections of the RE must be reiterated a
specified number of times.
. The first metacharacter we'll examine for recurring occurrences is *. Instead of
matching the actual character '*,' * signals that the preceding letter can be matched 0 or
even more times,
rather than exactly one.
Ba*t, for example, matches 'bt' (zero 'a' characters), 'bat' (one 'a' character), 'baaat'
(three 'a' characters), etc.
. Greedy repetitions, such as *, cause the matching algorithm to attempt to replicate the
RE as many times as feasible. If later elements of the sequence fail to match, the
matching algorithm will retry with lesser repetitions.
Python RegEx
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For example,
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a
and ending with s .
ab No match
s
SRINIVASARAO G (PROF)-VITAP 15
PROBLEM SOLVING USING PYTHON
abys Match
s
SRINIVASARAO G (PROF)-VITAP 15
PROBLEM SOLVING USING PYTHON
Alia No match
s
An No match
abacus
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
. Here, we used
re.match( function to search patter within the
test_string . The method
returns a match object if the search is successful. If not, it returns .
Non
. There are other several functions defined in the module to work with RegEx.
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of
metacharacters:
[].^$*+?{}()\|
SRINIVASARAO G (PROF)-VITAP 16
PROBLEM SOLVING USING PYTHON
[]
- Square
Square brackets specifies a set of characters you wish to match.
1 match
2 matches
[abc]
Hey
Jude No
match
abcde
ca
[a a or
. Here, will match if the string you are trying to match contains any of the
-
. You can also specify a range of characters using inside square
[a-e]
brackets. is the same as [abcde] .
. - Period
A period matches any single character (except newline '\ ).
Expression String Matched?
a No match
.
SRINIVASARAO G (PROF)-VITAP 17
PROBLEM SOLVING USING PYTHON
ac 1 match
ac 1 match
d
^ - Caret
The caret symbol ^ is used to check if a string starts with a certain character.
a 1 match
ab 1 match
c
No
ba
c
1
ab
c
No match (starts with a but not followed
^a
b
SRINIVASARAO G (PROF)-VITAP 18
PROBLEM SOLVING USING PYTHON
ac
b
SRINIVASARAO G (PROF)-VITAP 18
PROBLEM SOLVING USING PYTHON
$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.
1 match
a formul 1
a
No
ca
b
* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.
Expression String Matched?
1
m
n
ma
n
ma* 1
maaa
n
No match (a is not followed
mai
n 1
woma
SRINIVASARAO G (PROF)-VITAP 19
PROBLEM SOLVING USING PYTHON
n
SRINIVASARAO G (PROF)-VITAP 19
PROBLEM SOLVING USING PYTHON
+
-
The plus symbol matches one or more occurrences of the pattern left to it.
m
n No match (no
ma 1
n matc
h
ma+
maaa
n
woma
n
- Question Mark
The question mark matches zero or one occurrence of the pattern left to it.
Expression String Matched?
m 1 match
ma 1 match
ma?
n
maaa
No match (more than one a character)
SRINIVASARAO G (PROF)-VITAP 20
PROBLEM SOLVING USING PYTHON
woma 1
n
- Braces
Consider this code: {n, . This means atleast , and at most repetitions of the pattern left to it.
Expression String Matched?
No match
abcda
t
1 match (atdaa )
abc
daat
2 matches (at aab anddaaa
a{2,3 )
}
aabc aab daaaa
daaat
aabc
daaaat
Let's try one more example. This RegEx [0 -9]{2, 4} matches atleast 2 digits but not more than 4
digits
Expression String Matched?
1 and 2
No match
SRINIVASARAO G (PROF)-VITAP 21
PROBLEM SOLVING USING PYTHON
| - Alternation
Vertical bar | is used for alternation (or operator) .
cd
e No
a| ad 1 match (match at
e
3 matches (at
acdbe
acdbe
a
- Group
Parentheses () is used to group sub-patterns. For example, (a|b| match any string that matches
either or b or c followed by
abxz No match
1 match (match at )
axz 2 matches )
axzbc
SRINIVASARAO G (PROF)-VITAP 22
PROBLEM SOLVING USING PYTHON
cabxz
SRINIVASARAO G (PROF)-VITAP 22
PROBLEM SOLVING USING PYTHON
\ - Backslash
Backlash \ is used to escape various characters including all metacharacters. For example,
\$a match if a string contains $ followed by a . Here, $ is not interpreted by a RegEx engine in
a special
way.
If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes
sure
Special Sequences
Special sequences make commonly used patterns easier to write. Here's a list of special
sequences:
the No
sun
\Athe
In the
sun
Mat
\b - Matches if the specified characters are at the beginning or end of a word.
footbal
l
No
a
football
SRINIVASARAO G (PROF)-VITAP 23
PROBLEM SOLVING USING PYTHON
afootball
SRINIVASARAO G (PROF)-VITAP 23
PROBLEM SOLVING USING PYTHON
the Mat
foo
foo\b Mat
the
afootest
No
the
afootest
\B - Opposite of \ Matches if the specified characters are not at the beginning or end of a word.
b .
Expression String No
Matched?
\ footbal
l No
a Mat
football
No
afootball
foo\B No
the
foo
Mat
the
afootest
SRINIVASARAO G (PROF)-VITAP 24
PROBLEM SOLVING USING PYTHON
the
afootest
SRINIVASARAO G (PROF)-VITAP 24
PROBLEM SOLVING USING PYTHON
Pytho
n No
134 No match
1
Python
RegEx
\s No
PythonRegE
x
SRINIVASARAO G (PROF)-VITAP 25
PROBLEM SOLVING USING PYTHON
ab
2 matches (at ab)
\S
No match
%"> No match
1 match (at
1a2%
1a2%
c
\W
No
Pytho
n
SRINIVASARAO G (PROF)-VITAP 26
PROBLEM SOLVING USING PYTHON
I like 1
Python
Python\ No
I like Python
Programming
No
Python is
fun.
Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import the
module.
import re
The module defines several functions and constants to work with RegEx.
re.findall()
The re.findall( method returns a list of strings containing all matches.
Example 1: re.findall()
SRINIVASARAO G (PROF)-VITAP 27
PROBLEM SOLVING USING PYTHON
import re
SRINIVASARAO G (PROF)-VITAP 27
PROBLEM SOLVING USING PYTHON
re.split()
The re.spli method splits the string where there is a match and returns a list of strings where the
splits
have occurred.
Example 2: re.split()
import re
You can pass argument to there.split( method. It's the maximum number of splits
maxspli
t
occur.
SRINIVASARAO G (PROF)-VITAP 28
PROBLEM SOLVING USING PYTHON
import re
# maxsplit = 1
# split only at the first occurrence
result = re.split(pattern, string, 1)
print(result)
SRINIVASARAO G (PROF)-VITAP 28
PROBLEM SOLVING USING PYTHON
By the way, the default value ofmaxspli is 0; meaning all possible splits.
re.sub()
The syntax of re.sub() is:
The method returns a string where matched occurrences are replaced with the content
of replac variable.
Example 3: re.sub()
# multiline string
string = 'abc 12\
de 23 \nf45 6'
# empty string
replace = ''
# Output: abc12de23f456
If the pattern is not found,re.sub() returns the original string.
SRINIVASARAO G (PROF)-VITAP 29
PROBLEM SOLVING USING PYTHON
SRINIVASARAO G (PROF)-VITAP 29
PROBLEM SOLVING USING PYTHON
pattern = '\s+'
replace = ''
# Output:
# abc12de 23
# f45 6
re.subn()
The re.subn() is similar to re.sub() except it returns a tuple of 2 items containing the new string and
the
# multiline string
string = 'abc 12\
de 23 \nf45 6'
# empty string
replace = ''
# Output: ('abc12de23f456', 4)
re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the first
location where the RegEx pattern produces a match with the string.
SRINIVASARAO G (PROF)-VITAP 30
PROBLEM SOLVING USING PYTHON
Example 5: re.search()
import re
if match:
print("pattern found inside the string")
else:
print("pattern not found")
Match object
You can get methods and attributes of a match object using dir()function.
Some of the commonly used methods and attributes of match objects are:
match.group()
The group( method returns the part of the string where there is a match.
Example 6: Match object
SRINIVASARAO G (PROF)-VITAP 31
PROBLEM SOLVING USING PYTHON
import re
SRINIVASARAO G (PROF)-VITAP 31
PROBLEM SOLVING USING PYTHON
if match:
print(match.group())
else:
print("pattern not found")
# Output: 801 35
Here, matc variable contains a match object.
Our pattern
these (\d{3}) (\d{2})
parenthesized has two Here's
subgroups. subgroups
how:(\d{3}) and (\d{2}) You can get the part of the string of
.
>>> match.group(1, 2)
('801', '35')
>>> match.groups()
The start( function returns the indexof the start of the matched substring. Similarly,end( returns the
end indexof the matched substring.
>>> match.start()
2
>>> match.end()
8
The span( function returns a tuple containing start and end indexof the matched part.
)
>>> match.span()
SRINIVASARAO G (PROF)-VITAP 32
PROBLEM SOLVING USING PYTHON
(2, 8)
SRINIVASARAO G (PROF)-VITAP 32
PROBLEM SOLVING USING PYTHON
>>> match.string
'39801 356, 2102 1111'
import re
SRINIVASARAO G (PROF)-VITAP 33