GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING - by WWW - LearnEngineering.in PDF
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING - by WWW - LearnEngineering.in PDF
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING - by WWW - LearnEngineering.in PDF
in
UNIT I
ALGORITHMIC PROBLEM SOLVING
GE8151 - PROBLEM SOLVING AND PYTHON 1.1 ALGORITHMS
PROGRAMMING In computing, we focus on the type of problems categorically known as algorithmic
problems, where their solutions are expressible in the form of algorithms.
The term „algorithm‟ was derived from the name of Mohammed al-Khowarizmi, a
Persian mathematician in the ninth century. Al-Khowarizmi → Algorismus (in Latin) →
REGULATIONS – 2017 Algorithm.
UNIT – I
set of values, as output. In other word, an algorithm is a procedure that accepts data;
manipulate them following the prescribed steps, so as to eventually fill the required unknown
with the desired value(s).
People of different professions have their own form of procedure in their line of work,
and they call it different names. For instance, a cook follows a procedure commonly known
as a recipe that converts the ingredients (input) into some culinary dish (output), after a
certain number of steps.
1 2
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
proceeds through a finite number of well-defined successive states, eventually producing for it to turn green. She will check the lights and wait, check and wait. This sequence will be
"output" and terminating at a final ending state. The transition from one state to the next is repeated until the lights turn green.
not necessarily deterministic; that algorithms, known as randomized algorithms.
1.3 NOTATION OF ALGORITHM
An instruction is a single operation, that describes a computation. When it executed
it convert one state to other. There are four different Notation of representing algorithms:
Step-Form
Typically, when an algorithm is associated with processing information, data can be Pseudocode
read from an input source, written to an output device and stored for further processing. Flowchart
Stored data are considered as part of the internal state of the entity performing the algorithm. Programming Language
In practice, the state is stored in one or more data structures.
1.3.1 Algorithm as Step-Form
The state of an algorithm is defined as its condition regarding stored data. The stored
data in an algorithm are stored as variables or constants. The state shows its current values or It is a step – by – step procedure for solving a task or problem. The steps
contents. must be ordered, unambiguous and finite in number. It is English like representation of logic
which is used to solve the problem.
Because an algorithm is a precise list of precise steps, the order of computation is
always crucial to the functioning of the algorithm. Instructions are usually assumed to be Some guidelines for writing Step-Form algorithm are as follows:
listed explicitly, and are described as starting "from the top" and going "down to the bottom",
an idea that is described more formally by flow of control. Keep in mind that algorithm is a step-by-step process.
Use begin or start to start the process.
In computer science, control flow (or flow of control) is the order in which Include variables and their usage.
individual statements, instructions or function calls of an algorithm are executed or evaluated. If there are any loops, try to give sub number lists.
Try to give go back to step number if loop or condition fails.
For complex problems our goal is to divide the task into smaller and simpler functions Use jump statement to jump from one statement to another.
during algorithm design. So a set of related sequence of steps, part of larger algorithm is Try to avoid unwanted raw data in algorithm.
known as functions. Define expressions.
Use break and stop to terminate the process.
1.2.1 Control Flow
For accomplishing a particular task, different algorithms can be written. The
Normally Algorithm has three control flows they are: different algorithms differ in their requirements of time and space. The programmer selects
Sequence the best suited algorithm for the given task to be solved.
Selection
Iteration Let as look at two simple algorithms to find the greatest among three numbers,
as follows:
Sequence: A sequence is a series of steps that occur one after the other, in the same order
every time. Consider a car starting off from a set of lights. Imagine the road in front of the car Algorithm 1.1:
is clear for many miles and the driver has no need to slow down or stop. The car will start in
Step 1: Start.
first gear, then move to second, third, fourth and finally fifth. A good driver (who doesn‟t
have to slow down or stop) will move through the gears in this sequence, without skipping Step 2: Read the three numbers A,B,C.
gears. Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.
Step 4: Compare A and C. If A is greater, output “A is greater” else output “C is greater”.
Selection: A selection is a decision that has to be made. Consider a car approaching a set of Then go to step 6
lights. If the lights turn from green to yellow, the driver will have to decide whether to stop or Step 5: Compare B and C. If B is greater, output “B is greatest” else output “C is greatest”.
continue through the intersection. If the driver stops, she will have to wait until the lights are
Step 6: Stop.
green again.
Iteration: Iteration is sometimes called repetition, which means a set of steps which are
repeated over and over until some event occurs. Consider the driver at the red light, waiting
3 4
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Algorithm 1.2: for start and finish BEGIN MAINPROGRAM, END MAINPROGRAM -
this is often abbreviated to BEGIN and END - especially in smaller programs
Step 1: Start. for initialization INITIALISATION, END INITIALISATION - this part is
Step 2: Read the three numbers A,B,C. optional, though it makes your program structure clearer
Step 3: Compare A and B. If A is greater, store Ain MAX, else store B in MAX. for subprogram BEGIN SUBPROGRAM, END SUBPROGRAM
Step 4: Compare MAX and C. If MAX is greater, output “MAX is greater” else output “C is for selection IF, THEN, ELSE, ENDIF
for multi-way selection CASEWHERE, OTHERWISE, ENDCASE
greater”.
for pre-test repetition WHILE, ENDWHILE
Step 5: Stop. for post-test repetition REPEAT, UNTIL
Both the algorithms accomplish same goal, but in different ways. The Keywords are written in capitals.
programmer selects the algorithm based on the advantages and disadvantages of each Structural elements come in pairs, eg for every BEGIN there is an END, for
algorithm. For example, the first algorithm has more number of comparisons, whereas in every IF there is an ENDIF, etc.
second algorithm an additional variable MAX is required. Indenting is used to show structure in the algorithm.
The names of subprograms are underlined. This means that when refining
In the Algorithm 1.1, Algorithm 1.2, step 1 and 2 are in sequence logic and step 3, 4, the solution to a problem, a word in an algorithm can be underlined and a
and 5 are in selection logic. In order to illustrate iteration logic, consider one more example. subprogram developed. This feature is to assist the use of the „top-down‟
development concept.
Design an algorithm for calculating total mark of specified number of subjects given
as: 86, 99, 98, 87, 89 1.3.3 Flowcharts
Algorithm 1.3:
Flowcharts are a diagrammatic method of representing algorithms. They use
Step 1: Start an intuitive scheme of showing operations in boxes connected by lines and arrows that
Step 2: Read Number of subjects as N graphically show the flow of control in an algorithm.
Step 3: Total = 0, i=1
Step 4: Get single subject mark as mark Table 1.1 lists the flowchart symbol drawing, the name of the flowchart
Step 5: Total = Total + mark symbol in Microsoft Office (with aliases in parentheses), and a short description of where and
Step 6: i=i+1 how the flowchart symbol is used.
Step 7: If i<=N, THEN go to step 4. Otherwise, go to step 8
Step 8: Output the Total Table 1.1: Flowchart Symbols
Step 9: Stop
NAME
In the Algorithm 1.3 step 7 have a go to statement with a back ward step SYMBOL DESCRIPTION
(ALIAS)
reference, so it means that iteration logic.
Flow Line
Flow line connectors show the direction that the process
(Arrow,
flows.
Connector)
1.3.2 Pseudocode Terminator
(Terminal Terminators show the start and stop points in a process.
Pseudocode ("sort of code") is another way of describing algorithms. It is Point, Oval)
The Data flowchart shape indicates inputs to and outputs
called "pseudo" code because of its strong resemblance to "real" program code. Pseudocode Data
from a process. As such, the shape is more often referred
is essentially English with some defined rules of structure and some keywords that make (I/O)
to as an I/O shape than a Data shape.
it appear a bit like program code. Pretty self-explanatory - the Document flowchart symbol
Document
is for a process step that produces a document.
Some guidelines for writing pseudocode are as follows.
Show a Process or action step. This is the most common
Process
symbol in flowcharts.
Note: These are not "strict" guidelines. Any words used that have similar form and function
may be used in an emergency - however, it would be best to stick to the pseudocode words Indicates a question or branch in the process flow.
used here. Decision Typically, a Decision flowchart shape is used when there
are 2 options (Yes/No, No/No-Go, etc.)
5 6
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
1.3.4 Control Structures of Pseudocode and Flowcharts A binary selection may be described in pseudocode and flow chart as follows :
Each control structures can be built from the basic elements as shown below. Pseudocode Flowchart
Sequence: A sequence is a series of steps that take place one after another. Each step is IF (question) THEN
represented here by a new line.
statement
ELSE
Pseudocode Flowchart
statement
ENDIF
BEGIN
Statement An example of someone at a set of traffic lights follows :
Statement
END Pseudocode Flowchart
IF (lights are green) THEN
Go
Our sequence example of changing gears could be described as follows :
ELSE
Stop
ENDIF
7 8
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
CASEWHERE (question)
Alternative 1: Statement
WHILE (question)
Alternative 2 : Statement
Statement
OTHERWISE : Statement
ENDWHILE
ENDCASE
Green : Go
WHILE (lights are not green)
Amber : Slowdown
wait
Red : Stop
ENDWHILE
ENDCASE
Repetition: A sequence of steps which are repeated a number of times, is called repetition.
For a repeating process to end, a decision must be made. The decision is usually called a test.
The position of this test divides repetition structures into two types : Pre-test and Post-test Post-test repetitions may be described as follows:
repetitions.
Pseudocode Flowchart
Pre-test repetitions (sometimes called guarded loops) will perform the test before any part
of the loop occurs.
REPEAT
Post-test repetitions (sometimes called un-guarded loops) will perform the test after the
main part of the loop (the body) has been performed at least once.
Statement
Pre-test repetitions may be described in as follows :
UNTIL (Question)
9 10
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
REPEAT
Wait
BEGIN
UNTIL lights are green
Start Car
Engage Gears
Navigate Car
Sub-Programs: A sub-program is a self-contained part of a larger program. The use of sub- Stop Car
programs helps with "Top-Down" design of an algorithm, by providing a structure through
which a large and unwieldy solution may be broken down into smaller, more manageable, END
components.
Pseudocode Flowchart
subprogram
Note that the sub-program "Navigate Car" could be further developed into:
Pseudocode Flowchart
Consider the total concept of driving a car. This activity is made up of a number of sub-
processes which each contribute to the driver arriving at a destination. Therefore, driving may
involve the processes of "Starting the car"; "Engaging the gears"; "Speeding up and slowing
down"; "Steering"; and "Stopping the car".
BEGIN SUBPROGRAM Navigate
A (not very detailed) description of driving may look something like:
Steer Car
ENDSUBPROGRAM
In the example above, each of the sub-programs would have whole algorithms of their own,
incorporating some, or all, of the structures discussed earlier.
11 12
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
So now we have another way of thinking about how to compute the value of n!, for all
nonnegative integers n:
13 14
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
PRINT f ENDSUBPROGRAM
Return base solution
END
Figure 1.1 Recursive Flow chart Syntax
1.5 ALGORITHMIC PROBLEM SOLVING
End
We can consider algorithms to be procedural solutions to problems. These solutions
Subprogram
are not answers but specific instructions for getting answers. It is this emphasis on precisely
Start Begin Factorial(N) defined constructive procedures that makes computer science distinct from other disciplines.
In particular, this distinguishes it from theoretical mathematics, whose practitioners are
typically satisfied with just proving the existence of a solution to a problem and, possibly,
Read N No investigating the solution‟s properties. Let us discuss a sequence of steps one typically goes
Is
N==0 through in designing and analysing an algorithm
15 16
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
validation is to assure us that this algorithm will work correctly independent of issues
Ascertain the capabilities of the computational device: concerning programming language it will be written in.
Once a problem is understood, we need to Know the capabilities of the computing Analysing algorithms:
device this can be done by Knowing the type of the architecture, speed & memory
availability. As an algorithm is executed, it uses the computers central processing unit to perform
operation and its memory (both immediate and auxiliary) to hold the program and data.
Exact /approximate solution: Analysis of algorithms and performance analysis refers to the task of determining how much
computing time and storage an algorithm requires. This is a challenging area in which
Once algorithm is developed, it is necessary to show that it computes answer for all the sometimes requires grate mathematical skill. An important result of this study is that it allows
possible legal inputs. The solution is stated in two forms, exact solution or approximate you to make quantitative judgments about the value of one algorithm over another. Another
solution. Examples of problems where an exact solution cannot be obtained are i) Finding a result is that it allows you to predict whether the software will meet any efficiency constraint
square root of number. ii) Solutions of nonlinear equations. that exits.
Creating an algorithm is an art which may never be fully automated. By mastering these
design strategies, it will become easier for you to develop new and useful algorithms.
Dynamic programming is one such technique. Some of the techniques are especially useful in
fields other than computer science such as operation research and electrical engineering.
Some important design techniques are linear, nonlinear and integer programming
There are mainly two options for specifying an algorithm: use of natural language or
pseudocode & Flowcharts. A Pseudo code is a mixture of natural language & programming
language like constructs. A flowchart is a method of expressing an algorithm by a collection
of connected geometric shapes.
Proving algorithms correctness: Figure 1.3 Steps to Find Minimum Element in a List
Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs .We refer to this process as algorithm validation. The process of
17 18
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Step base algorithm to find minimum element in a list Pseudocode to find minimum element in a list
We start from the high end of the array and check to see if that's where we want to insert the
data. If so, fine. If not, we move the preceding element up one and then check to see if we
want to insert x in the “hole” left behind. We repeat this step as necessary.
Thus the search for the place to insert x and the shifting of the higher elements of the array
are accomplished together.
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Figure 1.4 Flow Chart to Find Minimum Element in a List
Step 13: i=i-1
19 20
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Maybe you guessed 1, then 2, then 3, then 4, and so on, until you guessed the
right number. We call this approach linear search, because you guess all the numbers as if
they were lined up in a row. It would work. But what is the highest number of guesses you
could need? If the computer selects N, you would need N guesses. Then again, you could be
really lucky, which would be when the computer selects 1 and you get the number on your
first guess. How about on average? If the computer is equally likely to select any number
from 1 to N, then on average you'll need N/2 guesses.
But you could do something more efficient than just guessing 1, 2, 3, 4, …,
right? Since the computer tells you whether a guess is too low, too high, or correct, you can
start off by guessing N/2. If the number that the computer selected is less than N/2, then
because you know that N/2 is too high, you can eliminate all the numbers from N/2 to N from
further consideration. If the number selected by the computer is greater than N/2, then you
can eliminate 1 through N/2. Either way, you can eliminate about half the numbers. On your
next guess, eliminate half of the remaining numbers. Keep going, always eliminating half of
the remaining numbers. We call this halving approach binary search, and no matter which
number from 1 to N the computer has selected, you should be able to find the number in at
most log2N+1 guesses with this technique. The following table shows the maximum number
Figure 1.6 Flow Chart to Insert a Card in a List of Sorted Cards of guesses for linear search and binary search for a few number sizes:
Pseudocode to Insert a Card in a List of Sorted Cards Highest Number Max Linear Search Guesses Max Binary Search Guesses
READ Number of element in sorted list as N 10 10 4
SET i=0
100 100 7
WHILE i<N
READ Sorted list element as List[i] 1,000 1,000 10
21 22
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
SET Count =0
READ Range as N
SELECT an RANDOM NUMBER from 1 to N as R
WHILE TRUE
READ User guessed Number as G
Count =Count +1
IF R== G THEN
BREAK
ELSEIF R<G THEN
DISPLAY “Guess is Too High”
ELSE
DISPLAY “Guess is Too Low”
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took
Figure 1.7 Flow Chart for Guess an Integer Number in a Range Figure 1.8 Tower of Hanoi
23 24
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The mission is to move all the disks to some another tower without violating The steps to follow are −
the sequence of arrangement. A few rules to be followed for Tower of Hanoi are: Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Rules Step 3 − Move n-1 disks from aux to dest
A recursive Step based algorithm for Tower of Hanoi can be driven as follows −
Only one disk can be moved among the towers at any given time.
Only the "top" disk can be removed. Step 1: BEGIN Hanoi(disk, source, dest, aux)
No large disk can sit over a small disk. Step 2: IF disk == 1 THEN go to step 3 ELSE go to step 4
Step 3: move disk from source to dest AND go to step 8
Step 4: CALL Hanoi(disk - 1, source, aux, dest)
Step 5: move disk from source to dest
Step 6: CALL Hanoi(disk - 1, aux, dest, source)
Step 7: END Hanoi
A recursive Pseudocode for Tower of Hanoi can be driven as follows –
Figure 1.9 Step by Step Moves in Solving Three Disk Tower of Hanoi Problem
Algorithm:
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem
with lesser amount of disks, say → 1 or 2. We mark three towers with name, source,
destination and aux (only to help moving the disks). If we have only one disk, then it can
easily be moved from source to destination tower.
If we have 2 disks −
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two
disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and
all other (n-1) disks are in the second part.
Figure 1.10 Flow Chart for Tower of Hanoi Algorithm
Our ultimate aim is to move disk n from source to destination and then put all other (n-1)
disks onto it. We can imagine to apply the same in a recursive way for all given set of disks. Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps.
25 26
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Step 1: Start
Step 2: READ the value in Celsius scale as C
Step 3: Use the formula F= (C*1.8)+32 to convert Celsius scale to Fahrenheit scale
Step 4: PRINT F
Step 5: READ the value in Fahrenheit scale as F
Step 6: Use the formula C=(F-32)*1/1.8 to convert Fahrenheit scale to Celsius scale
Step 7: PRINT C
Step 8: Stop Figure 1.11 Flow Chart for Temperature Conversion
READ Celsius value as C Swapping is the process of exchanging values of two variables. It can be
COMPUTE F= (C*1.8)+32 performed in with temporary variable and without temporary variable method. Here we are
PRINT F as Fahrenheit going to discuss about the algorithm, Pseudocode, and flow chart for swapping without using
READ Fahrenheit value as F temporary variable.
COMPUTE C=(F-32)*1/1.8
PRINT C as Celsius Algorithm in step form
27 28
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Figure 1.12 Flow Chart for Swapping Two Values without Temporary Variable
1.7.3 Calculate Area and Circumference of a Circle Figure 1.13 Flow Chart for Calculating Area and Circumference of Circle
Area and Circumference of a Circle can be calculated using following formula 1.7.4 Eligible for Vote or Not
Area= 3.14*r* r
Circumference = 2* 3.14 *r If a person‟s age is 18 or greater than 18 then he is eligible to vote, otherwise he is not
Where r is the radius of a circle. eligible to vote. Following are the algorithm, Pseudocode, and flow chart for check whether a
Following are the algorithm, Pseudocode, and flow chart for the calculation of person is eligible to vote or not.
area and circumference of a circle. Algorithm in step form
Algorithm in step form Step1: Start
Step1: Start Step2: READ age of a person as age
Step2: READ radius of the circle as r Step3: IF age>=18 then go to step 4 otherwise go to step 5
Step3: CALCULATE area== 3.14*r* r Step4: PRINT “Eligible to Vote” then go to Step 6
Step4: CALCULATE circumference = 2* 3.14 *r Step5: PRINT “Not Eligible to Vote” then go to Step 6
Step5: PRINT area Step6: Stop
Step6: PRINT circumference Pseudocode
Step 7: Stop
READ age of a person as age
Pseudocode IF age>=18 THEN
PRINT “Eligible to Vote”
READ radius of the circle as r ELSE
CALCULATE area== 3.14*r* r PRINT “Not Eligible to Vote”
CALCULATE circumference = 2* 3.14 *r END IF
PRINT area
PRINT circumference
29 30
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
ELSE
PRINT “C is Big”
END IF
Figure 1.14 Flow Chart to Check Whether a Person is Eligible to Vote or Not.
Following algorithm, Pseudocode, and flow chart are designed to print the
biggest number among the given 3 numbers. Figure 1.15 Flow Chart to Print Biggest Among Three Numbers
Step 7: Stop
Pseudocode
READ a number as N
SET sum=0
ASSIGN temp=N
WHILE temp>0 THEN
digit=temp%10
sum =sum+digit*digit*digit
temp=temp/10
END WHILE
IF N==sum
PRINT “Given Number is Armstrong Number”
ELSE
“Given Number is Not Armstrong Number”
Figure 1.16 Flow Chart to Check Whether the Given Number is Armstrong Number or Not
Following algorithm, Pseudocode, and flow chart are used to check whether
the given number is Palindrome Number or not.
Step 1: Start.
Step 2: READ a number as N
33 34
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Step 3: reverse=0
Step 4: temp=N
Step 5: IF temp> 0 go to step 5.1 ELSE go to step 6
Step 5.1: digit=temp%10
Step 5.2: reverse = reverse*10+digit
Step 5.3: temp=temp/10
Step 5.4: go to step 5
Step 6: IF N== reverse THEN PRINT “Given Number is Palindrome Number” ELSE PRINT
“Given Number is Not Palindrome Number”
Step 7: Stop
Pseudocode
READ a number as N
SET reverse =0
ASSIGN temp=N
WHILE temp>0 THEN
digit=temp%10
reverse = reverse*10+digit
temp=temp/10
END WHILE
IF N== reverse
PRINT “Given Number is Palindrome Number”
ELSE
“Given Number is Not Palindrome Number”
Figure 1.17 Flow Chart to Check Whether the Given Number is Palindrome Number or Not
Algorithm, Pseudocode, and flow chart for calculate Total and average of
given number of subjects mark.
Step 1: Start
Step 2: READ Number of subjects as N
Step 3: SET i=0
Step 4: IF i<N THEN go to step 5 ELSE go to step 8
Step 5: READ single subject mark as List[i]
Step 6: i=i+1
35 36
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Step 7: go to step 4
Step 8: SET i=0, total=0
Step 9: IF i<N THEN go to step 10 ELSE go to step 12
Step 10: total=total+List[i]
Step 11: i=i+1, go to 9
Step 12: average=total/N
Step 13: PRINT total as Total Marks
Step 14: PRINT average as Average Marks
Pseudocode
Figure 1.18 Flow Chart to Calculate the Total and Average of Marks
37 38
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Step 1: Start
Step 2: READ a Number to check as N
Step 3: SET i=2, flag=0
Step 4: IF i<=N/2 THEN go to step 4.1 ELSE go to step 5
Step 4.1: IF N%i==0 THEN SET flag=1 and go to step 5 ELSE go to step 4.2
Step 4.2: i=i+1, go to step 4
Step 5: IF flag==1 THEN PRINT “Given Number is Not Prime” ELSE PRINT “Given
Number is Prime”
Step 6: Stop
Pseudocode
39 40
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
UNIT II
DATA, EXPRESSIONS, STATEMENTS
GE8151 - PROBLEM SOLVING AND PYTHON 2.1 THE PYTHON INTERPRETER
The Python programming language was conceived in the late 1980s, and its
PROGRAMMING implementation was started in December 1989 by Guido van Rossum at CWI in the
Netherlands as a successor to the ABC programming language. When he began implementing
Python, Guido van Rossum was also reading the published scripts from “Monty Python’s
Flying Circus‖, a BBC comedy series from the 1970s. Van Rossum thought he needed a
REGULATIONS – 2017 name that was short, unique, and slightly mysterious, so he decided to call the language
Python.
Prepared By :
Python Mode
Mr. Vinu S, ME,
Assistant Professor,
1 2
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
This mode is used to execute Python program written in a file. Such a file is called 2.2 VALUES AND TYPES
a script. Scripts can be saved to disk for future use. Python scripts have the extension .py,
meaning that the filename ends with .py. A value is one of the basic things a program works with, like a letter or a number.
Some example values are 5, 83.0, and 'Hello, World!'. These values belong to different types:
For example: helloWorld.py 5 is an integer, 83.0 is a floating-point number, and 'Hello, World!' is a string, so-called
To execute this file in script mode we simply write python helloWorld.py at the because the letters it contains are strung together. If you are not sure what type a value has,
command prompt. the interpreter can tell you:
>>>type(5)
2.1.4 Integrated Development Environment (IDE) <class 'int'>
>>>type(83.0)
We can use any text editing software to write a Python script file. <class 'float'>
>>>type('Hello, World!')
<class 'str'>
We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax In these results, the word ―class‖ is used in the sense of a category; a type is a
highlighting and checking, file explorers etc. to the programmer for application development. category of values. Not surprisingly, integers belong to the type int, strings belong to str and
floating-point numbers belong to float. What about values like '5' and '83.0'? They look like
Using an IDE can get rid of redundant tasks and significantly decrease the time required for numbers, but they are in quotation marks like strings.
application development. >>>type('5')
<class 'str'>
IDEL is a graphical user interface (GUI) that can be installed along with the Python >>>type('83.0')
programming language and is available from the official website. <class 'str'>
We can also use other commercial or free IDE according to our preference. PyScripter IDE is They’re strings. When you type a large integer, you might be tempted to use commas
one of the Open source IDE. between groups of digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
3 4
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
5 6
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. 2
>>> False + 1
For example − 1
>>> False * 85
list = [ 'Hai', 123 , 1.75, 'vinu', 100.25 ]
0
smalllist = [251, 'vinu']
>>> True * 85
print list # Prints complete list
85
print list[0] # Prints first element of the list
>>>True+True
print list[-1] # Prints last element of the list
2
print list[1:3] # Prints elements starting from 2nd till 3rd
>>>False+False
print list[2:] # Prints elements starting from 3rd element
0
print smalllist * 2 # Prints list two times
print list + smalllist # Prints concatenated lists
We will discuss about data types like Tuple, Dictionary in Unit IV.
This produces the following result –
7 8
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
unichr(x) Converts an integer to a Unicode character. There are some reserved (KeyWords)words which you cannot use as a variable name
because Python uses them for other things.
ord(x) Converts a single character to its integer value.
The interpreter uses keywords to recognize the structure of the program, and
hex(x) Converts an integer to a hexadecimal string. they cannot be used as variable names.
9 10
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
11 12
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
13 14
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
x>> 2= 2 Example
x<< 2= 40 x1 = 7
2.5.5 Assignment Operators y1 = 7
x2 = 'Welcome'
Assignment operators are used in Python to assign values to variables. y2 = 'Welcome'
x3 = [1,2,3]
a = 10 is a simple assignment operator that assigns the value 10 on the right to y3 = [1,2,3]
the variable a on the left.
print(x1 is not y1)
print(x2 is y2)
There are various compound operators in Python like a += 10 that adds to the
variable and later assigns the same. It is equivalent to a = a + 10. print(x3 is y3)
When you run the program, the output will be:
Table 2.7: Assignment operators in Python False
True
Operator Example Equivatent to False
= x=5 x=5
+= x += 5 x=x+5 Here, we see that x1 and y1 are integers of same values, so they are equal as
-= x -= 5 x=x-5 well as identical. Same is the case with x2 and y2 (strings). But x3 and y3 are list. They are
*= x *= 5 x=x*5 equal but not identical. Since list are mutable (can be changed), interpreter locates them
/= x /= 5 x=x/5 separately in memory although they are equal.
%= x %= 5 x=x%5
//= x //= 5 x = x // 5 2.5.6.2 Membership Operators
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5 in and not in are the membership operators in Python. They are used to test whether a value
|= x |= 5 x=x|5 or variable is found in a sequence (string, list, tuple, set and dictionary).
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5 Table 2.9: Membership operators in Python
<<= x <<= 5 x = x << 5
2.5.6 Special Operators Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
Python language offers some special type of operators like the identity not in True if value/variable is not found in the sequence 5 not in x
operator or the membership operator. They are described below with examples.
Example
2.5.6.1 Identity Operators x = 'Python Programming'
print('Program' not in x)
is and is not are the identity operators in Python. They are used to check if two values (or print('Program' in x)
variables) are located on the same part of the memory. Two variables that are equal does not print('program' in x)
imply that they are identical. When you run the program, the output will be:
False
Table 2.8: Identity operators in Python
True
False
Operator Meaning Example
Here, ' Program ' is in x but ' program' is not present in x, since Python is case
is True if the operands are identical (refer to the same object) x is True
sensitive.
is not True if the operands are not identical (do not refer to the same x is not
object) True
15 16
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
2.6 PRECEDENCE OF PYTHON OPERATORS For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.
The combination of values, variables, operators and function calls is termed as
an expression. Python interpreter can evaluate a valid expression. When an expression >>> 10 * 7 // 3
contains more than one operator, the order of evaluation dependson the Precedence of 23
operations. >>> 10 * (7//3)
20
For example, multiplication has higher precedence than subtraction. >>> (10 * 7)//3
23
>>> 20 – 5*3 We can see that 10 * 7 // 3is equivalent to (10 * 7)//3.
5
But we can change this order using parentheses () as it has higher precedence. Exponent operator ** has right-to-left associativity in Python.
>>> (20 - 5) *3
45 >>> 5 ** 2 ** 3
390625
The operator precedence in Python are listed in the following table. It is in >>> (5** 2) **3
descending order, upper group has higher precedence than the lower ones. 15625
>>> 5 **(2 **3)
Table 2.10: Operator precedence rule in Python 390625
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
Operators Meaning
2.7.1 Non Associative Operators
() Parentheses
** Exponent
Some operators like assignment operators and comparison operators do not
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
have associativity in Python. There are separate rules for sequences of this kind of operator
*, /, //, % Multiplication, Division, Floor division, Modulus
and cannot be expressed as associativity.
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
^ Bitwise XOR < y and y < z, and is evaluates from left-to-right.
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += z will
not Logical NOT result into error.
and Logical AND
or Logical OR 2.8 TUPLE ASSIGNMENT
It is often useful to swap the values of two variables. With conventional
2.7 ASSOCIATIVITY OF PYTHON OPERATORS
assignments, you have to use a temporary variable. For example, to swap a and b:
>>>temp = a
We can see in the above table that more than one operator exists in the same
>>> a = b
group. These operators have the same precedence.
>>> b = temp
When two operators have the same precedence, associativity helps to This solution is cumbersome; tuple assignment is more elegant:
determine which the order of operations. >>>a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable. All the expressions on the right side are
Associativity is the order in which an expression is evaluated that has multiple
evaluated before any of the assignments. The number of variables on the left and the number
operator of the same precedence. Almost all the operators have left-to-right associativity.
of values on the right have to be the
same:
17 18
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
19 20
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The name of the function is type. The expression in parentheses is called the All parameters must be integers.
argument of the function. The result, for this function, is the type of the argument. It is All parameters can be positive or negative.
common to say that a function ―takes‖ an argument and ―returns‖ a result. The resultis also
called the return value. >>>range(10)
Python provides functions that convert values from one type to another. The [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
int function takes any value and converts it to an integer, if it can, or complains otherwise: >>>range(5,10)
>>>int('25')
[5, 6, 7, 8, 9]
25
>>>range(10,1,-2)
>>>int('Python')
[10, 8, 6, 4, 2]
ValueError: invalid literal for int(): Python
int can convert floating-point values to integers, but it doesn’t round off; it 2.10.1.1.2. Printing to the Screen
chops off the fraction part:
>>>int(9.999999) In python 3, print function will prints as strings everything in a comma-
9 separated sequence of expressions, and it will separate the results with single blanks by
>>>int(-2.3) default. Note that you can mix types: anything that is not already a string is automatically
-2 converted to its string representation.
float converts integers and strings to floating-point numbers:
>>>float(25) Eg.
25.0 >>> x=10
>>>float('3.14159') >>> y=7
3.14159 >>>print('The sum of', x, 'plus', y, 'is', x+y)
Finally, str converts its argument to a string: The sum of 10 plus 7 is 17
>>>str(25)
You can also use it with no parameters:
'25'
>>>str(3.14159) print()
'3.14159'
to just advance to the next line.
2.10.1.1.1. range() – function
In python 2, simplest way to produce output is using the print statement
The range() constructor returns an immutable sequence object of integers where you can pass zero or more expressions separated by commas. This function converts
between the given start integer to the stop integer. the expressions you pass into a string and writes the result to standard output as follows
Python's range() Parameters >>> x=10
The range() function has two sets of parameters, as follows: >>> y=7
>>>print'The sum of', x, 'plus', y, 'is', x+y
range(stop) The sum of 10 plus 7 is 17
stop: Number of integers (whole numbers) to generate, starting from zero.
2.10.1.1.3. Reading Keyboard Input
eg. range(3) == [0, 1, 2].
Python provides two built-in functions to read a line of text from standard
range([start], stop[, step])
input, which by default comes from the keyboard. These functions are −
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number. raw_input
step: Difference between each number in the sequence.
input
Note that:
21 22
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The raw_input([prompt]) function reads one line from standard input and def welcome(person_name):
returns it as a string. """This function welcome
the person passed in as
>>>str = raw_input("Enter your input: "); parameter"""
Enter your input: range(0,10) print(" Welcome " , person_name , " to Python Function Section")
>>> print "Received input is : ", str
Received input is : range(0,10) Using Function or Function Call
This prompts you to enter any string and it would display same string on the
Once we have defined a function, we can call it from another function,
screen.
program or even the Python prompt. To call a function we simply type the function name
with appropriate parameters.
The input Function >>> welcome('Vinu')
The input([prompt]) function is equivalent to raw_input, except that it Welcome Vinu to Python Function Section
assumes the input is a valid Python expression and returns the evaluated result to you.
The return statement
>>>str = input("Enter your input: ");
Enter your input: range(0,10) The return statement is used to exit a function and go back to the place from
where it was called.
>>> print "Received input is : ", str
Received input is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Syntax of return
Input data is evaluated and the list is generated
return [expression_list]
2.10.1.2 User-defined functions
As you already know, Python gives you many built-in functions like print(), This statement can contain expression which gets evaluated and the value is
input(), type() etc. but you can also create your own functions. These functions are returned. If there is no expression in the statement or the return statement itself is not present
called user-defined functions. inside a function, then the function will return the None object.
23 24
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
statements inside the function don’t run until the function is called. A function call is like a The argument is evaluated before the function is called, so in the below
detour in the flow of execution. Instead of going to the next statement, the flow jumps to the examples the expressions 'vinu'*3 is evaluated.
body of the function, runs the statements there, and then comes back to pick up where it left
off. Figure 2.3 show the flow of execution >>> welcome('vinu'*3)
Welcome vinuvinuvinu to Python Function Section
>>> student_name='Ranjith'
>>> welcome(student_name)
Welcome Ranjith to Python Function Section
2.10.4 Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Default arguments
Figure 2.3 Flow of execution when function Call Keyword arguments
Variable-length arguments
Required Arguments
That sounds simple enough, until you remember that one function can call Required arguments are the arguments passed to a function in correct
another. While in the middle of one function, the program might have to run the statements in positional order. Here, the number of arguments in the function call should match exactly
another function. Then, while running that new function, the program might have to run yet with the function definition.
another function! Fortunately, Python is good at keeping track of where it is, so each time a def add(a,b):
function completes, the program picks up where it left off in the function that called it. When return a+b
it gets to the end of the program, it terminates. a=10
In summary, when you read a program, you don’t always want to read from b=20
top to bottom. Sometimes it makes more sense if you follow the flow of execution.
print "Sum of ", a ,"and ", b, "is" , add(a,b)
2.10.3 Parameters and Arguments
To call the function add(), you definitely need to pass two argument,
Some of the functions we have seen require arguments. For example, when
otherwise it gives a syntax error as follows
you call type() you pass a variable or value as an argument. Some functions take more than When the above code is executed, it produces the following result:
one argument: eg, range() function take one or two or three arguments. Sum of 10 and 20 is 30
If we miss to give an argument it will show syntax error. Example
Inside the function, the arguments are assigned to variables called
def add(a,b):
parameters. Here is a definition for a function that takes an argument:
return a+b
def welcome(person_name): a=10
print(" Welcome " , person_name , " to Python Function Section") b=20
This function assigns the argument to a parameter named person_name. When print "Sum of ", a ,"and ", b, "is" , add(a)
the function is called, it prints the value of the parameter (whatever it is). This function works It will produce Error message as follows
with any value that can be printed. Sum of 10 and 20 is
25 26
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
A default argument is an argument that assumes a default value if a value is printvalues( 50, 60, 55 )
not provided in the function call for that argument. The following example gives an idea on When the above code is executed, it produces the following result:-
default arguments, it add default value of b if it is not passed while calling. Output is:
def add(a,b=0): 20
print "Sum of ", a ,"and ", b, "is" ,a+b Output is:
a=10 50
b=20 60
add(a,b) 55
add(a)
2.10. 5 The Anonymous Functions or Lambda Functions
When the above code is executed, it produces the following result: These functions are called anonymous because they are not declared in the
Sum of 10 and 20 is 30 standard manner by using the def keyword. You can use the lambda keyword to create small
Sum of 10 and 0 is 10 anonymous functions.
When default argument is used in program, Non default arguments should Lambda forms can take any number of arguments but return just one value in the form
come before default arguments. of an expression. They cannot contain commands or multiple expressions.
Keyword Arguments An anonymous function cannot be a direct call to print because lambda requires an
Keyword arguments are related to the function calls. When you use keyword expression
arguments in a function call, the caller identifies the arguments by the parameter name. Lambda functions have their own local namespace and cannot access variables other
This allows you to skip arguments or place them out of order because the than those in their parameter list and those in the global namespace.
Python interpreter is able to use the keywords provided to match the values with Although it appears that lambda's are a one-line version of a function, they are not
parameters. You can also make keyword calls to the add() function in the following ways − equivalent to inline statements in C or C++, whose purpose is by passing function
def add(a,b): stack allocation during invocation for performance reasons.
print "Sum of ", a ,"and ", b, "is" ,a+b Syntax
a=10 The syntax of lambda functions contains only a single statement, which is as follows
b=20
add(b=a,a=b) lambda [arg1 [,arg2,.....argn]]:expression
When the above code is executed, it produces the following result − Following is the example to show how lambda form of function works
Sum of 20 and 10 is 30
sum = lambda a, b: a + b;
Variable-Length Arguments
You may need to process a function for more arguments than you specified print "Sum is : ", sum( 5, 10 )
while defining the function. These arguments are called variable-length arguments and are print "Sum is : ", sum( 30, 50 )
not named in the function definition, unlike required and default arguments. When the above code is executed, it produces the following result
Syntax for a function with non-keyword variable arguments is this
def functionname([formal_args,] *var_args_tuple ): Sum is: 15
"function_docstring" Sum is: 80
function_suite 2.10.6 Modules
return [expression] A module allows you to logically organize your Python code. Grouping
An asterisk (*) is placed before the variable name that holds the values of all related code into a module makes the code easier to understand and use. A module is a file
nonkeyword variable arguments. This tuple remains empty if no additional arguments are that contains a collection of related functions. Python has lot of built-in modules; math
specified during the function call. Following is a simple example module is one of them. math module provides most of the familiar mathematical functions.
def printvalues( arg1, *vartuple ): Before we can use the functions in a module, we have to import it with an
print "Output is: " import statement:
print arg1
>>> import math
for var in vartuple:
This statement creates a module object named math. If you display the
print var
module object, you get some information about it:
>>> math
printvalues( 20 ) <module 'math' (built-in)>
27 28
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The module object contains the functions and variables defined in the module. Programs that will be imported as modules often use the following idiom:
To access one of the functions, you have to specify the name of the module and the name of if __name__ == '__main__':
the function, separated by a dot (also known as a period). This format is called dot notation. add(10,20)
>>> math.log10(200) __name__ is a built-in variable that is set when the program starts. If the
2.3010299956639813 program is running as a script, __name__ has the value '__main__'; in that case, the test code
>>> math.sqrt(10) runs. Otherwise, if the module is being imported, the test code is skipped. Modify
addModule.py file as given below.
3.1622776601683795
def add(a, b):
Math module have functions like log(), sqrt(), etc… In order to know what are result = a + b
the functions available in particular module, we can use dir() function after importing print(result)
particular module. Similarly if we want to know detail description about a particular module if __name__ == '__main__':
or function or variable means we can use help() function. add(10,20)
Eg. Now while importing addModule test case is not running
>>> import math >>> import addModule
>>> dir(math) __name__ has module name as its value when it is imported. Warning: If you
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', import a module that has already been imported, Python does nothing. It does not re-read the
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', file, even if it has changed. If you want to reload a module, you can use the built-in function
'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] the module again.
>>> help(pow)
Help on built-in function pow in module __builtin__:
2.11 ILLUSTRATIVE PROGRAMS
pow(...)
pow(x, y[, z]) -> number 2.11.1 Exchange the Value of two Variables
In python exchange of values of two variables (swapping) can be done in
With two arguments, equivalent to x**y. With three arguments, different ways
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
Using Third Variable
2.10.6.1 Writing modules Without Using Third Variable
Any file that contains Python code can be imported as a module. For example, o Using Tuple Assignment method
suppose you have a file named addModule.py with the following code: o Using Arithmetic operators
def add(a, b): o Using Bitwise operators
result = a + b
print(result) 2.11.1.1 Using Third Variable
add(10,20)
If you run this program, it will add 10 and 20 and print 30. We can import it 1 var1 = input("Enter value of variable1: ")
like this: 2 var2 = input("Enter value of variable2: ")
>>> import addModule 3 temp = var1
30 4 var1 = var2
Now you have a module object addModule 5 var2 = temp
>>> addModule 6 print("After swapping:")
<module 'addModule' from 'G:/class/python/code\addModule.py'> 7 print("First Variable =",var1,)
The module object provides add(): 8 print("Second Variable=",var2,)
>>> addModule.add(120,150) When you run the program, the output will be:
270 Enter value of variable1: 5
So that’s how you write modules in Python. Enter value of variable2: 10
The only problem with this example is that when you import the module it After swapping:
runs the test code at the bottom. Normally when you import a module, it defines new First Variable = 10
functions but it doesn’t run them. Second Variable= 5
29 30
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
In the above program line number 3,4,5, are used to swap the values of two variables. In this 2.11.2 Circulate the Value of N Variables
program, we use the temp variable to temporarily hold the value of var1. We then put the
value of var2 in var1 and later temp in var2. In this way, the values get exchanged. In this Problem of circulating a Python list by an arbitrary number of items to the
method we are using one more variable other than var1,var2. So we calling it as swapping right or left can be easily performed by List slicing operator.
with the use of third variable.
2.11.1.2 Without Using Third Variable 1 2 3 4 5 6 7
Figure 2.4.a Example List
We can do the same swapping operation even without the use of third variable,
There are number of ways to do this, they are. Consider the above list Figure 2.4.a; circulation of the above list by n position
can be easily achieved by slicing the array into two and concatenating them. Slicing is done
2.11.1.2.1 Using Tuple Assignment method
as nth element to end element + beginning element to n-1th element. Suppose n=2 means,
In this method in the above program instead of line number 3,4,5 use a single given list is rotated 2 positions towards left side as given in Figure 2.4.b
tuple assignment statement
var1 , var2 = var2 , var1 3 4 5 6 7 1 2
The left side is a tuple of variables; the right side is a tuple of expressions. Figure 2.4.b Left Circulated List
Each value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments. Suppose n= - 2 means, given list is rotated 2 position towards right side as
given in Figure 2.4.c
2.11.1.2.2 Using Arithmetic operators
6 7 1 2 3 4 5
If the variables are both numbers, Swapping can be performed using simple
mathematical addition subtraction relationship or multiplication division relationship. Figure 2.4.c Right Circulated List
In this method in the above program instead of line number 3,4,5 use the following
code
2.11.3 Test for Leap Year
In order to check whether a year is leap year or not python provide a isleap()
x=x*y
y=x/y function in calendar module. So if you want to check whether a year is leap year or not, first
x=x/y import calendar module. Then use the isleap() function.
2.11.1.2.3 Using Bitwise operators
>>> import calendar
If the variables are integers then we can perform swapping with the help of bitwise >>> calendar
<module 'calendar' from 'C:\Python27\lib\calendar.pyc'>
XOR operator. In order to do this in the above program instead of line number 3,4,5 use the
>>> calendar.isleap(2003)
following code False
>>> import calendar
x=x^y
>>> calendar.isleap(2000)
y=x^y
True
x=x^y
>>> calendar.isleap(2004)
True
31 32
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
>>> calendar.isleap(2003)
False
>>> calendar.isleap(1900)
False
>>> calendar.isleap(2020)
True
33
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
UNIT III
CONTROL FLOW, FUNCTIONS
GE8151 - PROBLEM SOLVING AND PYTHON 3.1 CONDITIONALS
PROGRAMMING 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.
>>> 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
More explanation can found in 2.5.2. Although these operations are probably
Prepared By : 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
Mr. Vinu S, ME, an assignment operator and == is a relational operator. There is no such thing as =< or =>.
St.Joseph’s College of Engineering, 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
Chennai -600119.
For example:
1 2
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
x > 0 and x < 10 is true only if x is greater than 0 and less than 10. if TEST EXPRESSION:
STATEMENT(S) # executed if condition evaluates to True
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.
Here, the program evaluates the TEST EXPRESSION and will execute
not operator negates a boolean expression, so not (x > y) is true if x > y is false, that
statement(s) only if the text expression is True. If the text expression is False, the
is, if x is less than or equal to y. statement(s) is not executed.
Note:- Any nonzero number is interpreted as True
A few important things to note about if statements:
>>>95 and True
True 1. The colon (:) is significant and required. It separates the header of the compound
statement from the body.
>>>mark=95
2. The line after the colon must be indented. It is standard in Python to use four spaces for
>>>mark>0 and mark<=100 indenting.
True 3. All lines indented the same amount after the colon will be executed whenever the
>>> mark=102 BOOLEAN_EXPRESSION is true.
>>> mark>0 and mark<=100 4. Python interprets non-zero values as True. None and 0 are interpreted as False.
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.
3 4
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, Here is an example:
which does nothing. age=21 #age=17
if age >= 18:
if x < 0:
print("Eligible to vote")
pass # TODO: need to handle negative values!
else:
3.2.2 Alternative execution print("Not Eligible to vote")
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 Output will be:
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 .. else statement is Eligible to vote
if TEST EXPRESSION: In the above example, when age is greater than 18, the test expression is true
STATEMENTS_1 # executed if condition evaluates to True and body of if is executed and body of else is skipped. If age is less than 18, the test
else: expression is false and body of else is executed and body of if is skipped. If age is equal to
STATEMENTS_2 # executed if condition evaluates to False 18, the test expression is true and body of if is executed and body of else is skipped.
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.
5 6
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Any number of these statements can be nested inside one another. Indentation
is the only way to figure out the level of nesting.
if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
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.
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")
7 8
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
9 10
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
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 Figure 3.6 Flowchart of while Loop
beforehand, the number of times to iterate.
Example:
The general syntax for the while statement : Python program to find sum of first n numbers using while loop
while TEST_EXPRESSION: n = 20
STATEMENTS sum = 0 # initialize sum and counter
i=1
In while loop, test expression is checked first. The body of the loop is entered while i <= n:
only if the TEST_EXPRESSION evaluates to True. After one iteration, the test expression is sum = sum + i
checked again. This process continues until the TEST_EXPRESSION evaluates to False. i = i+1 # update counter
print("The sum is", sum) # print the sum
In Python, the body of the while loop is determined through indentation. Body When you run the program, the output will be:
starts with indentation and the first unindented line marks the end.
The sum is 210
Python interprets any non-zero value as True. None and 0 are interpreted
In the above program, the test expression will be True as long as our counter
as False.
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.
11 12
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The general syntax for the while statement: print("Sum is ", sum)
for LOOP_VARIABLE in SEQUENCE:
Output will be:
STATEMENTS
Sum is 190
Here, LOOP_VARIABLE is the variable that takes the value of the item
inside the sequence on each iteration. 3.3.3 Break, Continue, Pass
Loop continues until we reach the last item in the sequence. The body of for You might face a situation in which you need to exit a loop completely when
loop is separated from the rest of the code using indentation. 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.
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
print('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
print('Current variable value :', var)
var = var -1
if var == 5:
Figure 3.7 Flowchart of for Loop break
print "End!"
Example
This will produce the following output:
marks = [95,98,89,93,86]
Current Letter : W
total = 0
Current Letter : e
for subject_mark in marks:
Current Letter : l
total = total+subject_mark
Current variable value : 10
print("Total Mark is ", total)
Current variable value : 9
when you run the program, the output will be: Current variable value : 8
Current variable value : 7
Total Mark is 461 Current variable value : 6
We can use the range() function in for loops to iterate through a sequence of End!
numbers.
Example: 3.3.3.2 The continue Statement:
sum=0
The continue statement in Python returns the control to the beginning of the
for i in range(20):
while loop. The continue statement rejects all the remaining statements in the current
sum=sum+i
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.
13 14
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
15 16
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
pass else:
return x
We generally use it as a placeholder.
Another way to write the above function is to leave out the else and just follow
the if condition by the second return statement.
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 def absolute_value(x):
complain. So, we use the pass statement to construct a body that does nothing. if x < 0:
return -x
Example return x
sequence = {'p', 'a', 's', 's'} Think about this version and convince yourself it works the same as the first one.
for val in sequence:
Code that appears after a return statement, or any other place the flow of
pass
execution can never reach, is called dead code, or unreachable code.
We can do the same thing in an empty function
In a fruitful function, it is a good idea to ensure that every possible path through
def function(args): the program hits a return statement. The following version of absolute_value fails to do this:
pass
def bad_absolute_value(x):
if x < 0:
3.4 FRUITFUL FUNCTIONS return -x
elif x > 0:
3.4.1 Return Values return x
This version is not correct because if x happens to be 0, neither condition is true,
The built-in functions we have used, such as abs, pow, int, max, and range,
and the function ends without hitting a return statement. In this case, the return value is a
have produced results. Calling each of these functions generates a value, which we usually
special value called None:
assign to a variable or use as part of an expression.
>>> print(bad_absolute_value(0))
biggest = max(3, 7, 2, 5)
None
x = abs(3 - 11) + 10
All Python functions return None whenever they do not return another value.
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 It is also possible to use a return statement in the middle of a for loop, in which case control
area of a circle with the given radius: immediately returns from the function. Let us assume that we want a function which looks
def area(radius): through a list of words. It should return the first 2-letter word. If there is not one, it should
b = 3.14159 * radius**2 return the empty string:
return b def find_first_2_letter_word(xs):
for wd in xs:
We have seen the return statement before, but in a fruitful function
if len(wd) == 2:
the return statement includes a return value. This statement means: evaluate the return
return wd
expression, and then return it immediately as the result of this function. The expression
return ""
provided can be arbitrarily complicated, so we could have written this function like this:
def area(radius): While running output will be:
return 3.14159 * radius * radius >>> find_first_2_letter_word(["This", "is", "a", "dead", "parrot"])
'is'
On the other hand, temporary variables like b above often make debugging easier.
>>> find_first_2_letter_word(["I", "like", "cheese"])
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:
Single-step through this code and convince yourself that in the first test case that
def absolute_value(x): we’ve provided, the function returns while processing the second element in the list: it does not
if x < 0: have to traverse the whole list.
return -x
17 18
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
3.4.2 Incremental Development Next we compute the sum of squares of dx and dy:
def distance(x1, y1, x2, y2):
To deal with increasingly complex programs, we are going to suggest a dx = x2 - x1
technique called incremental development. The goal of incremental development is to avoid dy = y2 - y1
long debugging sessions by adding and testing only a small amount of code at a time. dsquared = dx*dx + dy*dy
As an example, suppose we want to find the distance between two points, given return 0.0
by the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is: Again, we could run the program at this stage and check the value
of dsquared (which should be 25).
Finally, using the fractional exponent 0.5 to find the square root, we compute
The first step is to consider what a distance function should look like in Python. and return the result:
In other words, what are the inputs (parameters) and what is the output (return value)?
def distance(x1, y1, x2, y2):
In this case, the two points are the inputs, which we can represent using four dx = x2 - x1
parameters. The return value is the distance, which is a floating-point value. dy = y2 - y1
dsquared = dx*dx + dy*dy
Already we can write an outline of the function that captures our thinking so far: result = dsquared**0.5
def distance(x1, y1, x2, y2): return result
return 0.0
If that works correctly, you are done. Otherwise, you might want to inspect the
Obviously, this version of the function doesn’t compute distances; it always value of result before the return statement.
returns zero. But it is syntactically correct, and it will run, which means that we can test it
When you start out, you might add only a line or two of code at a time. As you
before we make it more complicated.
gain more experience, you might find yourself writing and debugging bigger conceptual
To test the new function, we call it with sample values: chunks. Either way, stepping through your code one line at a time and verifying that each step
matches your expectations can save you a lot of debugging time. As you improve your
>>> distance(1, 2, 4, 6) programming skills you should find yourself managing bigger and bigger chunks: this is very
0.0 similar to the way we learned to read letters, syllables, words, phrases, sentences, paragraphs,
We chose these values so that the horizontal distance equals 3 and the vertical etc., or the way we learn to chunk music — from individual notes to chords, bars, phrases, and
distance equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle). When testing a so on.
function, it is useful to know the right answer. The key aspects of the process are:
At this point we have confirmed that the function is syntactically correct, and
we can start adding lines of code. After each incremental change, we test the function again. If 1. Start with a working skeleton program and make small incremental changes. At any
an error occurs at any point, we know where it must be — in the last line we added. point, if there is an error, you will know exactly where it is.
2. Use temporary variables to refer to intermediate values so that you can easily inspect
A logical first step in the computation is to find the differences x2- x1 and y2- y1. and check them.
We will refer to those values using temporary variables named dx and dy. 3. Once the program is working, relax, sit back, and play around with your options.
4. You might want to consolidate multiple statements into one bigger compound
def distance(x1, y1, x2, y2):
expression, or rename the variables you’ve used, or see if you can make the function
dx = x2 - x1
shorter. A good guideline is to aim for making code as easy as possible for others to
dy = y2 - y1
read.
return 0.0
If we call the function with the arguments shown above, when the flow of Here is another version of the function. It makes use of a square root function
execution gets to the return statement, dx should be 3 and dy should be 4. We can check that that is in the math module
this is the case in PyScripter by putting the cursor on the return statement, and running the import math
program to break execution when it gets to the cursor (using the F4 key). Then we inspect the
variables dx and dy by hovering the mouse above them, to confirm that the function is getting def distance(x1, y1, x2, y2):
the right parameters and performing the first computation correctly. If not, there are only a few return math.sqrt( (x2-x1)**2 + (y2-y1)**2 )
lines to check.
While running output will be:
19 20
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
You can call one function from within another. This ability is When a reference is made inside a function, the name is searched in the local
called composition. namespace, then in the global namespace and finally in the built-in namespace.
As an example, we’ll write a function that takes two points, the center of the If there is a function inside another function, a new scope is nested inside the local scope.
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 Example
perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the def outer_function():
distance between the two points. Fortunately, we’ve just written a function, distance, that does b = “India”
just that, so now all we have to do is use it: def inner_func():
radius = distance(xc, yc, xp, yp) c = “TamilNadu”
a = “World”
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: Here, the variable a is in the global namespace. Variable b is in the local
result = area(radius) namespace of outer_function() and c is in the nested local namespace of inner_function().
return result
Wrapping that up in a function, we get:
21 22
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
When we are in inner_function(), c is local to us, b is nonlocal and a is global. 3.6 RECURSION
We can read as well as assign new values to c but can only
read b and a from inner_function(). 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
If we try to assign as a value to b, a new variable b is created in the local the same problem, and the smaller versions reduce to easily solvable cases, then one can use a
namespace which is different than the nonlocal b. Same thing happens when we assign a recursive function to solve that problem.
value to a.
3.6.1 Base Condition in Recursion
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 Base case is the smallest version of the problem, which cannot expressed in
following example will further clarify this. 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
def outer_function(): terms of smaller problems.
a ="i am in India"
def inner_function():
For Example:
a = "i am in TamilNadu"
print('a =',a)
Following is an example of recursive function to find the factorial of an integer.
inner_function()
print('a =',a)
For positive values of n, let's write n!, as we known n! is a product of numbers
a = "i am in World"
starting from n and going down to 1. n! = n. (n-1)…… 2 .1. But notice that (n-1) ... 2.1 is
outer_function()
another way of writing (n-1)!, and so we can say that n!=n.(n−1)!. So we wrote n! as a
print('a =',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
As you can see, the output of this program is
on n by first computing the factorial function on n−1. So computing (n−1)! is
a subproblem that we solve to compute n!.
a = i am in TamilNadu
a = i am in India
In the above example, base case for n == 1 is defined and larger value of
a = i am in World
number can be solved by converting to smaller one till base case is reached.
In this program, three different variables a are defined in separate namespaces
and accessed accordingly. While in the following program,
def outer_function():
global a
Python program to find factorial of a given number using recursive function is.
a = "i am in India"
def inner_function():
def factorial(n):
global a
if n == 1:
a = "i am in TamilNadu"
return 1
print('a =',a)
else:
inner_function()
return (n * factorial(n-1))
print('a =',a)
num = 5
a = "i am in World"
print("The factorial of", num, "is", factorial(num))
outer_function()
print('a =',a)
Output will be:
The output of the program is.
a = i am in TamilNadu
The factorial of 7 is 120
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. 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
23 24
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
the number. Each function call multiples the number with the factorial of number 1 until the For most people, the first letter of 'python' is p, not y. But for computer
number is equal to one. This recursive call can be explained in the following steps. scientists, the index is an offset from the beginning of the string, and the offset of the first
letter is zero.
factorial(5) # 1st call with 5 >>> letter = subject [0]
>>> letter
5 * factorial(4) # 2nd call with 4 'p'
5 * 4 * factorial(3) # 3rd call with 3 So p is the 0th letter (“zero-eth”) of 'python', y is the 1th letter (“one-eth”), and
t is the 2th letter (“two-eth”).
5 * 4 * 3 * factorial(2) # 4th call with 2
As an index you can use an expression that contains variables and operators:
5 * 4 * 3 * 2 * factorial(1) # 5th call with 1 >>> i = 1
5*4*3*2*1 # return from 5th call as n==1 >>> subject [i]
'y'
5*4*3*2 # return from 4th call >>> subject [i+1]
5*4*6 # return from 3rd call 't
But the value of the index has to be an integer. Otherwise you get:
5 * 24 # return from 2nd call
>>> letter =subject [1.5]
120 # return from 1st call TypeError: string indices must be integers
Our recursion ends when the number reduces to 1. This is called the base condition. Every 3.7.1 len()
recursive function must have a base condition that stops the recursion or else the function len is a built-in function that returns the number of characters in a string:
calls itself infinitely
>>> subject = 'python'
>>> len(subject)
Advantages of recursion
6
1. Recursive functions make the code look clean and elegant. To get the last letter of a string, you might be tempted to try something like this:
2. A complex task can be broken down into simpler sub-problems using recursion. >>> length = len(subject)
3. Sequence generation is easier with recursion than using some nested iteration. >>> last = subject [length]
IndexError: string index out of range
Disadvantages of recursion
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
1. Sometimes the logic behind recursion is hard to follow through.
character, you have to subtract 1 from length:
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug. >>> last = subject [length-1]
>>> last
3.7 STRINGS 't'
Or you can use negative indices, which count backward from the end of the
A string is a sequence of characters. You can access the characters one at a string. The expression subject [-1] yields the last letter, subject [-2] yields the second to last,
time with the bracket operator: and so on.
>>> subject = 'python'
>>> letter = subject [1] 3.7.2 Traversal with a for Loop
A lot of computations involve processing a string one character at a time.
The second statement selects character number 1 from fruit and assigns it to Often they start at the beginning, select each character in turn, do something to it, and
letter. The expression in brackets is called an index. The index indicates which character in continue until the end. This pattern of processing is called a traversal. One way to write a
the sequence you want. But you might not get what you expect: traversal is with a while loop:
>>> letter index = 0
'y' while index < len(subject):
letter = subjec [index]
print(letter)
25 26
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
index = index + 1 If the first index is greater than or equal to the second the result is an empty
This loop traverses the string and displays each letter on a line by itself. The string, represented by two quotation marks:
loop condition is index < len(subjec), so when index is equal to the length of the string, the >>> subject = 'python'
condition is false, and the body of the loop doesn’t run. The last character accessed is the one >>> subject[3:3]
with the index len(subjec)-1, which is the last character in the string. ''
An empty string contains no characters and has length 0, but other than that, it
Another way to write a traversal is with a for loop: is the same as any other string.
for letter in subject:
print(letter) Continuing this example, subject[:] gives entire string.
subject ‘ p y t h o n ‘
Index 0 1 2 3 4 5 >>> subject = 'python'
>>> subject[:]
Figure 3.8 Slice indices python
3.7.4 Strings are Immutable
Each time through the loop, the next character in the string is assigned to the It is tempting to use the [] operator on the left side of an assignment, with the
variable letter. The loop continues until no characters are left. intention of changing a character in a string. For example:
The following example shows how to use concatenation (string addition) and a >>> greeting = 'Hello, world!'
for loop to generate an abecedarian series (that is, in alphabetical order). In Robert >>> greeting[0] = 'J'
McCloskey’s book MakeWay for Ducklings, the names of the ducklings are Jack, Kack, TypeError: 'str' object does not support item assignment
Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order: The reason for the error is that strings are immutable, which means you can’t
prefixes = 'JKLMNOPQ' change an existing string. The best you can do is create a new string that is a variation on the
suffix = 'ack' original:
for letter in prefixes: >>> greeting = 'Hello, world!'
print(letter + suffix) >>> new_greeting = 'J' + greeting[1:]
The output is: >>> new_greeting
Jack 'Jello, world!'
Kack This example concatenates a new first letter onto a slice of greeting. It has no
Lack effect on the original string.
Mack
Nack 3.7.5 String Methods
Oack Strings provide methods that perform a variety of useful operations. A method
Pack is similar to a function it takes arguments and returns a value but the syntax is different. For
Qack example, the method upper takes a string and returns a new string with all uppercase letters.
3.7.3 String Slices Instead of the function syntax upper(word), it uses the method syntax word.upper().
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: >>> word = 'python'
>>> s = 'Monty Python' >>> new_word = word.upper()
>>> s[0:5] >>> new_word
'Monty' 'PYTHON
>>> s[6:12]
'Python' This form of dot notation specifies the name of the method, upper, and the
The operator [n:m] returns the part of the string from the “n-eth” character to name of the string to apply the method to, word. The empty parentheses indicate that this
the “m-eth” character, including the first but excluding the last. This behavior is method takes no arguments.
counterintuitive, but it might help to imagine the indices pointing between the characters, as A method call is called an invocation; in this case, we would say that we are
in Figure 3.8. If you omit the first index (before the colon), the slice starts at the beginning of invoking upper on word.
the string. If you omit the second index, the slice goes to the end of the string: As it turns out, there is a string method named find that is remarkably similar
>>> subject = 'python' to the function we wrote:
>>> subject[:3] >>> word = 'python'
. 'pyt' >>> index = word.find('t')
>>> subject[3:] >>> index
'hon' 2
27 28
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
In this example, we invoke find on word and pass the letter we are looking for 8 find(str, beg=0 end=len(string)) Determine if str occurs in string or in a
as a parameter. Actually, the find method is more general than our function; it can find
substrings, not just characters: substring of string if starting index beg and
>>> word.find('ho') ending index end are given returns index if
3 found and -1 otherwise.
By default, find starts at the beginning of the string, but it can take a second 9
argument, the index where it should start: index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str
>>> word='welcome' not found.
>>> word.find('e') 10 isalnum() Returns true if string has at least 1 character
1
and all characters are alphanumeric and false
>>> word.find('e',2)
6 otherwise.
This is an example of an optional argument; find can also take a third 11 isalpha() Returns true if string has at least 1 character
argument, the index where it should stop:
and all characters are alphabetic and false
>>> name = 'bob'
>>> name.find('b', 1, 2) otherwise.
-1 12 isdigit() Returns true if string contains only digits and
This search fails because b does not appear in the index range from 1 to 2, not
false otherwise.
including 2. Searching up to, but not including, the second index makes find consistent with
13 islower() Returns true if string has at least 1 cased
the slice operator.
3.7.6 More String Methods character and all cased characters are in
Python includes the following built-in methods to manipulate strings lowercase and false otherwise.
14 isnumeric() Returns true if a unicode string contains only
SN Methods Description
1 numeric characters and false otherwise.
capitalize() Capitalizes first letter of string 15
2 isspace() Returns true if string contains only whitespace
center(width, fillchar) Returns a space-padded string with the original
characters and false otherwise.
string centered to a total of width columns. 16
3 istitle() Returns true if string is properly "titlecased"
count(str, beg= 0,end=len(string)) Counts how many times str occurs in string or
and false otherwise.
in a substring of string if starting index beg and 17 isupper() Returns true if string has at least one cased
ending index end are given.
4 character and all cased characters are in
decode(encoding='UTF- Decodes the string using the codec registered
uppercase and false otherwise.
8',errors='strict') for encoding. encoding defaults to the default 18 join(seq) Merges (concatenates) the string
string encoding.
5 representations of elements in sequence seq
encode(encoding='UTF- Returns encoded string version of string; on
into a string, with separator string.
8',errors='strict') error, default is to raise a ValueError unless 19 len(string) Returns the length of the string
errors is given with 'ignore' or 'replace'. 20
6 ljust(width[, fillchar]) Returns a space-padded string with the original
endswith(suffix,beg=0, Determines if string or a substring of string (if
string left-justified to a total of width columns.
end=len(string)) starting index beg and ending index end are 21 lower() Converts all uppercase letters in string to
given) ends with suffix; returns true if so and
lowercase.
false otherwise. 22
7 lstrip() Removes all leading whitespace in string.
expandtabs(tabsize=8) Expands tabs in string to multiple spaces; 23 maketrans() Returns a translation table to be used in
defaults to 8 spaces per tab if tabsize not
translate function.
provided.
24 max(str) Returns the max alphabetical character from
29 30
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
31 32
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Arrays are sequence types and behave very much like lists, except that the Next method to creating and reading lists is, first, consider the size of the list
type of objects stored in them is constrained. A list (array) is a set of objects. Individual and create a list from the desired number of elements, then loop through the variable i starting
objects can be accessed using ordered indexes that represent the position of each object with number 0 and inside the loop read i-th element of the list:
within the list (array). a = [0] * int(input('Enter No of Elements :'))
for i in range(len(a)):
The list can be set manually by enumerating of the elements the list in square a[i] = int(input('Enter Element : '))
brackets, like here: print (a)
Primes = [2, 3, 5, 7, 11, 13]
Rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'] Output will be
Enter No of Elements :3
The list Primes has 6 elements, namely: Primes[0] == 2, Primes[1] == 3, Enter Element : 2
Primes[2] == 5, Primes[3] == 7,Primes[4] == 11, Primes[5] == 13. The list Rainbow has 7 Enter Element : 4
elements, each of which is the string. Enter Element : 3
[2, 4, 3]
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 You can print elements of a list a with print(a); this displays the list items
the last element and go left when reading a list. 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
You can obtain the number of elements in a list with the two examples of that, using other forms of loop:
function len (meaning length of the list), e.g.len(Primes) == 6.
a = [1, 2, 3, 4, 5]
Unlike strings, the elements of a list are changeable; they can be changed by for i in range(len(a)):
assigning them new values. print(a[i])
Consider several ways of creating and reading lists. First of all, you can create Here the index i is changed, then the element a[i] is displayed.
an empty list (the list with no items, its length is 0), and you can add items to the end of your a = [1, 2, 3, 4, 5]
list using append. For example, suppose the program receives the number of elements in the for elem in a:
list n, and then n elements of the list one by one each at the separate line. Here is an example print(elem, end=' ')
of input data in this format: In this example, the list items are displayed in one line separated by spaces,
a = [] # start an empty list and it's not the index that is changed but rather the value of the variable itself (for example, in
n = int(input('Enter No of Elements')) # read number of element in the list the loop for elem in ['red', 'green', 'blue'] variable elem will take the values 'red', 'green', 'blue'
for i in range(n): successively.
new_element = int(input('Enter Element :')) # read next element
a.append(new_element) # add it to the list 3.9 ILLUSTRATIVE PROGRAMS:
# the last two lines could be replaced by
one: 3.9.1 Square Roots
# a.append(int(input('Enter Element :'))) Loops are often used in programs that compute numerical results by starting
print(a) 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
Output will be start with almost any estimate, x, you can compute a better estimate with the following
Enter No of Elements5 formula:
Enter Element :2
Enter Element :7
Enter Element :4 For example, if a is 4 and x is 3:
Enter Element :3 >>> a = 4
Enter Element :8 >>> x = 3
[2, 7, 4, 3, 8] >>> y = (x + a/x) / 2
In the demonstrated example the empty list is created, then the number of >>> y
elements is read, then you read the list items line by line and append to the end. The same 2.16666666667
thing can be done, saving the variable n:
33 34
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
The result is closer to the correct answer (√4 = 2). If we repeat the process 3.9.2.1 Euclidean algorithm
with the new estimate, it gets even closer:
>>> x = y This algorithm is based on the fact that GCD of two numbers divides their
>>> y = (x + a/x) / 2 difference as well. In this algorithm, we divide the greater by smaller and take the remainder.
>>> y Now, divide the smaller by this remainder. Repeat until the remainder is 0.
2.00641025641
After a few more updates, the estimate is almost exact: For example, if we want to find the GCD of 108 and 30, we divide 108 by 30.
>>> x = y The remainder is 18. Now, we divide 30 by 18 and the remainder is 12. Now, we divide 18
>>> y = (x + a/x) / 2 by 12 and the remainder is 6. Now, we divide 12 by 6 and the remainder is 0. Hence, 6 is the
>>> y required GCD.
2.00001024003
>>> x = y
>>> y = (x + a/x) / 2 def computeGCD(x, y):
>>> y while(y):
2.00000000003 x, y = y, x % y #can also be written as follows
In general we don’t know ahead of time how many steps it takes to get to the right answer, return x #reminder=x%y
but we know when we get there because the estimate stops changing: # x=y
>>> x = y #y=reminder
>>> y = (x + a/x) / 2 a=108
>>> y b=30
2.0 print('GCD of ',a ,' and ' , b, ' is ',computeGCD(a,b))
>>> x = y
>>> y = (x + a/x) / 2 Output will be:
>>> y
2.0 GCD of 108 and 30 is 6
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: Here we loop until y becomes zero. The statement x, y = y, x % y does
def square_root(a): swapping of values in Python. In each iteration, we place the value of y in x and the
x=.5*a remainder (x % y) in y, simultaneously. When y becomes zero, we have GCD in x.
while True:
print(x) 3.9.3 Exponentiation
y = (x + a/x) / 2
if y == x: Simplest way to find the exponentiation of a number xy in python is, the use of ** operator
break >>> 4**3
x=y 64
print("Square Root of ", a , " is ", y) Another way to find the exponentiation of a number x y in python is, the use of
square_root(25) pow() function that is available in math module. eg
>>> import math
Output will be: >>> math.pow(4,3)
64.0
12.5 We can also write our own function to find the exponentiation of a number x y using looping
7.25 statement.
5.349137931034482 def my_pow(x,y):
5.011394106532552 powered = x
5.000012953048684 if y == 0:
5.000000000016778 powered=1
5.0 else:
Square Root of 25 is 5.0 while y > 1:
3.9.2 GCD powered *= x
y -= 1
35 36
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
return powered the sum of the first element of the list (numList[0]), and the sum of the numbers in the rest of
a=4 the list (numList[1:]). To state it in a functional form:
b=3
listSum(numList)=first(numList)+listSum(rest(numList))
print(a, ' Power ', b, ' is ', my_pow(a,b))
Output will be: I n this equation first(numList)) returns the first element of the list
4 Power 3 is 64 and rest(numList) returns a list of everything but the first element. This is easily expressed in
Python as shown in Recursive Summation program.
3.9.4 Sum of a List (Array) of Numbers Recursive Summation:
def listsum(numList):
Suppose that you want to calculate the sum of a list of numbers such as: [1,
if len(numList) == 1:
3,5,7,9]. An iterative function that computes the sum is shown in Iterative Summation return numList[0]
program. The function uses an accumulator variable (Sum) to compute a running total of all else:
the numbers in the list by starting with 00 and adding each number in the list. return numList[0] + listsum(numList[1:])
my_list=[1,3,5,7,9]
Iterative Summation: print(listsum(my_list))
def listsum(numList):
Sum = 0 Output will be:
for i in numList: 25
Sum = Sum + i There are a few key ideas in this listing to look at. First, on line 2 we are
return Sum 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
my_list=[1,3,5,7,9] the list. Second, on line 5 our function calls itself! This is the reason that we call
print(listsum(my_list)) the listsum algorithm recursive. A recursive function is a function that calls itself.
Output will be:
25 Figure 3.9 shows the series of recursive calls that are needed to sum the
Pretend for a minute that you do not have while loops or for loops. How would list [1,3,5,7,9]. You should think of this series of calls as a series of simplifications. Each
you compute the sum of a list of numbers? If you were a mathematician you might start by time we make a recursive call we are solving a smaller problem, until we reach the point
recalling that addition is a function that is defined for two parameters, a pair of numbers. To where the problem cannot get any smaller.
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 Figure 3.9 Recursive Calls in List Sum
37 38
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
When we reach the point where the problem is as simple as it can get, we Example:
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.
39 40
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
41 42
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
UNIT IV
LISTS, TUPLES, DICTIONARIES
GE8151 - PROBLEM SOLVING AND PYTHON In this Unit we will discuss about Python‘s built-in compound types like Lists,
Tuples, Dictionaries and their use.
PROGRAMMING
4.1 LISTS
Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in a list are called elements or
REGULATIONS – 2017 sometimes items. There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and ]): It can have any number of items and they may be of
different types (integer, float, string etc.).
Syntax
UNIT – IV []
[1, 2, 3]
# empty list
# list of integers
['physics', 'chemistry',‘computer‘] # list of strings
[1, "Hello", 3.4] # list with mixed datatypes
Also, a list can even have another list as an item. This is called nested list.
my_list = ["mouse", [8, 4, 6], ['a']] # nested list
As you might expect, you can assign list values to variables:
>>>subject= ['physics', 'chemistry','computer']
>>>mark=[98,87,94]
>>>empty=[]
>>> print(Subject,mark,empty)
['physics', 'chemistry', 'computer'], [98, 87, 94], []
Chennai -600119.
1 2
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
0 'physics'
subject
1 'chemistry' This works well if you only need to read the elements of the list. But if you
want to write or update the elements, you need the indices. A common way to do that is to
2 'computer' combine the built-in functions range and len:
The Syntax is :
for ITERATION_VARIABLE in range(len(LIST_NAME)):
STATEMENT(S) Using LIST_NAME[ITERATION_VARIABLE]
0 98
mark ITERATION_VARIABLE holds value from 0 to length of LIST_NAME one by one.
1 87 Using that ITERATION_VARIABLE we can access individual element of LIST_NAME for
reading and writing
2 94 >>> for i in range(len(mark)):
100
mark[i] = mark[i] * 2
>>> mark
[196, 174, 200]
This loop traverses the list and updates each element. len returns the number
of elements in the list. range returns a list of indices from 0 to n-1, where n is the length of
empt
the list. Each time through the loop i gets the index of the next element. The assignment
y
Figure 4.1 State diagrams statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never runs the body:
Figure 4.1 shows the state diagram for the lists subject, mark, and empty. 2nd for x in []:
element of mark, which used to be 94, is now 100 print('This never happens.')
Although a list can contain another list, the nested list still counts as a single
List indices work the same way as string indices:
Any integer expression can be used as an index. element. The length of the following list is 3:
If you try to read or write an element that does not exist, you get an IndexError. >>> my_list = ["mouse", [8, 4, 6], ['a']]
If an index has a negative value, it counts backward from the end of the list. >>> len(my_list)
The in operator also works on lists. 3
>>> subject= ['physics', 'chemistry', 'computer'] 4.1.3 List Operations
>>> 'chemistry' in subject The + operator concatenates lists:
True >>> first=[100,200,300]
>>> 'english' in subject >>> second=[55,65]
False >>> third=first+second
4.1.2 Traversing a List, List Loop >>> third
The most common way to traverse the elements of a list is with a for loop. [100, 200, 300, 55, 65]
The Syntax is : The * operator repeats a list a given number of times:
for VARIABLE in LIST:
>>> [5]*3
STATEMENT(S) USING VARIABLE
[5, 5, 5]
Elements in the List are stores in VARIABLE one by one for each iteration.
>>> [55,65]*3
WE can use the element stored in VARIABLE for further processing inside the loop body
Example: [55, 65, 55, 65, 55, 65]
>>> for s in subject: 4.1.4 List Slices
print(s) The slice operator also works on lists:
>>> w=['w','e','l','c','o','m','e']
physics >>> w[2:5]
chemistry ['l', 'c', 'o']
computer >>> w[:3 ]
3 4
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
['w', 'e', 'l'] Removes object obj from list [123, 'zara', 'abc']
>>> w[5:] 8 list.reverse() >>> aList = [123, 'xyz', 'zara', 'abc', 'xyz']
['m', 'e']
>>> w[:] >>> aList.reverse()
Reverses objects of list in place >>> aList
['w', 'e', 'l', 'c', 'o', 'm', 'e']
['xyz', 'abc', 'zara', 'xyz', 123]
If you omit the first index, the slice starts at the beginning. If you omit the 9 >>> t = ['d', 'c', 'e', 'b', 'a']
list.sort([func])
second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list. >>> t.sort()
4.1.5 List Methods >>> t
Python includes following list methods. Sorts objects of list, use compare func if ['a', 'b', 'c', 'd', 'e']
SN Methods with Description Example given
4.1.6 Deleting Elements
1 list.append(obj) >>> t = ['a', 'b', 'c'] There are several ways to delete elements from a list. If you know the index of
>>> t.append('d') the element you want to delete, you can use pop:
>>> t >>> t = ['a', 'b', 'c']
Appends object obj to list ['a', 'b', 'c', 'd'] >>> x = t.pop(1)
2 >>> aList = [123, 'xyz', 'zara', 'abc', 123] >>> t
list.count(obj)
>>> aList.count(123) ['a', 'c']
2 >>> x
Returns count of how many times obj >>> aList.count('xyz') 'b'
occurs in list 1 pop modifies the list and returns the element that was removed. If you don‘t
3 list.extend(seq) >>> t1 = ['a', 'b', 'c'] provide an index, it deletes and returns the last element. If you don‘t need the removed value,
>>> t2 = ['d', 'e'] you can use the del operator:
>>> t1.extend(t2)
>>> t = ['a', 'b', 'c']
Appends the contents of seq to list >>> t1
['a', 'b', 'c', 'd', 'e'] >>> del t[1]
>>> t
This example leaves t2 unmodified. ['a', 'c']
If you know the element you want to remove (but not the index), you can use remove:
4 list.index(obj) aList = [123, 'xyz', 'zara', 'abc', 123]
>>> t = ['a', 'b', 'c']
>>> aList.index(123)
0 >>> t.remove('b')
Returns the lowest index in list that obj >>> aList.index('xyz') >>> t
appears 1 ['a', 'c']
5 >>> aList.insert( 3, 2009) The return value from remove is None. To remove more than one element, you can use del
list.insert(index, obj)
>>> aList with a slice index:
[123, 'xyz', 'zara', 2009, 'abc', 123] >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
Inserts object obj into list at offset index >>> del t[1:5]
6 list.pop(obj=list[-1]) >>> aList = [123, 'xyz', 'zara', 'abc'] >>> t
>>> aList.pop() ['a', 'f']
'abc'
As usual, the slice selects all the elements up to but not including the second index.
Removes and returns last object or obj >>> aList.pop(2)
from list 'zara' 4.1.7 Aliasing
>>> aList If one is a refers to an object and you assign two = one, then both variables
[123, 'xyz'] refer to the same object:
7 list.remove(obj) >>> aList = [123, 'xyz', 'zara', 'abc'] >>> one = [10, 20, 30]
>>> aList.remove('xyz')
>>> two = one
>>> aList
5 6
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
7 8
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
[81, 82, [5, 84]] The return value from append is None.
[81, 10, [5, 84]] Here‘s an example using the + operator:
>>> t3 = t1 + [40]
Deep copy Example: >>> t1
[10, 20, 30]
import copy >>> t3
a = [81, 82, [83,84]] [10, 20, 30, 40]
b = copy.deepcopy(a) # make a clone using deepcopy() The result of the operator is a new list, and the original list is unchanged. This
print(a == b) difference is important when you write functions that are supposed to modify lists. For
print(a is b) example, this function does not delete the head of a list:
b[1]=10 def bad_delete_head(t):
b[2][0] = 5 t = t[1:] # WRONG!
print(a) The slice operator creates a new list and the assignment makes t refer to it, but
that doesn‘t affect the caller.
print(b)
>>> t4 = [10, 20, 30]
Output will be:
>>> bad_delete_head(t4)
True
>>> t4
False
[10, 20, 30]
[81, 82, [83, 84]]
At the beginning of bad_delete_head, t and t4 refer to the same list. At the end,
[81, 10, [5, 84]]
t refers to a new list, but t4 still refers to the original, unmodified list. An alternative is to
We can notice the difference between shallow copy and deep copy from the write a function that creates and returns a new list. For example, tail returns all except first
above examples. In shallow copy method change made in nested list b affect list a also it is element of a list:
same as copying using slice operator. But in deep copy method changes made in nested list b def tail(t):
does not affect list a.
return t[1:]
This function leaves the original list unmodified. Here‘s how it is used:
4.1.9 List Parameters
>>> letters = ['x', 'y', 'z']
>>> rest = tail(letters)
When you pass a list to a function, the function gets a reference to the list. If
>>> rest
the function modifies the list, the caller sees the change. For example, delete_head removes
the first element from a list: ['y', 'z']
def delete_head(t):
del t[0] 4.2 TUPLES
Here‘s how it is used:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
>>> letters = ['x', 'y', 'z']
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
>>> delete_head(letters) lists and tuples use parentheses, whereas lists use square brackets.
>>> letters 4.2.1 Creating Tuples
['y', 'z']
Similar to List, Tuple is a sequence of values. The values can be any type, and
The parameter t and the variable letters are aliases for the same object. It is they are indexed by integers. The important difference is that tuples are immutable.
important to distinguish between operations that modify lists and operations that create new Syntactically, a tuple is a comma-separated list of values:
lists. For example, the append method modifies a list, but the + operator creates a new list. >>>message= 'h','a','i'
Here‘s an example using append:
>>> type(message)
>>> t1 = [10, 20]
<type 'tuple'>
>>> t2 = t1.append(30)
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t1
>>> message= ('h','a','i')
[10, 20, 30]
>>> type(message)
>>> t2
<type 'tuple'>
None
9 10
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
To create a tuple with a single element, you have to include a final comma: 4.2.2 Tuple Assignment
>>> t1 = 'a', It is often useful to swap the values of two variables. With conventional
>>> type(t1) assignments, you have to use a temporary variable. For example, to swap a and b:
<class 'tuple'> >>> temp = a
A value in parentheses is not a tuple: >>> a = b
>>> t2 = ('a') >>> b = temp
>>> type(t2) This solution is cumbersome; tuple assignment is more elegant:
<class 'str'> >>> a, b = b, a
Another way to create a tuple is the built-in function tuple. With no argument, it creates The left side is a tuple of variables; the right side is a tuple of expressions.
an empty tuple: Each value is assigned to its respective variable. All the expressions on the right side are
>>> t = tuple() evaluated before any of the assignments. The number of variables on the left and the number
>>> t of values on the right have to be the same:
() >>> a, b = 1, 2, 3
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of ValueError: too many values to unpack
the sequence: More generally, the right side can be any kind of sequence (string, list or
>>> course=tuple('python') tuple). For example, to split an email address into a user name and a domain, you could write:
>>> course >>> email='[email protected]'
('p', 'y', 't', 'h', 'o', 'n') >>> username,domain=email.split('@')
Because tuple is the name of a built-in function, you should avoid using it as a variable name. The return value from split is a list with two elements; the first element is
Most list operators also work on tuples. The square bracket operator indexes an element: assigned to username, the second to domain.
>>> course = ('p', 'y', 't', 'h', 'o', 'n') >>> username
>>> cource[0] 'hodcse'
'p' >>> domain
And the slice operator selects a range of elements. 'stjosephs.ac.in'
>>> course[3:5] 4.2.3 Tuples as return Values
('h', 'o') Strictly speaking, a function can only return one value, but if the value is a
But if you try to modify one of the elements of the tuple, you get an error: tuple, the effect is the same as returning multiple values. For example, if you want to divide
>>> course[0]='P' two integers and compute the quotient and remainder, it is inefficient to compute x/y and then
TypeError: 'tuple' object does not support item assignment x%y. It is better to compute them both at the same time.
Because tuples are immutable, you can‘t modify the elements. But you can replace one tuple The built-in function divmod takes two arguments and returns a tuple of two
with another: values, the quotient and remainder. You can store the result as a tuple:
>>> course=('P',)+course[1:] >>> t = divmod(7, 3)
>>> course >>> t
('P', 'y', 't', 'h', 'o', 'n') (2, 1)
This statement makes a new tuple and then makes course refer to it. The relational operators Or use tuple assignment to store the elements separately:
work with tuples and other sequences; Python starts by comparing the first element from each >>> quot, rem = divmod(7, 3)
sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements Here is an example of a function that returns a tuple:
that differ. Subsequent elements are not considered, even if they are really big. def min_max(t):
>>> (0, 1, 2) < (0, 3, 4) return min(t), max(t)
True max and min are built-in functions that find the largest and smallest elements
>>> (0, 1, 2000000) < (0, 3, 4) of a sequence. min_max computes both and returns a tuple of two values.
True >>> quot
2
>>> rem
1
11 12
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
13 14
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
A dictionary contains a collection of indices, which are called keys, and a To see whether something appears as a value in a dictionary, you can use the
collection of values. Each key is associated with a single value. The association of a key and method values, which returns a collection of values, and then use the in operator:
a value is called a key-value pair or sometimes an item. >>> meaning = eng_tam.values()
>>> 'irantu' in meaning
In mathematical language, a dictionary represents a mapping from keys to True
values, so you can also say that each key ―maps to‖ a value. As an example, we‘ll build a
dictionary that maps from English to Tamil words, so the keys and the values are all strings. The in operator uses different algorithms for lists and dictionaries. For lists, it
The function dict creates a new dictionary with no items. Because dict is the searches the elements of the list in order. As the list gets longer, the search time gets longer in
name of a built-in function, you should avoid using it as a variable name. direct proportion. For dictionaries, Python uses an algorithm called a hashtable that has a
4.3.2 Creates Dictionary remarkable property: the in operator takes about the same amount of time no matter how
>>> eng_tam=dict() many items are in the dictionary.
>>> eng_tam
{} 4.3.3 Dictionary as a Collection of Counters
The squiggly-brackets, {}, represent an empty dictionary. To add items to the Suppose you are given a string and you want to count how many times each
dictionary, you can use square brackets: letter appears.
>>> eng_tam['two']='irantu' There are several ways you could do it:
This line creates an item that maps from the key 'two' to the value 'irantu'. If 1. You could create 26 variables, one for each letter of the alphabet. Then you could
we print the dictionary again, we see a key-value pair with a colon between the key and traverse the string and, for each character, increment the corresponding counter,
probably using a chained conditional.
value:
2. You could create a list with 26 elements. Then you could convert each character to a
>>> eng_tam number (using the built-in function ord), use the number as an index into the list, and
{'two': 'irantu'} increment the appropriate counter.
This output format is also an input format. For example, you can create a new 3. You could create a dictionary with characters as keys and counters as the
dictionary with three items: corresponding values. The first time you see a character, you would add an item to the
>>> eng_tam={'two':'irantu','three':'munru','four':'nanku'} dictionary. After that you would increment the value of an existing item.
But if you print eng_tam, you might be surprised: Each of these options performs the same computation, but each of them implements that
>>> eng_tam computation in a different way.
{'four': 'nanku', 'two': 'irantu', 'three': 'munru'} An implementation is a way of performing a computation; some
The order of the key-value pairs might not be the same. If you type the same implementations are better than others. For example, an advantage of the dictionary
example on your computer, you might get a different result. In general, the order of items in a implementation is that we don‘t have to know ahead of time which letters appear in the string
dictionary is unpredictable. and we only have to make room for the letters that do appear.
Here is what the code might look like:
But that‘s not a problem because the elements of a dictionary are never
indexed with integer indices. Instead, you use the keys to look up the corresponding values: def histogram(s):
>>> eng_tam['two'] d = dict()
'irantu' for c in s:
The key 'two' always maps to the value ' irantu ' so the order of the items if c not in d:
doesn‘t matter. If the key isn‘t in the dictionary, you get an exception: d[c] = 1
>>> eng_tam['five'] else:
KeyError: 'five' d[c] += 1
The len function works on dictionaries; it returns the number of key-value pairs: return d
>>> len(eng_tam)
The name of the function is histogram, which is a statistical term for a
3
collection of counters (or frequencies). The first line of the function creates an empty
The in operator works on dictionaries, too; it tells you whether something
dictionary. The for loop traverses the string. Each time through the loop, if the character c is
appears as a key in the dictionary (appearing as a value is not good enough). not in the dictionary, we create a new item with key c and the initial value 1 (since we have
>>> 'two'in eng_tam seen this letter once). If c is already in the dictionary we increment d[c].
True Here‘s how it works:
>>> 'irantu' in eng_tam
False >>> h=histogram('python programmimg')
15 16
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
>>> h But what if you have v and you want to find k? You have two problems: first,
{'a': 1, ' ': 1, 'g': 2, 'i': 1, 'h': 1, 'm': 3, 'o': 2, 'n': 1, 'p': 2, 'r': 2, 't': 1, 'y': 1} there might be more than one key that maps to the value v. Depending on the application, you
The histogram indicates that the letters 'a ' and ' ' appear once; 'g' appears might be able to pick one, or you might have to make a list that contains all of them. Second,
twice, and so on. Dictionaries have a method called get that takes a key and a default value. If there is no simple syntax to do a reverse lookup; you have to search.
the key appears in the dictionary, get returns the corresponding value; otherwise it returns the Here is a function that takes a value and returns the first key that maps to that
default value. For example: value:
>>> h = histogram('a')
>>> h def reverse_lookup(d, v):
{'a': 1} for k in d:
>>> h.get('a', 0) if d[k] == v:
1 return k
>>> h.get('b', 0) raise LookupError()
0
>>> This function is yet another example of the search pattern, but it uses a feature
4.3.4 Looping and Dictionaries we haven‘t seen before, raise. The raise statement causes an exception; in this case it
causes a LookupError, which is a built-in exception used to indicate that a lookup operation
If you use a dictionary in a for statement, it traverses the keys of the
failed.
dictionary. For example, print_hist prints each key and the corresponding value:
If we get to the end of the loop, that means v doesn‘t appear in the dictionary
def print_hist(h):
as a value, so we raise an exception.
for c in h:
Here is an example of a successful reverse lookup:
print(c, h[c])
>>> h = histogram('programming')
Here‘s what the output looks like:
>>> key = reverse_lookup(h, 2)
>>> h = histogram('programming')
>>> key
>>> print_hist(h)
'g'
('a', 1)
And an unsuccessful one:
('g', 2)
>>> key = reverse_lookup(h, 3)
('i', 1)
('m', 2)
Traceback (most recent call last):
('o', 1)
File "<pyshell#38>", line 1, in <module>
('n', 1)
key = reverse_lookup(h, 3)
('p', 1)
File "G:\class\python\code\dictionary.py", line 22, in reverse_lookup
('r', 2)
raise LookupError()
Again, the keys are in no particular order. To traverse the keys in sorted order,
LookupError
you can use the built-in function sorted:
>>> for key in sorted(h):
The effect when you raise an exception is the same as when Python raises one:
print(key, h[key])
it prints a traceback and an error message. The raise statement can take a detailed error
message as an optional argument. For example:
('a', 1)
>>> raise LookupError('value does not appear in the dictionary')
('g', 2)
Traceback (most recent call last):
('i', 1)
File "<stdin>", line 1, in ?
('m', 2)
LookupError: value does not appear in the dictionary
('n', 1)
A reverse lookup is much slower than a forward lookup; if you have to do it
('o', 1)
often, or if the dictionary gets big, the performance of your program will suffer.
('p', 1)
('r', 2)
4.3.6 Dictionaries and Lists
4.3.5 Reverse Lookup
Lists can appear as values in a dictionary. For example, if you are given a
Given a dictionary d and a key k, it is easy to find the corresponding value v =
dictionary that maps from letters to frequencies, you might want to invert it; that is, create a
d[k]. This operation is called a lookup.
dictionary that maps from frequencies to letters. Since there might be several letters with the
17 18
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
same frequency, each value in the inverted dictionary should be a list of letters. Here is a The syntax of a list comprehension is a little awkward because the loop
function that inverts a dictionary: variable, s in this example, appears in the expression before we get to the definition.
List comprehensions can also be used for filtering. For example, this function
def invert_dict(d): selects only the elements of t that are upper case, and returns a new list:
inverse = dict() def only_upper(t):
for key in d: res = []
val = d[key] for s in t:
if val not in inverse: if s.isupper():
inverse[val] = [key] res.append(s)
else: return res
inverse[val].append(key) We can rewrite it using a list comprehension
return inverse def only_upper(t):
return [s for s in t if s.isupper()]
Each time through the loop, key gets a key from d and val gets the List comprehensions are concise and easy to read, at least for simple
corresponding value. If val is not in inverse, that means we haven‘t seen it before, so we expressions. And they are usually faster than the equivalent for loops, sometimes much
create a new item and initialize it with a singleton (a list that contains a single element). faster.
Otherwise we have seen this value before, so we append the corresponding key to the list.
Here is an example: 4.4 ILLUSTRATIVE PROGRAMS
>>> hist = histogram('programming')
>>> hist 4.4.1 Sorting
{'a': 1, 'g': 2, 'i': 1, 'm': 2, 'o': 1, 'n': 1, 'p': 1, 'r': 2} It is an operation in which all the elements of a list are arranged in a
>>> inverse = invert_dict(hist) predetermined order. The elements can be arranged in a sequence from smallest to largest
>>> inverse such that every element is less than or equal to its next neighbour in the list. Such an
{1: ['a', 'i', 'o', 'n', 'p'], 2: ['g', 'm', 'r']}
arrangement is called ascending order. Assuming an array or List containing N elements, the
Lists can be values in a dictionary, as this example shows, but they cannot be
keys. Here‘s what happens if you try: ascending order can be defined by the following relation:
>>> t = [1, 2, 3]
List[i] <= List [i+1], 0 < i < N-1
>>> d = dict()
>>> d[t] = 'oops' Similarly in descending order, the elements are arranged in a sequence from
Traceback (most recent call last):
File "<stdin>", line 1, in ? largest to smallest such that every element is greater than or equal to its next neighbor in the
TypeError: list objects are unhashable list. The descending order can be defined by the following relation:
19 20
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Algorithm SelectionSort()
An algorithm for selection sort is given below. In this algorithm, the elements
of a list stored in an array called LIST[] are sorted in ascending order. Two variables called
Small and Pos are used to locate the smallest element in the unsorted part of the list. Temp is
the variable used to interchange the selected element with the first element of the unsorted
part of the list.
21 22
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
for j in range(i+1,n):
if int(data[j])<small:
small=int(data[j])
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)
Output
Selection Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :4
Enter the Element 2 :3
Enter the Element 3 :6
Enter the Element 4 :8
Enter the Element 5 :1
Original Array :
['4', '3', '6', '8', '1']
Intermediate Steps :
['1', '3', '6', '8', '4']
['1', '3', '6', '8', '4']
['1', '3', '4', '8', '6']
['1', '3', '4', '6', '8']
Sorted Array :
['1', '3', '4', '6', '8']
23 24
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
3. Stop
data = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
for i in range(1,n):
temp=int(data[i])
j=i-1
while temp<int(data[j]) and j>=0:
Figure 4.6 Insertion sort data[j+1]=data[j]
j=j-1
It may be noted that the insertion operation requires following steps: data[j+1]=temp
print(data)
Step print('Sorted Array is:')
print(data)
1. Scan the sorted part to find the place where the element, from unsorted part, can
be inserted. While scanning, shift the elements towards right to create space. Output
2. Insert the element, from unsorted part, into the created space.
Insertion Sort :
This algorithm for the insertion sort is given below. In this algorithm, the elements of Enter Number of Elements in the Array: 5
a list stored in an array called List[] are sorted in an ascending order. The algorithm uses two Enter the Element 1 :3
loops – the outer For loop and inner while loop. The inner while loop shifts the elements of Enter the Element 2 :5
Enter the Element 3 :2
the sorted part by one step to right so that proper place for incoming element is created. The Enter the Element 4 :8
outer For loop inserts the element from unsorted part into the created place and moves to next Enter the Element 5 :1
element of the unsorted part. Original Array :
['3', '5', '2', '8', '1']
Algorithm insertSort() Intermediate Steps :
['3', '5', '2', '8', '1']
1. For I = 2 to N #The first element becomes the sorted part ['2', '3', '5', '8', '1']
['2', '3', '5', '8', '1']
1.1 Temp = List[I] #Save the element from unsorted part into temp
['1', '2', '3', '5', '8']
1.2 J = I-1 Sorted Array is:
1.3 While(Temp < = List[J] AND J >=0) ['1', '2', '3', '5', '8']
1.3.1 List[J+I] = List[J] #Shift elements towards right
4.4.4 Merge Sort
1.3.2 J = J-I
This method uses following two concepts:
1.4 List [J+I] = Temp
If a list is empty or it contains only one element, then the list is already sorted. A list
2. Print the list that contains only one element is also called singleton.
25 26
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
It uses old proven technique of ‗divide and conquer‘ to recursively divide the list into Note: The merge operation is a time consuming and slow operation. The working of merge
sub-lists until it is left with either empty or singleton lists. operation is discussed in the next section.
In fact, this algorithm divides a given list into two almost equal sub-lists. Each Merging of lists It is an operation in which two ordered lists are merged into a single
sub-list, thus obtained, is recursively divided into further two sub-lists and so on till ordered list. The merging of two lists PAR1 and PAR2 can be done by examining the
singletons or empty lists are left as shown in Figure 4.7. elements at the head of two lists and selecting the smaller of the two. The smaller element is
then stored into a third list called mergeList. For example, consider the lists PAR1 and PAR2
Since the singleton and empty list are inherently sorted, the only step left is to given the figure 4.9. Let Ptr1, Ptr2, and Ptr3 variables point to the first locations of lists
merge the singletons into sub-lists containing two elements each (see figure 4.7) which are PAR1, PAR2 and PAR3, respectively. The comparison of PAR1[Ptr1] and PAR2[Ptr2]
further merged into sub-lists containing four elements each and so on. This merging operation shows that the element of PAER1 (i.e., ‗2‘) is smaller. Thus, this element will be placed in
is recursively carried out till a final merged list is obtained as shown in figure 4.8. the mergeList as per the following operation:
mergeList[Ptr3] S= PAR1[Ptr1];
Ptr1++;
Ptr3++;
Since an element from the list PAR1 has been taken to mergeList, the variable
Ptr1 is accordingly incremented to point to the next location in the list. The variable Ptr3 is
also incremented to point to next vacant location in mergeList.
This process of comparing, storing and shifting is repeated till both the lists
are merged and stored in mergeList as shown in figure 4.10.
27 28
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
5.2 ptr1++
5.3 ptr3++
}
6. while (ptr2 <= ub) #copy remaining second list
6.1 mergeList [ptr3] = List[ptr2]
6.2 ptr2++
6.3 ptr3++
7. for(i=lb; i<ptr3; i++) #copy merged list back into original list
8. Stop
It may be noted that an extra temporary array called mergedList is required to
store the intermediate merged sub-lists. The contents of the mergeList are finally copied back
into the original list.
The algorithm for the merge sort is given below. In this algorithm, the
Figure 4.10 Merging of lists (second step) elements of a list stored in a array called List[] are sorted in an ascending order. The
algorithm has two parts- mergeSort and merge. The merge algorithm, given above, merges
It may be noted here that during this merging process, a situation may arise two given sorted lists into a third list, which is also sorted. The mergeSort algorithm takes a
when we run out of elements in one of the lists. We must, therefore, stop the merging process list and stores into an array called List[]. It uses two variables lb and ub to keep track of lower
and copy rest of the elements from unfinished list into the final list. and upper bounds of list or sub-lists as the case may be. It recursively divides the list into
almost equal parts till singleton or empty lists are left. The sub-lists are recursively merged
The algorithm for merging of lists is given below. In this algorithm, the two through merge algorithm to produce final sorted list.
sub-lists are part of the same array List[]. The first sub-list in locations List[lb] to List[mid]
and the second sub-list is stored in locations List [mid+1] to List [ub] where lb and ub mean Algorithm mergeSort (List, lb, ub)
lower and upper bounds of the array, respectively.
1. if (lb<ub)
Algorithm merge (List, lb, mid, ub)
1.1mid = (lb+ub)/2 #divide the list into two sub-lists
1. ptr1 =lb # index of first list
2. ptr2 = mid # index of second list 1.2 mergeSort(List, lb, mid) #sort the left sub-list
3. ptr3 = lb #index of merged list
1.3 mergeSort(List, mid+1, ub) #sort the right sub-list
4. while ((ptr1 < mid) && ptr2 <= ub) #merge the lists
4.1 if (List[ptr1 <= List[ptr2]) 1.4 merge(List, lb, mid+1, ub) #merge the lists
4.1.1 mergeList[ptr3] = List[ptr1] #element from firstlist is taken 2. Stop
4.1.2 ptr1++ #move to next element in the list Program to sort a List in ascending order using Merge Sort
4.1.3 ptr3++ def mergeSort(alist):
print("Splitting ",alist)
4.2 else if len(alist)>1:
4.2.1 mergeList[ptr3] = List[ptr2] #element from second list is taken mid = len(alist)//2
4.2.2 ptr2++ #move to next element in the list lefthalf = alist[:mid]
4.2.3 ptr3++ righthalf = alist[mid:]
5. while(ptr1 < mid) #copy remaining first list mergeSort(lefthalf)
mergeSort(righthalf)
5.1 mergeList [ptr3] = List[ptr1]
i=0
29 30
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
31 32
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
#travel the list from lb till an element greater than the pivot is found
3.1 while (List[i] <= pivot) i++
# travel the list from ub till an element smaller than the pivot is found
3.2 while (List[j]> pivot) j--
3.3 if (i <= j) #exchange the elements
3.3.1 temp = List[i]
3.3.2 List[i] = List[j]
3.3.3 List[j] = temp
4. temp =List[j] #place the pivot at mid of the sub-lists
5. List[j] = List[lb-1]
6. List[lb-1] = temp
7. if (j>lb) quicksort (List, lb, j-1) #sort left sub-list
8. if(j<ub) quicksort (List, j+1, ub) #sort the right sub-lists
33 34
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
quicksort(data,0,n-1)
print('Sorted Array is:')
print(data)
Output
Quick Sort :
Enter Number of Elements in the Array: 8
Enter the Element 1 :8
Enter the Element 2 :5
Enter the Element 3 :6
Enter the Element 4 :9
Enter the Element 5 :4
Enter the Element 6 :19
Enter the Element 7 :7
Enter the Element 8 :2
Original Array :
['8', '5', '6', '9', '4', '19', '7', '2']
Intermediate Steps :
['7', '5', '6', '2', '4', '8', '19', '9']
['4', '5', '6', '2', '7', '8', '19', '9']
['2', '4', '6', '5', '7', '8', '19', '9']
['2', '4', '5', '6', '7', '8', '19', '9']
['2', '4', '5', '6', '7', '8', '9', '19']
Sorted Array is:
['2', '4', '5', '6', '7', '8', '9', '19']
35
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
UNIT V
FILES, MODULES, PACKAGES
GE8151 - PROBLEM SOLVING AND PYTHON 5.1 FILES
PROGRAMMING Most of the programs we have seen so far are transient in the sense that they
run for a short time and produce some output, but when they end, their data disappears. If you
run the program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they keep at least
REGULATIONS – 2017 some of their data in permanent storage (a hard drive, for example); and if they shut down
and restart, they pick up where they left off.
One of the simplest ways for programs to maintain their data is by reading and
writing text files. An alternative is to store the state of the program in a database.
UNIT – V 5.1.1 Text Files
Python provides inbuilt functions for creating, writing and reading files. There
are two types of files that can be handled in python, normal text files and binary files (written
in binary language,0s and 1s).
Text files: In this type of file, each line of text is terminated with a special character
called EOL (End of Line), which is the new line character („\n‟) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
In order to perform some operations on files we have to follow below steps
Opening
Reading or writing
Closing
Here we are going to discusses about opening, closing, reading and writing data in a text file.
Prepared By :
5.1.2.1 File Access Modes
Mr. Vinu S, ME, Access modes govern the type of operations possible in the opened file. It
refers to how the file will be used once its opened. These modes also define the location of
Assistant Professor, the File Handle in the file. File handle is like a cursor, which defines from where the data has
to be read or written in the file. There are 6 access modes in python.
St.Joseph’s College of Engineering,
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
Chennai -600119. of the file. If the file does not exists, raises I/O error. This is also the default mode in
which file is opened.
1 2
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
Read and Write (‘r+’) : Open the file for reading and writing. The handle is 5.1.5 Reading from a File
positioned at the beginning of the file. Raises I/O error if the file does not exists. To read the content of a file, we must open the file in reading mode.
Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated There are three ways to read data from a text file.
and over-written. The handle is positioned at the beginning of the file. Creates the file
if the file does not exists. 1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data reads the entire file.
is truncated and over-written. The handle is positioned at the beginning of the file. File_object.read([n])
Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. 2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads
The handle is positioned at the end of the file. The data being written will be inserted at most n bytes. However, does not reads more than one line, even if n exceeds the
at the end, after the existing data. length of the line.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if File_object.readline([n])
it does not exist. The handle is positioned at the end of the file. The data being written 3. readlines() : Reads all the lines and return them as each line a string element in a list.
will be inserted at the end, after the existing data. File_object.readlines()
Example:
5.1.3 Opening a File
Consider the content of file sample.txt that is present in location G:\class\python\code\ as
It is done using the open() function. No module is required to be imported for
this function. Read Only
Syntax: Read and Write
Write OnlyWrite and Read
File_object = open(r"File_Name","Access_Mode")
Append Only
The file should exist in the same directory as the python program file else, full
Append and Read
address (path will be discussed in later section of this unit) of the file should be written on
place of filename. Note: The r is placed before filename to prevent the characters in filename Now execute the following file reading script.
string to be treated as special character. For example, if there is \temp in the file address, then >>> f1=open("G:\class\python\code\sample.txt","r")
\t is treated as the tab character and error is raised of invalid address. The r makes the string >>> f1.read()
raw, that is, it tells that the string is without any special characters. The r can be ignored if the 'Read Only\nRead and Write\nWrite Only\nWrite and Read\nAppend Only\nAppend and
file is in same directory and address is not being placed. Read'
Example: Here \n denotes next line character. If you again run the same script, you will
get empty string. Because during the first read statement itself file handler reach the end of
>>> f1 = open("sample.txt","a") the file. If you read again it will return empty string
>>> f2 = open(r"G:\class\python\sample3.txt","w+") >>> f1.read()
''
Here, f1 is created as object for sample.txt and f3 as object for sample3.txt So in order to take back the file handler to the beginning of the file you have
(available in G:\class\python directory) to open the file again or use seek() function. We will discuss about seek function in
upcoming section.
>>> f1=open("G:\class\python\code\sample.txt","r")
5.1.4 Closing a File >>> f1.read(10)
close() function closes the file and frees the memory space acquired by that 'Read Only\n'
file. It is used at the time when the file is no longer needed or if it is to be opened in a >>> f1=open("G:\class\python\code\sample.txt","r")
different file mode.
>>> f1.readline()
Syntax:
File_object.close() 'Read Only\n'
Example: >>> f1=open("G:\class\python\code\sample.txt","r")
>>> f1 = open("smapl.txt","a") >>> f1.readlines()
>>> f1.close() ['Read Only\n', 'Read and Write\n', 'Write Only\n', 'Write and Read\n', 'Append Only\n',
After closing a file we can‟t perform any operation on that file. If want to do 'Append and Read']'
so, we have to open the file again.
3 4
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
5 6
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
7 8
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
C:\Python27\DLLs\sqlite3.dll Example 2
C:\Python27\DLLs\tcl85.dll This is a Python Program to copy the contents of one file into another. Source
C:\Python27\include\abstract.h and destination file names are given through command line argument while running the
C:\Python27\include\asdl.h program.
C:\Python27\include\ast.h
os.path.join takes a directory and a file name and joins them into a complete In order to do this we have to follow the following steps
path.
>>> os.path.join(cwd,'stringsample.txt') 1) Open file name with command line argument one as read mode (input file).
'C:\\Python27\\stringsample.txt' 2) Open file name with command line argument two as write mode (output file).
5.2 COMMAND LINE ARGUMENTS 3) Read each line from the input file and write it into the output file until the input file
data gets over.
It is possible to pass some values from the command line to your python 4) Exit.
programs when they are executed. These values are called command line arguments and
many times they are important for your program especially when you want to control your Program
program from outside instead of hard coding those values inside the code.
import sys
The command line arguments are handled using sys module. We can access
source=open(sys.argv[1],'r')
command-line arguments via the sys.argv. This serves two purposes −
destination=open(sys.argv[2],'w')
while(True):
sys.argv is the list of command-line arguments.
new_line=source.readline()
if new_line=='':
len(sys.argv) is the number of command-line arguments.
break
Here sys.argv[0] is the program name ie. script name. destination.write(new_line)
source.close()
Example 1 destination.close()
Consider the following script command_line.py Now run above script as follows – in Command prompt:
C:\Python27>python.exe copy_file.py input_file.txt output_file.txt
import sys
print 'There are %d arguments'%len(sys.argv) 5.3 ERRORS AND EXCEPTIONS
print 'Argument are', str(sys.argv)
print 'File Name is: ', sys.argv[0] There are two distinguishable kinds of errors: syntax errors and exceptions.
Now run above script as follows – in Command prompt: 5.3.1 Syntax Errors
C:\Python27>python.exe command_line.py vinu ranjith
This produce following result – Syntax errors, also known as parsing errors, are perhaps the most common kind of
There are 3 arguments complaint you get while you are still learning Python. Syntax error is an error in the syntax of a
Argument are ['command_line.py', 'vinu', 'ranjith'] sequence of characters or tokens that is intended to be written in python. For compiled languages,
syntax errors are detected at compile-time. A program will not compile until all syntax errors are
File Name is: command_line.py
corrected. For interpreted languages, however, a syntax error may be detected during program
NOTE: As mentioned above, first argument is always script name and it is also being execution, and an interpreter's error messages might not differentiate syntax errors from errors of
counted in number of arguments. Here „vinu‟ and „ranjith‟ are extra inputs passed to other kinds.
program through command line argument method while running python program
command_line.py.
5.3.2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is
made to execute it. Errors detected during execution are called exceptions. You will soon learn how
9 10
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
EOFError Raised when there is no input from either the raw_input() or input() function
to handle them in Python programs. Most exceptions are not handled by programs, however, and
and the end of file is reached.
result in error messages as shown here: ImportError Raised when an import statement fails.
>>> 55+(5/0) KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Traceback (most recent call last): Ctrl+c.
LookupError Base class for all lookup errors.
File "<pyshell#12>", line 1, in <module> IndexError Raised when an index is not found in a sequence.
55+(5/0) KeyError Raised when the specified key is not found in the dictionary.
ZeroDivisionError: integer division or modulo by zero NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no
value has been assigned to it.
>>> 5+ repeat*2 EnvironmentError Base class for all exceptions that occur outside the Python environment.
Traceback (most recent call last): IOError Raised when an input/ output operation fails, such as the print statement or
File "<pyshell#13>", line 1, in <module> the open() function when trying to open a file that does not exist.
OSError Raised for operating system-related errors.
5+ repeat*2
SyntaxError Raised when there is an error in Python syntax.
NameError: name 'repeat' is not defined IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when this error is
>>> '5'+5 encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not
Traceback (most recent call last): handled in the code, causes the interpreter to exit.
File "<pyshell#14>", line 1, in <module> TypeError Raised when an operation or function is attempted that is invalid for the
'5'+5 specified data type.
TypeError: cannot concatenate 'str' and 'int' objects ValueError Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
The last line of the error message indicates what happened. Exceptions come NotImplementedError Raised when an abstract method that needs to be implemented in an inherited
in different types, and the type is printed as part of the message: the types in the example class is not actually implemented.
are ZeroDivisionError, NameError and TypeError. The string printed as the exception type
is the name of the built-in exception that occurred. This is true for all built-in exceptions, but
5.4 HANDLING EXCEPTIONS
need not be true for user-defined exceptions (although it is a useful convention). Standard
Python provides two very important features to handle any unexpected error
exception names are built-in identifiers (not reserved keywords).
in your Python programs and to add debugging capabilities in them.
The rest of the line provides detail based on the type of exception and what caused it.
Exception Handling:
The preceding part of the error message shows the context where the
exception happened, in the form of a stack traceback. In general it contains a stack traceback Assertions:
listing source lines; however, it will not display lines read from standard input.
5.4.1 Exception Handling
Python’s built-in exceptions lists and their meanings.
An exception is an event, which occurs during the execution of a program that
EXCEPTION NAME DESCRIPTION disrupts the normal flow of the program's instructions. In general, when a Python script
Exception Base class for all exceptions
encounters a situation that it cannot cope with, it raises an exception. An exception is a
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function. Python object that represents an error.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation. When a Python script raises an exception, it must either handle the exception
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails. immediately otherwise it terminates and quits.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement. If you have some suspicious code that may raise an exception, you can defend
AttributeError Raised in case of failure of attribute reference or assignment.
your program by placing the suspicious code in a try: block. After the try: block, include
11 12
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
an except: statement, followed by a block of code which handles the problem as elegantly as Example:
possible. This example opens a file with read mode, and tries to write the file where you
do not have write permission, so it raises an exception
Syntax:
try:
Here is simple syntax of try....except...else blocks − fp = open("test_exception.txt", "r")
fp.write("Exception handling")
try:
except IOError:
You do your operations here;
print "Error: File don\'t have read permission"
......................
else:
except ExceptionI:
print "Written successfully"
If there is ExceptionI, then execute this block.
fp.close()
except ExceptionII:
If there is ExceptionII, then execute this block. This produces the following result
...................... Error: File don't have read permission
else:
5.4.2 The except Clause with No Exceptions
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax − You can also use the except statement with no exceptions defined as follows −
A single try statement can have multiple except statements. This is useful when the try:
try block contains statements that may throw different types of exceptions. You do your operations here;
......................
You can also provide a generic except clause, which handles any exception. except:
If there is any exception, then execute this block.
After the except clause(s), you can include an else-clause. The code in the else-block ......................
executes if the code in the try: block does not raise an exception. else:
If there is no exception then execute this block.
The else-block is a good place for code that does not need the try: block's protection. This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good programming practice
Example:
This example opens a file with write mode, writes content in the file and comes though, because it catches all exceptions but does not make the programmer identify the root
out gracefully because there is no problem at all cause of the problem that may occur.
13 14
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
15 16
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
5.4.6 Hierarchical Exceptions Handle Note: In order to catch an exception, an "except" clause must refer to the same exception
Exception handlers don‟t just handle exceptions if they occur immediately in the try thrown either class object or simple string. For example, to capture above exception, we
clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For must write the except clause as follows
example:
try:
def this_fails(): Business Logic here...
x = 1/0 except "Invalid level!":
try: Exception handling here...
this_fails() else:
except ZeroDivisionError, detail: Rest of the code here...
print 'Handling run-time error:', detail
This produces the following result
5.4.8 Assertions in Python
Handling run-time error: integer division or modulo by zero
An assertion is a sanity-check that you can turn on or turn off when you are
In this example exception is raised in this_fails() function. But, because of
done with your testing of the program.
this_fails() function don‟t have except block exception is thrown to the caller function. As there
is a except block, it will handle the exception. The easiest way to think of an assertion is to liken it to a raise-if statement (or
to be more accurate, a raise-if-not statement). An expression is tested, and if the result
5.4.7 Raising an Exceptions
comes up false, an exception is raised.
You can raise exceptions in several ways by using the raise statement. The
Assertions are carried out by the assert statement, the newest keyword to
general syntax for the raise statement is as follows.
Python, introduced in version 1.5.
Syntax
raise [Exception [, args [, traceback]]] Programmers often place assertions at the start of a function to check for valid
Here, Exception is the type of exception (for example, NameError) input, and after a function call to check for valid output.
and argument is a value for the exception argument. The argument is optional; if not
The assert Statement
supplied, the exception argument is None.
When it encounters an assert statement, Python evaluates the accompanying
The final argument, traceback, is also optional (and rarely used in practice), expression, which is hopefully true. If the expression is false, Python raises
and if present, is the traceback object used for the exception. an AssertionError exception.
17 18
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
19 20
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
__name__ is a built-in variable that is set when the program starts. If the 5.7 WORD COUNT
program is running as a script, __name__ has the value '__main__'; in that case, the test code
runs. Otherwise, if the module is being imported, the test code is skipped. Modify Example.
addModule.py file as given below.
def add(a, b): Following program print each word in the specified file occurs how many times.
import sys
result = a + b
def word_count(file_name):
print(result)
try:
if __name__ == '__main__':
file=open(file_name,"r")
add(10,20)
wordcount={}
Now while importing addModule test case is not running
>>> import addModule entier_words=file.read().split()
__name__ has module name as its value when it is imported. Warning: If you for word in entier_words:
import a module that has already been imported, Python does nothing. It does not re-read the if word not in wordcount:
file, even if it has changed. If you want to reload a module, you can use the built-in function wordcount[word] = 1
reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import else:
the module again. wordcount[word] += 1
file.close();
5.6 PACKAGES
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
Packages are namespaces which contain multiple packages and modules
print ("%-30s %d " %(key , wordcount[key]))
themselves. They are simply directories, but with a twist.
except IOError:
Each package in Python is a directory which must contain a special file print ("No file found with name %s" %file_name)
called __init__.py. This file can be empty, and it indicates that the directory it contains is a fname=raw_input("Enter New File Name:")
Python package, so it can be imported the same way a module can be imported. word_count(fname)
21 22
For More Visit : www.Learnengineering.in
For More Visit : www.Learnengineering.in
source.close()
destination.close()
except IOError:
print ("Problem with Source or Destination File Name ")
source_name=raw_input("Enter New Source File Name:")
destination_name=raw_input("Enter New Destination File Name:")
copy(source_name,destination_name)
try:
copy(sys.argv[1],sys.argv[2])
except IndexError:
print("Insufficent Command line argument!")
source_name=raw_input("Enter Source File Name:")
destination_name=raw_input("Enter Destination File Name:")
copy(source_name,destination_name)
finally:
print("Copying Done.....")
This produces the following result
C:\Python27>python copy_file_exception.py input_file.txt
Insufficent Command line argument!
Enter Source File Name:input_file.tx
Enter Destination File Name:output_file.txt
Problem with Source or Destination File Name
Enter New Source File Name:input_file.txt
Enter New Destination File Name:output_file.txt
Copying Done.....
25
For More Visit : www.Learnengineering.in