Py Unit - 3
Py Unit - 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
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
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.
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!
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.
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
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.
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”)
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
Output will be
Greatest number is 20
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. ‘)
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
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:
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
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
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
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
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)
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!”
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.”)
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
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
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
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
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
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))
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
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)
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.
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
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. 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
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
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
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
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’]
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])
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
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)
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))
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))
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)
(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
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.
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
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
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
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