0% found this document useful (0 votes)
17 views53 pages

Py Unit - 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views53 pages

Py Unit - 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

3.

1 Conditionals
Flow of execution of instruction can be controlled using conditional statements.
Conditional statements have some Boolean expression. Boolean expression can have
relational operators or logical operators or both.
3.1.1 Boolean Expressions
A boolean expression is an expression it‘s result is either true or false. The
following examples use the operator ==, which compares two operands and produces
True if they are equal and False otherwise:\
>>> 9 == 9
True
>>> 9 == 6
False

True and False are special values that belong to the type bool; they are not
strings:
>>>type(True)
<class ‘bool’>
>>>type(False)
<class ‘bool’>
Boolean expression can have relational operators or logical operators. The ==
operator is one of the relational operators; the others are:
x==y #x is equal to y
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y x
<= y # x is less than or equal to y
3. 2 Problem Solving and Python Programming

More explanation can found in 2.5.2.Although these operations are probably


familiar to you, the Python symbols are different from the mathematical symbols.
A common error is to use a single equal sign (=) instead of a double equal sign (==).
Remember that = is an assignment operator and == is a relational operator. There
is no such thing as =< or =>.
3.1.2 Logical operators
There are three logical operators: and, or, and not. The semantics (meaning)
of these operators is similar to their meaning in English. This was explained in 2.5.3
For example
x> 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that
is, if the number is divisible by 2 or 3.

not operator negates a boolean expression, so not (x > y) is true if x > y is false,
that is, if x is less than or equal to y.
Note:- Any nonzero number is interpreted as True
>>>95 and True
True
>>>mark=95
>>>mark>0 and mark<=100
True
>>>mark=102
>>>mark>0 and mark<=100
False

3. 2 Selection
In Unit I, you were introduced to the concept of flow of control: the sequence of
statements that the computer executes. In procedurally written code, the computer
usually executes instructions in the order that they appear. However, this is not
always the case. One of the ways in which programmers can change the flow of
control is the use of selection control statements.
Now we will learn about selection statements, which allow a program to
choose when to execute certain instructions. For example, a program might choose
how to proceed on the basis of the user‘s input. As you will be able to see, such
statements make a program more versatile.
Lists, Tuples,Dictionaries 3.3

In python selection can be achieved through


££ if statement ££ if...elif...else
££ The elif Statement ££ Nested if statements
3.2.1 Conditional Execution
In order to write useful programs, we almost always need the ability to check
conditions and change the behaviour of the program accordingly. Selection or
Conditional statements give us this ability. The simplest form is the if statement:
General Syntax of if statement is
if TEST EXPRESSION:
STATEMENT(S)
# executed if condition evaluates to True

Here, the program evaluates the TEST EXPRESSION and will execute
statement(s) only if the text expression is True.If the text expression is False, the
statement(s) is not executed.
A few important things to note about if statements:
1. The colon (:) is significant and required. It separates the header of the
compound statement from the body.
2. The line after the colon must be indented. It is standard in Python to use
four spaces for indenting.
3. All lines indented the same amount after the colon will be executed
whenever the BOOLEAN_EXPRESSION is true.
4. Python interprets non-zero values as True. None and 0 are interpreted
as False.

Figure 3.1 if Statement Flowchart


3. 4 Problem Solving and Python Programming
Here is an example
mark = 102
if mark >= 100:
print(mark, “ is a Not a valid mark.”)
print(“This is always printed.”)

Output will be
102 is a Not a valid mark.
This is always printed

The boolean expression after the if statement (here mark>=100) is called the
condition. If it is true, then all the indented statements get executed.
There is no limit on the number of statements that can appear in the body,
but there has to be at least one. Occasionally, it is useful to have a body with no
statements (usually as a place keeper for code you haven‘t written yet). In that case,
you can use the pass statement, which does nothing.
if x < 0:
# TODO: need to handle negative values!

3.2.2 Alternative execution


A second form of the if statement is ―alternative execution , in which there are
two possibilities and the condition determines which one runs. In other words ,It is
frequently the case that you want one thing to happen when a condition it true, and
something else to happen when it is false. For that we have if else statement. The
syntax looks like this:
General Syntax of if ..elsestatement is
if TEST EXPRESSION:
STATEMENTS_1
# executed if condition evaluates to True
else:
STATEMENTS_2
# executed if condition evaluates to False

Each statement inside the if block of an if else statement is executed in order


if the test expression evaluates to True. The entire block of statements is skipped if
the test expression evaluates to False, and instead all the statements under the else
clause are executed.
Lists, Tuples,Dictionaries 3.5

There is no limit on the number of statements that can appear under the
two clauses of an if else statement, but there has to be at least one statement in
each block. Occasionally, it is useful to have a section with no statements, for code
you haven‘t written yet. In that case, you can use the pass statement, which does
nothing except act as a placeholder.

Figure 3.2 if..else Flowchart


if True: # This is always true
pass # so this is always executed, but it does nothing
else:
pass
age=21 #age=17
if age >= 18:
print(“Eligible to vote”)
else:
print(“Not Eligible to vote”)

Here is an example:
Output will be
Eligible to vote

In the above example, when age is greater than 18, the test expression is true
and body of if is executed and body of else is skipped.If age is less than 18, the test
expression is false and body of else is executed and body of if is skipped.If age is
equal to 18, the test expression is true and body of if is executed and body of else is
skipped.
3. 6 Problem Solving and Python Programming

3.2.3 Chained Conditionals


Sometimes there are more than two possibilities and we need more than two
branches. One way to express a computation like that is a chained conditional.
The syntax looks like this:
General Syntax of if..elif...else statement is
if TEST EXPRESSION1:
STATEMENTS_A elif
TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C

The elif is short for else if. It allows us to check for multiple expressions.If the
condition for if is False, it checks the condition of the next elif block and so on.If all
the conditions are False, body of else is executed.Only one block among
the several if...elif...else blocks is executed according to the condition.The if block
can have only one else block. But it can have multiple elif blocks.

Figure 3.3 Flowchart of if...elif...else


Each condition is checked in order. If the first is false, the next is checked, and
so on. If one of them is true, the corresponding branch executes, and the statement
ends. Even if more than one condition is true, only the first true branch executes.
Lists, Tuples,Dictionaries 3.7

Here is an example:
time=17 #time=10, time=13, time=17, time=22
if time<12:
print(“Good Morning”)
elif time<15:
print(“Good Afternoon”)
elif time<20:
print(“Good Evening”)
else:
print(“Good Night”)

Output will be:


Good Evening

When variable time is less than 12, Good Morning is printed.If time is
less than 15, Good Afternoon is printed.If time is less than 20, Good Evening is
printed. If all above conditions fails Good Night is printed.
3.2.4 Nested Conditionals
One conditional can also be nested within another. ie, We can have a if...elif...
else statement inside another if...elif...else statement. This is called nesting in
computer programming.
Any number of these statements can be nested inside one another. Indentation
is the only way to figure out the level of nesting.
General Syntax of Nested if..else statement is
if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
3. 8 Problem Solving and Python Programming

Figure 3.4 Flowchart of Nested if..else


The outer conditional contains two branches. Those two branches contain
another if… else statement, which has two branches of its own. Those two branches
could contain conditional statements as well.
Here is an example:
a=10
b=20
c=5
if a>b:
if a>c:
print(“Greatest number is “,a)
else:

print(“Greatest number is “,c)


else:
if b>c:
print(“Greatest number is “,b)
else:
print(“Greatest number is “,c)
Lists, Tuples,Dictionaries 3.9

Output will be
Greatest number is 20

Although the indentation of the statements makes the structure apparent,


nested conditionals very quickly become difficult to read. In general, it is a good idea
to avoid them when you can.
Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the above code using single if…elif…. else
statement:
a=10
b=20
c=5
if a>b and a>c:
print(“Greatest number is
“,a) elif b>a and b>c:
print(“Greatest number is “,b)
else:
print(“Greatest number is “,c)

Another example, we can rewrite the following code using a single conditional:
if 0 < x:
if x < 10:
print(‘x is a positive single-digit number. ‘)

The print statement runs only if we make it pass both conditionals, so we can
get the same effect with the and operator:
if 0 < x and x < 10:
print(‘x is a positive single-digit number. ‘)

For this kind of condition, Python provides a more concise option:


if 0 < x and x < 10:
print(‘x is a positive single-digit number. ‘)

3. 3 Iteration
Computers are often used to automate repetitive tasks. Repeating identical or
similar tasks without making errors is something that computers do well and people
do poorly.
3. 10 Problem Solving and Python Programming

Repeated execution of a set of statements is called iteration.Python has two


statements for iteration
££ for statement
££ while statement
Before we look at those, we need to review a few ideas.
Reassignmnent
As we saw back in the variable section, it is legal to make more than one
assignment to the same variable. A new assignment makes an existing variable
refer to a new value (and stop referring to the old value).
age = 26
print(age)
age = 17
print(age)
26
17

The output of this program is because the first time age is printed, its value is
26, and the second time, its value is 17.
Here is what reassignment looks like in a state snapshot:

Figure 3.5 State Diagram for Reassignment


With reassignment it is especially important to distinguish between an
assignment statement and a boolean expression that tests for equality. Because
Python uses the equal token (=) for assignment, it is tempting to interpret a statement
like a = b as a boolean test. Unlike mathematics, Remember that the Python token
for the equality operator is ==.
Note too that an equality test is symmetric, but assignment is not. For example,
if a == 7 then 7 == a. But in Python, the statement a = 7 is legal and 7 = a is not.
Further more, in mathematics, a statement of equality is always true.
If a == b now, then a will always equal b. In Python, an assignment statement can
make two variables equal, but because of the possibility of reassignment, they don‘t
have to stay that way:
Lists, Tuples,Dictionaries 3.11

a=5
b=a
a = 3 # after executing this line, a and b are now equal
# after executing this line, a and b are no longer equal

The third line changes the value of a but does not change the value of b, so they
are no longer equal.
Updating variables
When an assignment statement is executed, the right-hand-side expression (i.e.
the expression that comes after the assignment token) is evaluated first. Then the
result of that evaluation is written into the variable on the left hand side, thereby
changing it.
One of the most common forms of reassignment is an update, where the new
value of the variable depends on its old value.
n=5
n=3*n+1

The second line means ―get the current value of n, multiply it by three and add
one, and put the answer back into n as its new value . So after executing the two
lines above, n will have the value 16.
If you try to get the value of a variable that doesn‘t exist yet, you‘ll get an error:
>>> x = x + 1
Traceback (most recent call last):
File “<interactive input>”,
line 1, in NameError:
name ‘x’ is not defined

Before you can update a variable, you have to initialize it, usually with a
simple assignment:
>>> x = 0
>>> x = x + 1

This second statement — updating a variable by adding 1 to it. It is very common.


It is called an increment of the variable; subtracting 1 is called a decrement.
3. 12 Problem Solving and Python Programming

3.3.1 The while statement


The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.We generally use this loop when we don’t know
beforehand, the number of times to iterate.
The general syntax for the while statement :
while TEST_EXPRESSION:
STATEMENTS

In while loop, test expression is checked first. The body of the loop is entered
only if the TEST_EXPRESSION evaluates to True. After one iteration, the test
expression is checked again. This process continues until the TEST_EXPRESSION
evaluates to False.
In Python, the body of the while loop is determined through indentation.Body
starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as
False.
Flowchart of while Loop

Figure 3.6 Flowchart of while Loop


Example
Python program to find sum of first n numbers using while loop
Lists, Tuples,Dictionaries 3.13

n = 20
sum = 0 # initialize sum and counter
i=1
while i <= n:
sum = sum + i i = i+1
print(“The sum is”, sum) # update counter
# print the sum

When you run the program, the output will be:


The sum is 210

In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (20 in our program).
We need to increase the value of counter variable in the body of the loop. This
is very important (and mostly forgotten). Failing to do so will result in an infinite
loop (never ending loop).Finally the result is displayed.
3.3.2 The for Statement
The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.
The general syntax for the while statement
for LOOP_VARIABLE in SEQUENCE:
STATEMENTS

Here, LOOP_VARIABLE is the variable that takes the value of the item inside
the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
3. 14 Problem Solving and Python Programming

Figure 3.7 Flowchart of for Loop


Example
marks = [95,98,89,93,86]
total = 0
forsubject_mark in marks:
total = total+subject_mark
print (“Total Mark is “, total)

when you run the program, the output will be:


Total Mark is 461

We can use the range() function in for loops to iterate through a sequence of
numbers.
Example
sum=0
for i in range(20):
sum=sum+i
print(“Sum is “, sum)

Output will be:


Sum is 190

3.3.3 Break, Continue, Pass


You might face a situation in which you need to exit a loop completely when
an external condition is triggered or there may also be a situation when you want to
skip a part of the loop and start next execution.
Lists, Tuples,Dictionaries 3.15

Python provides break and continue statements to handle such situations


and to have good control on your loop.This section will discuss the
break, continue and pass statements available in Python.
3.3.3.1 The break Statement
The break statement in Python terminates the current loop and resumes
execution at the next statement. The most common use for break is when some
external condition is triggered requiring a hasty exit from a loop. The break
statement can be used in both while and for loops.
Example
for letter in ‘Welcome’: # First Example
if letter == ‘c’:
break
# Second Example
print(‘Current Letter :’, letter) var = 10
whilevar> 0:
print(‘Current variable value :’, var)
var = var -1
ifvar == 5:
break
print “End!”

This will produce the following output


Current Letter : W
Current Letter : e
Current Letter : l
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
End!

3.3.3.2 The continue Statement


The continue statement in Python returns the control to the beginning of
the while loop. The continue statement rejects all the remaining statements in the
3. 16 Problem Solving and Python Programming

current iteration of the loop and moves the control back to the top of the loop.The
continue statement can be used in both while and for loops.
Example
for letter in ‘Welcome’: # First Example
if letter == ‘c’:
continue print(‘Current Letter :’, letter) # Second Example
var = 10
whilevar> 0:
print(‘Current variable value :’, var) var = var -1
ifvar == 5:
continue
print “End!”

Thiswill produce the following output:


This will produce the following output:
Current Letter : W
Current Letter : e
Current Letter : l
Current Letter : o
Current Letter : m
Current Letter : e
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 5
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
End!
Lists, Tuples,Dictionaries 3.17

3.3.3.3 The else Statement Used with Loops


Python supports to have an else statement associated with a loop statements.
££ 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.
while loop with else
We can have an optional else block with while loop as well.The else part is
executed if the condition in the while loop evaluates to False. The while loop can be
terminated with a break statement.In such case, the else part is ignored. Hence, a
while loop’s else part runs if no break occurs and the condition is false.
Here is an example to illustrate this.
counter = 0
while counter < 3:
print(“Inside loop”)
counter = counter + 1
else:
print(“Inside else”)

Output
Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.On
the forth iteration, the condition in while becomes False. Hence, the else part is
executed.
for loop with else
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts.break statement can be used to
stop a for loop. In such case, the else part is ignored.Hence, a for loop’s else part runs
if no break occurs.
3. 18 Problem Solving and Python Programming
Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print(“No items left.”)

When you run the program, the output will be:


0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints
3.3.3.4 The pass Statement
In Python programming, pass is a null statement. The difference between
a comment and pass statement in Python is that, while the interpreter ignores
a comment entirely, pass is not ignored.However, nothing happens when pass is
executed. It results into no operation (NOP).
Syntax of pass
pass

We generally use it as a placeholder.


Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter
would complain. So, we use the pass statement to construct a body that does nothing.
Example
sequence = {‘p’, ‘a’, ‘s’, ‘s’} for
val in sequence:
pass

def function(args):
pass
Lists, Tuples,Dictionaries 3.19

3. 4 Fruitful Functions
3.4.1 Return Values
The built-in functions we have used, such as abs, pow, int, max, and range,
have produced results. Calling each of these functions generates a value, which we
usually assign to a variable or use as part of an expression.
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10

Here, we are going to write more functions that return values, which we will
call fruitful functions, for want of a better name. The first example is area, which
returns the area of a circle with the given radius:
def area(radius):
b = 3.14159 * radius**2
return b

We have seen the return statement before, but in a fruitful function


the return statement includes a return value. This statement means: evaluate the
return expression, and then return it immediately as the result of this function. The
expression provided can be arbitrarily complicated, so we could have written this
function like this:
def area(radius):
return 3.14159 * radius * radius

On the other hand, temporary variables like b above often make debugging
easier.
Sometimes it is useful to have multiple return statements, one in each branch
of a conditional. We have already seen the built-in abs, now we see how to write our
own:
defabsolute_value(x):
if x < 0:
return -x
else:
return x

Another way to write the above function is to leave out the else and just follow
the if condition by the second return statement.
3. 20 Problem Solving and Python Programming

defabsolute_value(x):
if x < 0:
return -x
return x

Think about this version and convince yourself it works the same as the first
one.
Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code, or unreachable code.
In a fruitful function, it is a good idea to ensure that every possible path through
the program hits a return statement. The following version of absolute_value fails
to do this:
defbad_absolute_value(x):
if x < 0:
return -
x elif x > 0:
return x

This version is not correct because if x happens to be 0, neither condition is


true, and the function ends without hitting a return statement. In this case, the
return value is a special value called None:
>>>print(bad_absolute_value(0))
None

All Python functions return None whenever they do not return another value.
It is also possible to use a return statement in the middle of a for loop, in which
case control immediately returns from the function. Let us assume that we want a
function which looks through a list of words. It should return the first 2-letter word.
If there is not one, it should return the empty string:
def find_first_2_letter_word(xs):
forwd in xs:
iflen(wd)==2:
returnwd
return””
Lists, Tuples,Dictionaries 3.21

While running output will be:


>>> find_first_2_letter_word([“This”, “is”, “a”, “dead”, “parrot”])
‘is’
>>> find_first_2_letter_word([“I”, “like”, “cheese”]) ‘’

Single-step through this code and convince yourself that in the first test case
that we‘ve provided, the function returns while processing the second element in the
list: it does not have to traverse the whole list.
3.4.2 Debugging with print
Another powerful technique for debugging (an alternative to single-stepping
and inspection of program variables), is to insert extra print functions in carefully
selected places in your code. Then, by inspecting the output of the program, you
can check whether the algorithm is doing what you expect it to. Be clear about the
following, however:
££ You must have a clear solution to the problem, and must know what
should happen before you can debug a program. Work on solving the
problem on a piece of paper (perhaps using a flowchart to record the
steps you take) before you concern yourself with writing code. Writing
a program doesn‘t solve the problem it simply automates the
manual steps you would take. So first make sure you have a pen- and-
paper manual solution that works. Programming then is about making
those manual steps happen automatically.
££ Do not write chatterbox functions. A chatterbox is a fruitful function
that, in addition to its primary task, also asks the user for input, or
prints output, when it would be more useful if it simply shut up and did
its work quietly.
For example, we‘ve seen built-in functions like range, max and abs. None of
these would be useful building blocks for other programs if they prompted the user
for input, or printed their results while they performed their tasks.
So a good tip is to avoid calling print and input functions inside fruitfulfunctions,
unless the primary purpose of your function is to perform input and output. The one
exception to this rule might be to temporarily sprinkle some calls to print into your
code to help debug and understand what is happening when the code runs, but these
will then be removed once you get things working.
3. 22 Problem Solving and Python Programming

3.4.3 Composition
You can call one function from within another. This ability is called
composition.
As an example, we‘ll write a function that takes two points, the center of the
circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle, which
is the distance between the two points. Fortunately, we‘ve just written a function,
distance, that does just that, so now all we have to do is use it:
radius = distance(xc, yc, xp, yp)

The second step is to find the area of a circle with that radius and return it.
Again we will use one of our earlier functions:
result = area(radius)
return result

Wrapping that up in a function, we get:


def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result

We called this function area2 to distinguish it from the area function defined
earlier.
The temporary variables radius and result are useful for d e v e l o p m e n t ,
debugging, and single-stepping through the code to inspect what is happening, but
once the program is working, we can make it more concise by composing the function
calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

3. 5 Scope: Global And Local


Namespace is a collection of names. In Python, you can imagine a namespace
as a mapping of every name; you have defined, to corresponding objects. Different
namespaces can co-exist at a given time but are completely isolated.
Lists, Tuples,Dictionaries 3.23

Although there are various unique namespaces defined, we may not be able to
access all of them from every part of the program. The concept of scope comes into
play.
Scope is the portion of the program from where a namespace can be accessed
directly without any prefix.
At any given moment, there are at least three nested scopes.
1. Scope of the current function which has local names
2. Scope of the module which has global names
3. Outermost scope which has built-in names
When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.
If there is a function inside another function, a new scope is nested inside the
local scope.
Example
defouter_function():
b = -India
definner_func():
c = -TamilNadu
a = -World

Here, the variable a is in the global namespace. Variable b is in the local


namespace of outer_function() and c is in the nested local namespace of inner_
function().
When we are in inner_function(), c is local to us, b is nonlocal and a is global.
We can read as well as assign new values to c but can only read b and a from inner_
function().
If we try to assign as a value to b, a new variable b is created in the local
namespace which is different than the nonlocal b. Same thing happens when we
assign a value to a.
However, if we declare a as global, all the reference and assignment go to
the global a. Similarly, if we want to rebind the variable b, it must be declared as
nonlocal. The following example will further clarify this.
3. 24 Problem Solving and Python Programming

defouter_function():
a =”i am in
India” definner_function():
a = “i am in TamilNadu”
print(‘a =’,a)
inner_function()
print(‘a =’,a)
a = “i am in
World” outer_function()
print(‘a =’,a)

As you can see, the output of this program is


a = i am in TamilNadu
a = i am in India
a = i am in World

In this program, three different variables a are defined in separate namespaces


and accessed accordingly. While in the following program,
defouter_function():
global a
a = “i am in India”
definner_function():
global a
a = “i am in TamilNadu”
print(‘a =’,a)
inner_function()
print(‘a =’,a)
a = “i am in World” outer_function()
print(‘a =’,a)

The output of the program is.


a = i am in TamilNadu
a = i am in TamilNadu
a = i am in TamilNadu

Here, all reference and assignment are to the global a due to the use of keyword
global.
Lists, Tuples,Dictionaries 3.25

3. 6 Recursion
A recursive function is a function which calls itself with “smaller (or
simpler)” input values. Generally if a problem can be solved utilizing solutions
to smaller versions of the same problem, and the smaller versions reduce to easily
solvable cases, then one can use a recursive function to solve that problem.
3.6.1 Base Condition in Recursion
Base case is the smallest version of the problem, which cannot expressed in
terms of smaller problems, Also this base case have predefined solution. In recursive
program, the solution to base case is provided and solution of bigger problem is
expressed in terms of smaller problems.
For Example
Following is an example of recursive function to find the factorial of an integer.
For positive values of n, let’s write n!, as we known n! is a product of numbers
starting from n and going down to 1. n! = n. (n-1)…… 2 .1. But notice that (n-1) 2.1
is another way of writing (n-1)!, and so we can say that n!=n.(n”1)!. So we wrote n!
as a product in which one of the factors is (n”1)!. You can compute n! by computing
(n”1)! and then multiplying the result of computing (n”1)! by n. You can compute the
factorial function on n by first computing the factorial function on n”1. So
computing (n”1)! is a subproblem that we solve to compute n!.
In the above example, base case for n == 1 is defined and larger value of number
can be solved by converting to smaller one till base case is reached.

Python program to find factorial of a given number using recursive


function is.
deffactorial(n):
ifn ==1:
return1
else:
return(n*factorial(n-1))
num = 5
print(“Thefactorialof”,num,”is”,factorial(num))
3. 26 Problem Solving and Python Programming
Output will be
The factorial of 7 is 120

In the above example, factorial() is a recursive functions as it calls itself.


When we call this function with a positive integer, it will recursively call itself by
decreasing the number.Each function call multiples the number with the factorial of
number 1 until the number is equal to one. This recursive call can be explained in
the following steps.

factorial(5) # 1st call with 5


5 * factorial(4) # 2nd call with 4
5 * 4 * factorial(3) # 3rd call with 3
5 * 4 * 3 * factorial(2) # 4th call with 2
5 * 4 * 3 * 2 * factorial(1) # 5th call with 1
5 * 4 * 3 * 2 * 1 # return from 5th call as n==1
5 * 4 * 3 * 2 # return from 4th call
5 * 4 * 6# return from 3rd call
5 * 24 # return from 2nd call
120 all
# return from 1st call

Our recursion ends when the number reduces to 1. This is called the base
condition.Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely
Advantages of recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3. Recursive functions are hard to debug.
Lists, Tuples,Dictionaries 3.27

3. 7 Strings
A string is a sequence of characters. You can access the characters one at a
time with the bracket operator:
>>>subject = ‘python’
>>>letter = subject [1]

The second statement selects character number 1 from fruit and assigns it
to letter. The expression in brackets is called an index. The index indicates which
character in the sequence you want. But you might not get what you expect:
>>>letter
‘y’

For most people, the first letter of ‘python’ is p, not y. But for computer scientists,
the index is an offset from the beginning of the string, and the offset of the first letter
is zero.
>>>letter = subject [0]
>>>letter

‘p’
So p is the 0th letter (―zero-eth ) of ‘python’, y is the 1th letter (―one-eth ), and
t is the 2thletter (―two-eth ).
As an index you can use an expression that contains variables and operators:
>>> i = 1
>>> subject
[i] ‘y’
>>> subject
[i+1] ‘t

But the value of the index has to be an integer. Otherwise you get:
>>>letter =subject [1.5]
TypeError: string indices must be integers

3.7.1 len()
len is a built-in function that returns the number of characters in a string:
3. 28 Problem Solving and Python Programming

>>>subject = ‘python’
>>>len(subject)
6

To get the last letter of a string, you might be tempted to try something like
this:
>>>length = len(subject)
>>>last = subject [length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in ‘python’ with the
index 6. Since we started counting at zero, the six letters are numbered 0 to 5.
To get the last character, you have to subtract 1 from length:
>>>last = subject [length-1]
>>>last
‘t’

Or you can use negative indices, which count backward from the end of the
string. The expression subject [-1] yields the last letter, subject [-2] yields the
second to last, and so on.
3.7.2 Traversal with a for Loop
A lot of computations involve processing a string one character at a time. Often
they start at the beginning, select each character in turn, do something to it, and
continue until the end. This pattern of processing is called a traversal. One way to
write a traversal is with a while loop:
index = 0
while index <len(subject):
letter = subjec [index]
print(letter)
index = index + 1

This loop traverses the string and displays each letter on a line by itself. The
loop condition is index <len(subjec), so when index is equal to the length of the
string, the condition is false, and the body of the loop doesn‘t run. The last character
accessed is the one with the index len(subjec)-1, which is the last character in the
Lists, Tuples,Dictionaries 3.29

string.
Another way to write a traversal is with a for loop: for letter in subject:
print(letter)


subject p y t h o n ‘
arrow
Index 0 1 2 3 4 5

Figure 3.8 Slice indices


Each time through the loop, the next character in the string is assigned to the
variable letter. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a
for loop to generate an abecedarian series (that is, in alphabetical order). In Robert
McCloskey‘s book MakeWay for Ducklings, the names of the ducklings are Jack,
Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names
in order:
prefixes = ‘JKLMNOPQ’
suffix = ‘ack’
for letter in prefixes:
print(letter + suffix)

The output is:


Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

3.7.3 String Slices


A segment of a string is called a slice. Selecting a slice is similar to selecting
a character:
3. 30 Problem Solving and Python Programming

>>> s = ‘Monty Python’


>>>s[0:5]
‘Monty’
>>>s[6:12]
‘Python’

The operator [n:m] returns the part of the string from the ―n-eth character
to the ―m-eth character, including the first but excluding the last. This
behavior is counterintuitive, but it might help to imagine the indices pointing
between the characters, as in Figure 3.8. If you omit the first index (before the colon),
the slice starts at the beginning of the string. If you omit the second index, the slice
goes to the end of the string:
>>>subject = ‘python’
>>>subject[:3]
. ‘pyt’
>>>subject[3:]
‘hon’

If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>>subject = ‘python’
>>>subject[3:3]
‘’

An empty string contains no characters and has length 0, but other than that,
it is the same as any other string.
Continuing this example, subject[:] gives entire string.
>>>subject = ‘python’
>>>subject[:]
python

3.7.4 Strings are Immutable


It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string. For example:
Lists, Tuples,Dictionaries 3.31

>>> greeting = ‘Hello, world!’


>>>greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
The reason for the error is that strings are immutable, which means you
can‘t change an existing string. The best you can do is create a new string that is a
variation on the original:
>>> greeting = ‘Hello, world!’
>>>new_greeting = ‘J’ + greeting[1:]
>>>new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
3.7.5 String Methods
Strings provide methods that perform a variety of useful operations. A method
is similar to a function it takes arguments and returns a value but the syntax is
different. A method is similar to a function it takes arguments and returns a value
but the syntax is different.
1. capitalize()
Returns a copy of the string with the first character of the string
capitalized
>>>a=’hello ‘
>>> a.capitalize()
‘Hello’
2. index()
This function indicates in which index the item is present
>>>a=’hello ‘
>>> a.index(‘l’)
2

3. rindex()
It is same as index() but it will display the rightmost index or last
index of the value
3. 32 Problem Solving and Python Programming

>>>a=’hello ‘
>>> a.rindex(‘l’)
3

4. isalnum()
Returns True if string contains alphabets or numbers.
>>>a=’hello ‘
>>> a.isalnum()
True

5. isdigit()
Returns True if string contains digits.
>>>a=’hello ‘
>>> a.isdigit()
False
6. isalpha()
Returns True if string contains alphabet.
>>>a=’hello ‘
>>> a.isalpha()
True
7. islower()
Tests if all characters of the string are in lowercase and returns True
if strin g is in lower case.
>>>a=’hello ‘
>>> a.islower()
True
8. isupper()
Tests if all characters of the string are in uppercase and returns True
if string is in upper case.
>>>a=’hello ‘
>>> a.isupper()
False
9. lower()
Lists, Tuples,Dictionaries 3.33

Returns a copy of string in which all characters are converted to


lowercase.
>>>a=’hello ‘
>>> a.lower()
‘hello’

10. count(str, beg, end)


Returns the number of occurrences of the value in string
>>>a=’hello ‘
>>> a.count(‘l’)
2

11. centre(width, fillchar)


Return a copy of string centered of the given width
>>>a=’hello ‘
>>> a.center(20)
‘hello‘

12. endswith(suffix)
>>>a=’hello ‘
>>> a.endswith(‘o’)
True

13. split()
Return a list of words in string which is separated by white space. This
function takes a string and splits it into individual words.
>>>a=’hello ‘
>>> a.split()
[‘hello’]
14. title()
Return the string as title. First letter of each word in string in
capitalize.
>>>a=’hello ‘
>>> a.title()
‘Hello’
3. 34 Problem Solving and Python Programming
15. 1swapcase()
It will change the case. If the given string is in uppercase this function
will convert into lower case and vice versa.
>>>a=’hello ‘
>>> a.swapcase()
‘HELLO’
16. join()
Return a string that is the concatenation of the strings in the sequence.
Join a list of words into a single string with string as its separator
>>>a=’hello ‘
>>> a.join(‘hai’)
‘hhelloahelloi’

17. 1startswith()
Returns True if the string starts with that value otherwise False
>>>a=’hello ‘
>>> a.startswith(‘h’)
True

18. 1upper( )
The method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses
the method syntax word.upper().
>>>word = ‘python’
>>>new_word = word.upper()
>>>new_word
‘PYTHON
19. find(obj)
It will display the lower index where the value is found otherwise
return -1
>>>word = ‘python’
>>>index = word.find(‘t’)
>>>index
2
Lists, Tuples,Dictionaries 3.35

3.7.6 The in Operator


The word in is a Boolean operator that takes two strings and returns True if
the first appears as a substring in the second:
>>> ‘t’ in ‘python’
True
>>> ‘jan’ in ‘python’
False

For example, the following function prints all the letters from word1 that also
appear in word2:
defin_both(word1, word2):
for letter in word1:
if letter in word2:
print(letter)

With well-chosen variable names, Python sometimes reads like English. You
could read this loop, ―for (each) letter in (the first) word, if (the) letter
(appears) in (the second) word, print (the) letter.
Here‘s what you get if you compare ‘django’ and ‘mongodb’
>>>in_both(‘django’,’mongodb’)
d
n
g
o

3.7.7 String Comparison


The relational operators work on strings. To see if two strings are equal:
if word == ‘python’:
print(‘All right, python.’)

Other relational operations are useful for putting words in alphabetical order:
if word < ‘ python ‘:
print(‘Your word, ‘ + word + ‘, comes before python.’)
elif word > ‘ python ‘:
print(‘Your word, ‘ + word + ‘, comes after python.’)
else:
print(‘All right, python.’)
3. 36 Problem Solving and Python Programming

Python does not handle uppercase and lowercase letters the same way people
do. All the uppercase letters come before all the lowercase letters, so:
Your word, Python, comes before c language

A common way to address this problem is to convert strings to a standard


format, such as all lowercase, before performing the comparison.

3. 8 Lists As Arrays
Most of programs work not only with variables. They also use lists of variables.
For example, a program can handle an information about students in a class by
reading the list of students from the keyboard or from a file. A change in the number
of students in the class must not require modification of the program source code.
To store such data, in Python you can use the data structure called list (in most
programming languages the different term is used — ―array ).
Arrays are sequence types and behave very much like lists, except that the type
of objects stored in them is constrained. A list (array) is a set of objects. Individual
objects can be accessed using ordered indexes that represent the position of each
object within the list (array).
The list can be set manually by enumerating of the elements the list in square
brackets, like here:
Primes = [2, 3, 5, 7, 11, 13]
Rainbow = [‘Red’, ‘Orange’, ‘Yellow’, ‘Green’, ‘Blue’, ‘Indigo’, ‘Violet’]

The list Primes has 6 elements, namely: Primes[0] == 2, Primes[1] == 3,


Primes[2] == 5, Primes[3] == 7,Primes[4] == 11, Primes[5] == 13. The list Rainbow
has 7 elements, each of which is the string.
Like the characters in the string, the list elements can also have negative
index, for example, Primes[-1] == 13,Primes[-6] == 2. The negative index means we
start at the last element and go left when reading a list.
You can obtain the number of elements in a list with the function
len (meaning length of the list), e.g.len(Primes) == 6.
Unlike strings, the elements of a list are changeable; they can be changed by
assigning them new values.
Consider several ways of creating and reading lists. First of all, you can create
an empty list (the list with no items, its length is 0), and you can add items to the end
Lists, Tuples,Dictionaries 3.37

of your list using append. For example, suppose the program receives the number of
elements in the list n, and then n elements of the list one by one each at the separate
line. Here is an example of input data in this format:
a = [] # start an empty list
n = int(input(‘Enter No of Elements’))
for i in range(n): # read number of element in the list
new_element = int(input
(‘Enter Element :’)) # read
next element a.append(new_element) # add it to the list
# the last two lines could be replaced
by one:
# a.append(int(input(‘Enter Element
: ’)))
print(a)

Output will be
Enter No of Elements5
Enter Element :2
Enter Element :7
Enter Element :4
Enter Element :3
Enter Element :8
[2, 7, 4, 3, 8]

In the demonstrated example the empty list is created, then the number of
elements is read, then you read the list items line by line and append to the
end. The same thing can be done, saving the variable n:
a = [0] * int(input(‘Enter No of Elements :’))
for i in range(len(a)):
a[i] = int(input(‘Enter Element : ‘))
print (a)

Next method to creating and reading lists is, first, consider the size of the
list and create a list from the desired number of elements, then loop through the
variable i starting with number 0 and inside the loop read i-th element of the list:
3. 38 Problem Solving and Python Programming
Output will be
Enter No of Elements :3 Enter Element : 2
Enter Element : 4 Enter Element : 3 [2, 4, 3]

You can print elements of a list a with print(a); this displays the list items
surrounded by square brackets and separated by commands. In general, this is
inconvenient; in common, you are about to print all the elements in one line or one
item per line. Here are two examples of that, using other forms of loop:
a = [1, 2, 3, 4, 5]
for i in range(len(a)):
print(a[i])

Here the index i is changed, then the element a[i] is displayed.


a = [1, 2, 3, 4, 5]
for elem in a:
print(elem, end=’ ‘)

In this example, the list items are displayed in one line separated by spaces,
and it’s not the index that is changed but rather the value of the variable itself
(for example, in the loop for elem in [‘red’, ‘green’, ‘blue’] variable elemwill take the
values ‘red’, ‘green’, ‘blue’ successively.

3. 9 Illustrative Programs
3.9.1 Square Roots
Loops are often used in programs that compute numerical results by starting
with an approximate answer and iteratively improving it. For example, one way of
computing square roots is Newton’s method. Suppose that you want to know the
square root of a. If you start with almost any estimate, x, you can compute a better
estimate with the following formula:
K+5ØNÜ
v - x/2 Type this Equavation
Y= X/2
For example, if a is 4 and x is 3:
Lists, Tuples,Dictionaries 3.39

>>> a = 4
>>> x = 3
>>> y = (x + a/x) / 2
>>>y 2.16666666667

The result is closer to the correct answer (“4 = 2). If we repeat the process with
the new estimate, it gets even closer:
>>> x = y
>>> y = (x + a/x) / 2
>>>y 2.00641025641

After a few more updates, the estimate is almost exact:


>>> x = y
>>> y = (x + a/x) / 2
>>>y 2.00001024003
>>> x = y
>>> y = (x + a/x) / 2
>>>y 2.00000000003

In general we don‘t know ahead of time how many steps it takes to get to the
right answer, but we know when we get there because the estimate stops changing:
>>> x = y
>>> y = (x + a/x) / 2
>>>y
2.0
>>> x = y
>>> y = (x + a/x) / 2
>>>y
2.0

When y == x, we can stop. Here is a program that starts with an initial estimate,
x= 0.5*a, and improves it until it stops changing:
3. 40 Problem Solving and Python Programming

defsquare_root(a):
x=.5*a while True:
print(x)
y = (x + a/x) / 2 if y == x:
break
x=y
print(“Square Root of “, a , “ is “, y)
square_root(25)

Output will be:


12.5
7.25
5.349137931034482
5.011394106532552
5.000012953048684
5.000000000016778
5.0
Square Root of 25 is 5.0

3.9.2 GCD
3.9.2.1 Euclidean algorithm
This algorithm is based on the fact that GCD of two numbers divides their
difference as well. In this algorithm, we divide the greater by smaller and take the
remainder. Now, divide the smaller by this remainder. Repeat until the remainder
is 0.
For example, if we want to find the GCD of 108 and 30, we divide 108 by 30.
The remainder is 18. Now, we divide 30 by 18 and the remainder is 12. Now, we
divide 18 by 12 and the remainder is 6. Now, we divide 12 by 6 and the remainder is
0. Hence, 6 is the required GCD.
Lists, Tuples,Dictionaries 3.41

defcomputeGCD(x, y):
while(y):F
x, y = y, x % y return x #can also be written as follows
#reminder=x%y
# x=y #y=reminder
a=108
b=30
print(‘GCD of ‘,a ,’ and ‘ , b, ‘ is ‘,computeGCD(a,b))

Output will be:


GCD of 108 and 30 is 6

Here we loop until y becomes zero. The statement x, y = y, x % y does swapping


of values in Python. In each iteration, we place the value of y in x and the remainder
(x % y) in y, simultaneously. When y becomes zero, we have GCD in x.
3.9.3 Exponentiation
Simplest way to find the exponentiation of a number xy in python is, the use
of ** operator
>>> 4**3
64

Another way to find the exponentiation of a number xy in python is, the use of
pow() function that is available in math module. eg
>>> import math
>>>math.pow(4,3)
64.0

We can also write our own function to find the exponentiation of a number xy
using looping statement.
3. 42 Problem Solving and Python Programming

defmy_pow(x,y):
powered = x if
y == 0:
powered=1
else:
while y > 1:
powered *= x y -= 1

return powered
a=4 b=3
print(a, ‘ Power ‘, b, ‘ is ‘, my_pow(a,b))

Output will be:


4 Power 3 is 64

3.9.4 Sum of a List (Array) of Numbers


Suppose that you want to calculate the sum of a list of numbers such as:
[1, 3,5,7,9]. An iterative function that computes the sum is shown inIterative
Summationprogram.The function uses an accumulator variable (Sum) to compute
a running total of all the numbers in the list by starting with 00 and adding each
number in the list.
Iterative Summation:
deflistsum(numList):
Sum = 0
for i in numList:
Sum = Sum + i
return Sum
my_list=[1,3,5,7,9]
print(listsum(my_list))

Output will be:


25

Pretend for a minute that you do not have while loops or for loops. How would
you compute the sum of a list of numbers? If you were a mathematician you
might start by recalling that addition is a function that is defined for two parameters,
Lists, Tuples,Dictionaries 3.43

a pair of numbers. To redefine the problem from adding a list to adding pairs of
numbers, we could rewrite the list as a fully parenthesized expression. Such an
expression looks like this:
((((1+3)+5)+7)+9)

We can also parenthesize the expression the other way around,

(1+(3+(5+(7+9))))
Notice that the innermost set of parentheses, (7+9), is a problem that we can
solve without a loop or any special constructs. In fact, we can use the following
sequence of simplifications to compute a final sum.
total= (1+(3+(5+(7+9))))
total= (1+(3+(5+16)))
total= (1+(3+21))
total= (1+24)
total= 25
How can we take this idea and turn it into a Python program? First, let‘s
restate the sum problem in terms of Python lists. We might say the sum of the list
numList is
the sum of the first element of the list (numList[0]),and the sum of the numbers
in the rest of the list (numList[1:]).To state it in a functional form:
list Sum(numList)=first(numList)+listSum(rest(numList))
In this equation first(numList)) returns the first element of the list and
rest(numList) returns a list of everything but the first element. This is easily
expressed in Python as shown in Recursive Summation program.
Recursive Summation:
deflistsum(numList):
iflen(numList) == 1:
returnnumList[0]
else:
returnnumList[0] +
listsum(numList[1:]) my_list=[1,3,5,7,9]
print(listsum(my_list))
3. 44 Problem Solving and Python Programming

Output will be:


25

There are a few key ideas in this listing to look at. First, on line 2we are
checking to see if the list is one element long. This check is crucial and is our escape
(base case) clause from the function. The sum of a list of length 1 is trivial; it is just
the number in the list. Second, on line 5 our function calls itself! This is the reason
that we call the listsum algorithm recursive. A recursive function is a function that
calls itself.
Figure 3.9 shows the series of recursive calls that are needed to sum the list
[1,3,5,7,9]. You should think of this series of calls as a series of simplifications. Each
time we make a recursive call we are solving a smaller problem, until we reach the
point where the problem cannot get any smaller.

Figure 3.9 Recursive Calls in List Sum


When we reach the point where the problem is as simple as it can get, we begin
to piece together the solutions of each of the small problems until the initial problem
is solved. Figure 3.10 shows the additions that are performed as listsum works its
way backward through the series of calls. When listsum returns from the topmost
problem, we have the solution to the whole problem.
Lists, Tuples,Dictionaries 3.45

Figure 3.10 Recursive Return for List Sum


3.9.5 Linear Search
Given an array arr[] of n elements, write a function to search a given element
x in arr[]. A simple approach is to do linear search, i.e
££ Start from the leftmost element of arr[] and one by one compare x with
each element of arr[]
££ If x matches with an element, return the index.
££ If x doesn‘t match with any of elements, return -1.
Example

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9


3. 46 Problem Solving and Python Programming

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

56 3 249 518 7 26 94 651 23 9

Figure 3.11 Linear Search : Searching for 9 in 10 Element Array.


deflinear_search(arr, x):
for i in range(len(arr)):
ifarr[i] == x:
return i
return -1
data = []
n = int(input(‘Enter Number of Elements in the Array: ‘))
for i in range(0, n):
data.append(input(‘Enter the Element :’))
x = input(‘Enter the Element to be Search ‘)
found=linear_search(data,x)
if found!=-1:
print(‘Element ‘, x,’ Found at Position ‘,found+1)
else:
print(‘Element ‘,x,’ is Not Found in the Array ‘)

Output will be
Enter Number of Elements in the Array: 5
Enter the Element : 2
Enter the Element : 7
Enter the Element : 4
Enter the Element : 9
Enter the Element : 1
Enter the Element to be Search 9
Element 9 Found at Position 4
Lists, Tuples,Dictionaries 3.47

The time complexity of above algorithm is O(n).


Linear search is rarely used practically because other search algorithms such
as the binary search algorithm and hash tables allow significantly faster searching
comparison to Linear search.
3.9.6 Binary Search
Given a sorted array arr[] of n elements, write a function to search a given
element x in arr[].A simple approach is to do linear search.The time complexity of
above algorithm is O(n). Another approach to perform the same task is using Binary
Search.
Binary Search: Search a sorted array by repeatedly dividing the search
interval in half. Begin with an interval covering the whole array. If the value of the
search key is less than the item in the middle of the interval, narrow the interval
to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the
value is found or the interval is empty.
Example:

2 5 8 12 16 23 38 56 72 91

L H
23 > 16,
2 5 8 12 16 23 38 56 72 91
take 2ndt half

L H
23 > 56,
2 5 8 12 16 23 38 56 72 91
take 1st half
L H
Found 23,
Return 5 2 5 8 12 16 23 38 56 72 91

Figure 3.12 Binary Search: Searching for 23 in 10 Element Array.


The idea of binary search is to use the information that the array is sorted and
reduce the time complexity to O(Logn).
We basically ignore half of the elements just after one comparison.
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half
subarray after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
3. 48 Problem Solving and Python Programming
Recursive implementation of Binary Search
defbinarySearch (arr, left, right, x):
ifright>= left:
mid = left + (right - left)/2 ifarr[mid] == x:
return
mid elifarr[mid] > x:
returnbinarySearch(arr, left, mid-1, x)
else:
returnbinarySearch(arr, mid+1, right, x)
else:
return -1
data = []
n = int(input(‘Enter Number of Elements in the Array: ‘))
for i in range(0, n):
data.append(input(‘Enter the Element :’))
x = input(‘Enter the Element to be Search ‘)
result = binarySearch(data, 0, len(data), x)
if result != -1:
print (“Element is present at index “, result+1)
else:
print (“Element is not present in array”)

Output will be:


Enter Number of Elements in the Array: 5
Enter the Element :2
Enter the Element :7
Enter the Element :9
Enter the Element :11
Enter the Element :14
Enter the Element to be Search 11
Element is present at index 4
Lists, Tuples,Dictionaries 3.49

Iterative Implementation of Binary Search


defbinarySearch(arr, left, right, x):
whileleft<= right:
mid = left + (right - left)/2;
ifarr[mid] == x:
return
mid elifarr[mid] < x:
left= mid + left else:
right= mid -
left return -1
data = []
n = int(input(‘Enter Number of Elements in the Array: ‘))
for i in range(0, n):
data.append(input(‘Enter the Element :’))
x = input(‘Enter the Element to be Search ‘)
result = binarySearch(data, 0, len(data), x)
if result != -1:
print (“Element is present at index “, result+1)
else:
print (“Element is not present in array”)

Auxiliary Space: O(1) in case of iterative implementation. In case


of recursive implementation, O(Logn) recursion call stack space.

3. 10 With Answers
Two Marks Questions
1. What is Boolean value?
A Boolean value is either true or false. In Python, the two Boolean values are
True and False (the capitalization must be exactly asshown), and the Python
type is bool.
>>> type(True)
2. What is Boolean Expression?
A Boolean expression is an expression that evaluates to produce a result
which is a Booleanvalue. For example, the operator == tests if two values are
equal. It produces (or yields) aBoolean value:
3. 50 Problem Solving and Python Programming

>>> 5 == (3 + 2) # Is five equal 5 to the result of 3 + 2?


True
3. What is meant by conditional If?
The if statement in python is used to test a condition. If condition is true,
statement of if block is executed otherwise it is skipped.Syntax of python if
statement:
if(condition):
statements
4. What is chained conditional statement?
To check for multiple conditions elif Statement is used.This statement is like
executing a if statement inside a else statement. Syntax: If statement:
statements
elif
statement:
statements
else:
statements
5. Write the syntax and usage of for loop
For Loop is used to iterate a variable over a sequence(i.e., list or string) in the
order that they appear.Syntax:
for <variable> in <sequence>:
6. Write the syntax and usage of while loop
While Loop is used to execute number of statements or body till the condition
passed in while is true. Once the condition is false, the control will come out of
the loop.
Syntax:
while
<expression>: Body
7. What is python break statement?
Break statement is a jump statement that is used to pass the control to the
end of the loop. Applying break statement makes the loop to terminate and
controls goes to next line pointing after loop body.
Lists, Tuples,Dictionaries 3.51

8. What is python continue statement?


Continue Statement is a jump statement that is used to skip the present
iteration and forces next iteration of loop to take place. It can be used in while
as well as for loop statements.
9. What is python pass statement?
When you do not want any code to execute, pass Statement is used. It is same
as the name refers to. It just makes the control to pass by without executing
any code.
Syntax:
pass
10. What is len function and explain how it is used on strings with an
example.
The len function, when applied to a string, returns the number or character in
a string.
Example
>>>book=‘Problem Solving and Python Programming‘
>>>l
en(book) 38
>>>
11. Explain about string slicing with examples.
A substring of a string is obtained by taking a slice. The operator [n:m] returns
the part of the string from the nth character to the mth character, including
the first but excluding the last.
>>>book=‘Problem Solving and Python Programming‘ >>>print(book[0:7])
Problem
>>>print(book[21:27]) python
12. What are the two operators that are used in string functions?
The in operator tests for membership.
>>>‘V‘ in _SP‘
True
>>>‘S‘ in _SP‘
>>>False
3. 52 Problem Solving and Python Programming

The not in operator returns the logical opposite results of in operator.


>>>‘x‘ not in _SP‘
True
13. What is the use of str.upper() and str.lower() functions in string?
The functions str.upper() and str.lower() will return a string with all the letters
of original string converted to upper or lower case letters.
>>>ss=‘Sahana Publishers’
>>>print(ss. upper()) ‘Sahana Publishers‘
>>>print(ss
. lower()) Sahana Publishers
14. Explain string comparison with an example.
The comparison operator works on string to check if two strings are equal.
>>>word=‘VRB Publishers‘
>>>if word==‘VRB Publishers‘ Print(_Both are Equal‘)
Both are Equal
15. How to split strings and what function is used to perform that
operation?
The str.split() method is used to split strings up.
>>>book=‘Problem Solving and Python Programming‘
>>>print(book.split())
[_Problem‘, _Solving‘, _and‘, _Python‘, _Programing‘]

Review 3. 11
Questions
1. Explain the function arguments in python
2. Explain call by value and call by reference in python
3. Briefly explain about function prototypes
4. Answer the following questions.
a. What is String? How do u create a string in Python? (4 marks)
b. How to perform a user input in Python? Explain with example. (4 marks)
c. Write a program to check whether entered string is palindrome or not.
(4 marks)
5. Answer the following questions.
Lists, Tuples,Dictionaries 3.53

a. What is the output produced by this program given below? (8 marks)


words = _Hello
World‘ print words.title()
print
words.replace(–World‖,‘Osw al‘)
print
words.upper()
print words*2
Assuming num=125, determine the value of each of the following Python
expressions. (8 marks)

i. num/125
ii. (num%100
iii. (num==2 1)&(2<3)
iv. not((num<45.9)&(6*2<=13))

You might also like