?Phython Gnrl 1
?Phython Gnrl 1
The term ‗algorithm‘ was derived from the name of Mohammed al-Khowarizmi, a
Persian mathematician in the ninth century. Al-Khowarizmi → Algorismus (in Latin) →
Algorithm.
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.
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
contents.
In computer science, control flow (or flow of control) is the order in which
individual statements, instructions or function calls of an algorithm are executed or evaluated.
For complex problems our goal is to divide the task into smaller and simpler functions
during algorithm design. So a set of related sequence of steps, part of larger algorithm is
known as functions.
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
is clear for many miles and the driver has no need to slow down or stop. The car will start in
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
gears.
Selection: A selection is a decision that has to be made. Consider a car approaching a set of
lights. If the lights turn from green to yellow, the driver will have to decide whether to stop or
continue through the intersection. If the driver stops, she will have to wait until the lights are
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
Let as look at two simple algorithms to find the greatest among three numbers,
as follows:
Algorithm 1.1:
Step 1: Start.
Step 2: Read the three numbers A,B,C.
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‖.
Step 5: Compare B and C. If B is greater, output ―B is greatest‖ else output ―C is greatest‖.
Step 6: Stop.
Algorithm 1.2:
Step 1: Start.
Step 2: Read the three numbers A,B,C.
In the Algorithm 1.1, Algorithm 1.2, step 1 and 2 are in sequence logic and step 3, 4,
and 5 are in selection logic. In order to illustrate iteration logic, consider one more example.
Design an algorithm for adding the test scores given as: 26, 49, 98, 87, 62, 75
Algorithm 1.3:
Step 1: Start
Step 2: Sum = 0
Step 3: Get a value
Step 4: sum = sum + value
Step 5: If next value is present, go to step 3. Otherwise, go to step 6
Step 6: Output the sum
Step 7: Stop
In the Algorithm 1.3 step 5 have a go to statement with a back ward step
reference, so it means that iteration logic.
1.3.2 Pseudocode
Pseudocode ("sort of code") is another way of describing algorithms. It is
called "pseudo" code because of its strong resemblance to "real" program code. Pseudocode
is essentially English with some defined rules of structure and some keywords that make
it appear a bit like program code.
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
used here.
1.3.3 Flowcharts
Flowcharts are a diagrammatic method of representing algorithms. They use
an intuitive scheme of showing operations in boxes connected by lines and arrows that
graphically show the flow of control in an algorithm.
Table 1.1lists the flowchart symbol drawing, the name of the flowchart
symbol in Microsoft Office (with aliases in parentheses), and a short description of where and
how the flowchart symbol is used.
NAME
SYMBOL DESCRIPTION
(ALIAS)
Flow Line
Flow line connectors show the direction that the process
(Arrow,
flows.
Connector)
Terminator
(Terminal Terminators show the start and stop points in a process.
Point, Oval)
The Data flowchart shape indicates inputs to and outputs
Data
from a process. As such, the shape is more often referred
(I/O)
to as an I/O shape than a Data shape.
Pretty self-explanatory - the Document flowchart symbol
Document
is for a process step that produces a document.
Show a Process or action step. This is the most common
Process
symbol in flowcharts.
Indicates a question or branch in the process flow.
Decision Typically, a Decision flowchart shape is used when there
are 2 options (Yes/No, No/No-Go, etc.)
This symbol is typically small and is used as a Connector
to show a jump from one point in the process flow to
another. Connectors are usually labeled with capital letters
Connector (A, B, AA) to show matching jump points. They are handy
(Inspection) for avoiding flow lines that cross other shapes and flow
lines. They are also handy for jumping to and from a sub-
processes defined in a separate area than the main
flowchart.
Each control structures can be built from the basic elements as shown below.
Sequence: A sequence is a series of steps that take place one after another. Each step is
represented here by a new line.
Pseudocode Flowchart
BEGIN
Statement
Statement
END
Pseudocode Flowchart
BEGIN
1st Gear
2nd Gear
3rd Gear
4th Gear
5th Gear
END
Pseudocode Flowchart
IF (question) THEN
statement
ELSE
statement
ENDIF
Pseudocode Flowchart
IF (lights are green) THEN
Go
ELSE
Stop
ENDIF
Pseudocode Flowchart
CASEWHERE (question)
Alternative 1: Statement
Alternative 2 : Statement
OTHERWISE : Statement
ENDCASE
Pseudocode Flowchart
Green : Go
Amber : Slowdown
Red : Stop
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
repetitions.
Pre-test repetitions (sometimes called guarded loops) will perform the test before any part
of the loop occurs.
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.
Pseudocode Flowchart
WHILE (question)
Statement
ENDWHILE
Pseudocode Flowchart
wait
ENDWHILE
Pseudocode Flowchart
REPEAT
Statement
UNTIL (Question)
Pseudocode Flowchart
REPEAT
Wait
Pseudocode Flowchart
subprogram
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".
Pseudocode Flowchart
BEGIN
Start Car
Engage Gears
Navigate Car
Stop Car
END
Pseudocode Flowchart
BEGINSUBPROGRAM Navigate
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.
1.4 RECURSION
1.4.1 Example
So now we have another way of thinking about how to compute the value of n!, for all
nonnegative integers n:
When we're computing n! in this way, we call the first case, where we immediately know the
answer, the base case, and we call the second case, where we have to compute the same
function but on a different value, the recursive case.
Base case is the case for which the solution can be stated non‐recursively(ie. the answer is
known). Recursive case is the case for which thesolution is expressed in terms of a smaller
version ofitself.
1.4.2 Recursion in Step Form
Recursion may be described as follows:
Syntax for recursive algorithm
Step 1: Start
Step 2: Statement(s)
Step 3: Call Subprogram(argument)
Step 4: Statement(s)
Step 5: Stop
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n) and store the result in f
Begin
Subprogram subprogram(argument)
call(argument)
Return recursive
solution with
Subprogram No Is base
call(smaller Case
version of
argument)
Yes
End
Start Begin Factorial(N)
Subprogram
Read N yes
Is
N==1
Fact=Factorial(N)
No
Stop
End Factorial
END
The problem given should be understood completely. Check if it is similar to some standard
problems & if a Known algorithm exists. Otherwise a new algorithm has to be developed.
Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs. The solution is stated in two forms, exact solution or approximate
solution. Examples of problems where an exact solution cannot be obtained are i) Finding a
square root of number. ii) Solutions of nonlinear equations.
Some algorithms do not demand any ingenuity in representing their inputs. Some others are
in fact are predicted on ingenious data structures. A data type is a well-defined collection of
data with a well-defined set of operations on it. A data structure is an actual implementation
of a particular abstract data type. The Elementary Data Structures are Arrays: These let you
access lots of data fast. (good) .You can have arrays of any other data type. (good) .However,
you cannot make arrays bigger if your program decides it needs more space. (bad). Records:
These let you organize non-homogeneous data into logical packages to keep everything
together. (good) .These packages do not include operations, just data fields (bad, which is
why we need objects) .Records do not help you process distinct items in loops (bad, which is
why arrays of records are used) Sets: These let you represent subsets of a set with such
operations as intersection, union, and equivalence. (good) .Built-in sets are limited to a
certain small size. (bad, but we can build our own set data type out of arrays to solve this
problem if necessary)
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.
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
Analysing algorithms:
A user has a list of numbers and wishes to find the minimum value in the list.
An Algorithm is required which will allow the user to enter the numbers, and which will
calculate the minimum value that are input. The user is quite happy to enter a count of the
numbers in the list before entering the numbers.
Finding the minimum value in a list of items isn‘t difficult. Take the first
element and compare its value against the values of all other elements. Once we find a
smaller element we continue the comparisons with its value. Finally we find the minimum.
Step 1: Start
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]
Step 13: i=i-1
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
of guesses for linear search and binary search for a few number sizes:
Highest Number Max Linear Search Guesses Max Binary Search Guesses
10 10 4
100 100 7
1,000 1,000 10
Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Step 6: READ User Guessed Number as G
Step 7: Count = Count +1
Step 8: IF R==G THEN go to step 11 ELSE go to step 9
Step 9: IF R< G THEN PRINT ―Guess is Too High‖ AND go to step 6 ELSE go to step10
Step 10: IF R>G THEN PRINT ―Guess is Too Low‖ AND go to step 6
Step 11: PRINT Count as Number of Guesses Took
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‖
ELSEIF R>G THEN
DISPLAY ―Guess is Too Low‖
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took
Rules
Only one disk can be moved among the towers at any given time.
Only the "top" disk can be removed.
No large disk can sit over a small disk.
Figure 1.9Step 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.
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.
Python Mode
The last line is a prompt that indicates that the interpreter is ready for you to enter code.
If you type a line of code and hit Enter, the interpreter displays the result:
>>> 5 + 4
9
This prompt can be used as a calculator. To exit this mode type exit() or quit() and press
enter.
We can use any text editing software to write a Python script file.
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
highlighting and checking, file explorers etc. to the programmer for application development.
Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.
IDEL is a graphical user interface (GUI) that can be installed along with the Python
programming language and is available from the official website.
We can also use other commercial or free IDE according to our preference.PyScripter IDEis
one of the Open source IDE.
Type the following code in any text editor or an IDE and save it as helloWorld.py
print("Hello world!")
Now at the command window, go to the loaction of this file. You can use the cd command to
change directory.
To run the script, type, python helloWorld.py in the command window. We should be able to
see the output as follows:
Hello world!
If you are using PyScripter, there is a green arrow button on top. Press that button or
press Ctrl+F9 on your keyboard to run the program.
In this program we have used the built-in function print(), to print out a string to the
screen. String is the value inside the quotation marks, i.e. Hello world!.
In these results, the word ―class‖ is used in the sense of a category; a type is a
category ofvalues.Not surprisingly, integers belong to the type int, strings belong to str and
floating-pointnumbers belong to float.What about values like '5' and '83.0'? They look like
numbers, but they are in quotationmarks like strings.
>>>type('5')
<class 'str'>
>>>type('83.0')
<class 'str'>
They‘re strings.When you type a large integer, you might be tempted to use commas
between groups ofdigits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> 1,000,000
(1, 0, 0)
Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
2.2.1.2 Python Strings
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example –
Python Programming
P
g
tho
thon Programming
Python ProgrammingPython Programming
Python Programming Course
2.2.1.3 Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging to a
list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
>>>bool(1)
True
>>>bool(0)
False
Python's Booleans were added with the primary goal of making code clearer.
For example, if you're reading a function and encounter the statement return 1, you might
wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that
multiplies some other quantity. If the statement is return True, however, the meaning of the
return value is quite clear.
Python's Booleans were not added for the sake of strict type-checking. A very
strict language such as Pascal would also prevent you performing arithmetic with Booleans,
and would require that the expression in an if statement always evaluate to a Boolean result.
Python is not this strict and never will be. This means you can still use any expression in
an if statement, even ones that evaluate to a list or tuple or some random object. The Boolean
type is a subclass of the int class so that arithmetic using a Boolean still works.
>>> True + 1
2
>>> False + 1
1
>>> False * 85
We will discuss about data types like Tuple, Dictionary in Unit IV.
Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted value.
Function Description
2.3 VARIABLES
Programmers generally choose names for their variables that are meaningful
The Rules
The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
except in raise
>>>1book = 'python'
SyntaxError: invalid syntax
>>>more@ = 1000000
SyntaxError: invalid syntax
>>>class = 'Fundamentals of programming'
SyntaxError: invalid syntax
1book is illegal because it begins with a number. more@ is illegal because it
contains an illegal character, @. class is illegal because it is a keyword.
Good Variable Name
Choose meaningful name instead of short name. roll_no is better than rn.
Maintain the length of a variable name. Roll_no_of_a_student is too long?
Be consistent; roll_no or orRollNo
Begin a variable name with an underscore(_) character for a special case.
2.4 EXPRESSIONS AND STATEMENTS
An expression is a combination of values, variables, and operators. A value
all by itself is considered an expression, and so is a variable, so the following are all legal
expressions:
>>> 50
50
>>> 10<5
False
>>> 50+20
70
When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression.
>>> n = 25
>>>print(n)
The first line is an assignment statement that gives a value to n. The second
line is a print statement that displays the value of n. When you type a statement, the
interpreter executes it, which means that it does whatever the statement says. In general,
statements don‘t have values.
Operators are special symbols in Python that carry out computation. The value
that the operator operates on is called the operand.
For example:
>>>10+5
15
Here, + is the operator that performs addition. 10 and 5 are the operands and 15 is the output
of the operation. Python has a number of operators which are classified below.
Arithmetic operators
Comparison (Relational) operators
Logical (Boolean) operators
Bitwise operators
Assignment operators
Special operators
Example
x=7
y=3
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x % y =',x%y)
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 10
x-y=4
x * y = 21
x / y = 2.3333333333333335
x // y = 2
x%y=1
x ** y = 343
2.5.2 Comparison or Relational Operators
Comparison operators are used to compare values. It either
returns True or False according to the condition.
Example
x=5
y=7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
When you run the program, the output will be:
x >y is False
x <y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
2.5.3 Logical Operators
Example
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
When you run the program, the output will be:
x and y is False
x or y is True
not x is False
In Table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Example
x=10
y=4
print('x& y=',x& y)
print('x | y=',x | y)
print('~x=',~x)
print('x ^ y=',x ^ y)
print('x>> 2=',x>> 2)
print('x<< 2=',x<< 2)
When you run the program, the output will be:
x& y= 0
x | y= 14
~x= -11
x ^ y= 14
x>> 2= 2
x<< 2= 40
2.5.5 Assignment Operators
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.
Python language offers some special type of operators like the identity
operator or the membership operator. They are described below with examples.
Example
x1 = 7
y1 = 7
x2 = 'Welcome'
y2 = 'Welcome'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
When you run the program, the output will be:
False
Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).But x3 and y3 are list. They are
equal but not identical. Since list are mutable (can be changed), interpreter locates them
separately in memory although they are equal.
in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).
Example
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
When you run the program, the output will be:
False
True
False
Here, ' Program ' is in x but ' program' is not present in x, since Python is case
sensitive.
2.6 PRECEDENCE OF PYTHON OPERATORS
The combination of values, variables, operators and function calls is termed as
an expression. Python interpreter can evaluate a valid expression. When an expression
contains more than one operator, the order of evaluation dependson the Precedence of
operations.
>>> 20 – 5*3
5
But we can change this order using parentheses () as it has higher precedence.
>>> (20 - 5) *3
45
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
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.
>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
We can see that 10 * 7 // 3is equivalent to (10 * 7)//3.
>>> 5 ** 2 ** 3
390625
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.
2.9 COMMENTS
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
2.9.1 Docstring in Python
def area(r):
"""Compute the area of Circle"""
return 3.14159*r**2
2.10.1 Functions
In the context of programming, a function is a named sequence of statements
that performs a computation. When you define a function, you specify the name and the
sequence of statements. Later, you can ―call‖ the function by name. Functions help break our
program into smaller and modular chunks. As our program grows larger and larger, functions
make it more organized and manageable. Furthermore, it avoids repetition and makes code
reusable.
Functions
Note that:
>>>range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>range(5,10)
[5, 6, 7, 8, 9]
>>>range(10,1,-2)
[10, 8, 6, 4, 2]
>>> x=10
>>> y=7
>>>print('The sum of', x, 'plus', y, 'is', x+y)
The sum of 10 plus 7 is 17
You can also use it with no parameters:
print()
>>> x=10
>>> y=7
>>>print'The sum of', x, 'plus', y, 'is', x+y
The sum of 10 plus 7 is 17
Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −
raw_input
input
Example of a function
def welcome(person_name):
"""This function welcome
the person passed in as
parameter"""
print(" Welcome " , person_name , " to Python Function Section")
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
defabsolute_value(num):
"""This function returns the absolute
value of the entered number"""
ifnum>= 0:
returnnum
else:
return -num
print(absolute_value(5))
print(absolute_value(-7))
def welcome(person_name):
print(" Welcome " , person_name , " to Python Function Section")
This function assigns the argument to a parameter named person_name. When
the function is called, it prints the value of the parameter (whatever it is). This function works
with any value that can be printed.
>>>welcome("Vinu")
Welcome Vinu to Python Function Section
>>>welcome(100)
Welcome 100 to Python Function Section
>>>welcome(50.23)
Welcome 50.23 to Python Function Section
The argument is evaluated before the function is called, so in the below
examples the expressions 'vinu'*3 is evaluated.
>>>welcome('vinu'*3)
Welcome vinuvinuvinu to Python Function Section
>>>student_name='Ranjith'
>>>welcome(student_name)
Welcome Ranjith to Python Function Section
2.10.4 Modules
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use. A module is a file
that contains a collection of related functions. Python has lot of built-in modules; math
module is one of them. math module provides most of the familiar mathematical functions.
Before we can use the functions in a module, we have to import it with an
import statement:
pow(...)
pow(x, y[, z]) -> number
Programs that will be imported as modules often use the following idiom:
if __name__ == '__main__':
add(10,20)
__name__ is a built-in variable that is set when the program starts. If the
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
addModule.py file as given below.
def add(a, b):
result = a + b
print(result)
if __name__ == '__main__':
add(10,20)
Now while importing addModule test case is not running
>>> import addModule
__name__ has module name as its value when it is imported. Warning: If you
import a module that has already been imported, Python does nothing. It does not re-read the
file, even if it has changed. If you want to reload a module, you can use the built-in function
reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import
the module again.
We can do the same swapping operation even without the use of third variable,
There are number of ways to do this, they are.
In this method inthe above programinstead of line number 3,4,5 use a single
tuple assignment statement
var1 , var2 = var2 , var1
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
evaluated before any of the assignments.
If the variables are both numbers, Swapping can be performed using simple
mathematical addition subtraction relationship or multiplication division relationship.
In this method inthe above program instead of line number 3,4,5 use the following
code
x=x+y
y=x-y
x=x-y
Multiplication and Division
In this method inthe above program instead of line number 3,4,5 use the following
code
x=x*y
y=x/y
x=x/y
2.11.1.2.3 Using Bitwise operators
If the variables are integers then we can perform swapping with the help of bitwise
XOR operator. In order to do this in the above program instead of line number 3,4,5 use the
following code
1 2 3 4 5 6 7
Figure 2.4.aExample List
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
as nth element to end element + beginning element to n-1th element. Suppose n=2 means,
given list is rotated 2 positions towards left side as given in Figure 2.4.b
3 4 5 6 7 1 2
Figure 2.4.b Left Circulated List
6 7 1 2 3 4 5
Figure 2.4.c Right Circulated List
>>>circulate([1,2,3,4,5,6,7], 2)
[3, 4, 5, 6, 7, 1, 2]
>>>circulate([1,2,3,4,5,6,7], -2)
[6, 7, 1, 2, 3, 4, 5]
>>> 9 == 9
True
>>> 9 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>>type(True)
<class 'bool'>
>>>type(False)
<class 'bool'>
Boolean expression can have relational operators or logical operators.The ==
operator is one of the relational operators; the others are:
x==y #x is equal to y
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
More explanation can found in 2.5.2.Although these operations are probably
familiar to you, the Python symbols are different from the mathematical symbols. A common
error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is
an assignment operator and == is a relational operator. There is no such thing as =< or =>.
For example:
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the
number is divisible by 2 or 3.
not operator negates a boolean expression, so not (x > y) is true if x > y is false, that
is, if x is less than or equal to y.
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.
if statement
The elif Statement
if...elif...else
Nested if statements
Here, the program evaluates the TEST EXPRESSION and will execute
statement(s) only if the text expression is True.If the text expression is False, the statement(s)
is not executed.
1. The colon (:) is significant and required. It separates the header of the compound
statement from the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.
3. All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION is true.
4. Python interprets non-zero values as True. None and 0 are interpreted as False.
Here is an example:
mark = 102
if mark >= 100:
print(mark, " is a Not a valid mark.")
print("This is always printed.")
if x < 0:
pass # TODO: need to handle negative values!
3.2.2 Alternative execution
A second form of the if statement is ―alternative execution‖, in which there are
two possibilities and the condition determines which one runs. In other words ,It is frequently
the case that you want one thing to happen when a condition it true, and something else to
happen when it is false. For that we have if else statement. The syntax looks like this:
General Syntax of if ..elsestatement is
if TEST EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Eligible to vote
In the above example, when age is greater than 18, the test expression is true
and body of if is executed and body of else is skipped.If age is less than 18, the test
expression is false and body of else is executed and body of if is skipped.If age is equal to 18,
the test expression is true and body of if is executed and body of else is skipped.
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.
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")
When variable time is less than 12, Good Morning is printed.If time is less
than 15, Good Afternoon is printed.If time is less than 20, Good Evening is printed. If all
above conditions fails Good Night is printed.
One conditional can also be nested within another. ie, We can have
a if...elif...else statement inside another if...elif...else statement. This is called nesting in
computer programming.
if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
The outer conditional contains two branches. Those two branches contain
another if… else statement, which has two branches of its own. Those two branches could
contain conditional statements as well.
Here is an example:
a=10
b=20
c=5
if a>b:
if a>c:
print("Greatest number is ",a)
else:
As we saw back in the variable section, it is legal to make more than one
assignment to the same variable. A new assignment makes an existing variable refer to a new
value (and stop referring to the old value).
age = 26
print(age)
age = 17
print(age)
The output of this program is
26
17
because the first time age is printed, its value is 26, and the second time, its
value is 17.
Here is what reassignment looks like in a state snapshot:
26
age 17
Updating variables
The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.We generally use this loop when we don't know
beforehand, the number of times to iterate.
In while loop, test expression is checked first. The body of the loop is entered
only if the TEST_EXPRESSION evaluates to True. After one iteration, the test expression is
checked again. This process continues until the TEST_EXPRESSION evaluates to False.
Python interprets any non-zero value as True. None and 0 are interpreted
as False.
Example:
Python program to find sum of first n numbers using while loop
n = 20
sum = 0 # initialize sum and counter
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum) # print the sum
When you run the program, the output will be:
The sum is 210
In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (20 in our program).
We need to increase the value of counter variable in the body of the loop. This
is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never
ending loop).Finally the result is displayed.
Here, LOOP_VARIABLE is the variable that takes the value of the item
inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
Example
marks = [95,98,89,93,86]
total = 0
forsubject_mark in marks:
total = total+subject_mark
print("Total Mark is ", total)
when you run the program, the output will be:
Total Mark is 461
We can use the range() function in for loops to iterate through a sequence of
numbers.
Example:
sum=0
for i in range(20):
sum=sum+i
Sum is 190
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
whilevar> 0:
print('Current variable value :', var)
var = var -1
ifvar == 5:
break
print "End!"
counter = 0
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times.On
the forth iteration, the condition in while becomes False. Hence, the else part is executed.
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.break statement can be used to stop a for loop. In such
case, the else part is ignored.Hence, a for loop's else part runs if no break occurs.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints
Syntax of pass
Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
Example
sequence = {'p', 'a', 's', 's'}
forval in sequence:
pass
We can do the same thing in an empty function
def function(args):
pass
You must have a clear solution to the problem, and must know what should happen
before you can debug a program. Work on solving the problem on a piece of paper
(perhaps using a flowchart to record the steps you take) before you concern yourself
with writing code. Writing a program doesn‘t solve the problem — it
simply automates the manual steps you would take. So first make sure you have a pen-
and-paper manual solution that works. Programming then is about making those manual
steps happen automatically.
Do not write chatterbox functions. A chatterbox is a fruitful function that, in addition
to its primary task, also asks the user for input, or prints output, when it would be more
useful if it simply shut up and did its work quietly.
For example, we‘ve seen built-in functions like range, max and abs. None of
these would be useful building blocks for other programs if they prompted the user for input, or
printed their results while they performed their tasks.
As an example, we‘ll write a function that takes two points, the center of the
circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the
distance between the two points. Fortunately, we‘ve just written a function, distance, that does
just that, so now all we have to do is use it:
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it.
Again we will use one of our earlier functions:
result = area(radius)
return result
Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
Although there are various unique namespaces defined, we may not be able to
access all of them from every part of the program. The concept of scope comes into play.
Scope is the portion of the program from where a namespace can be accessed
directly without any prefix.
When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.
If there is a function inside another function, a new scope is nested inside the local scope.
Example
defouter_function():
b = ―India‖
definner_func():
c = ―TamilNadu‖
a = ―World‖
defouter_function():
a ="i am in India"
definner_function():
a = "i am in TamilNadu"
print('a =',a)
inner_function()
print('a =',a)
a = "i am in World"
outer_function()
print('a =',a)
a = i am in TamilNadu
a = i am in India
a = i am in World
defouter_function():
global a
a = "i am in India"
definner_function():
global a
a = "i am in TamilNadu"
print('a =',a)
inner_function()
print('a =',a)
a = "i am in World"
outer_function()
print('a =',a)
The output of the program is.
a = i am in TamilNadu
a = i am in TamilNadu
a = i am in TamilNadu
Here, all reference and assignment are to the global a due to the use of keyword global.
3.6 RECURSION
A recursive function is a function which calls itself with "smaller (or simpler)"
input values. Generally if a problem can be solved utilizing solutions to smaller versions of
For Example:
In the above example, base case for n == 1 is defined and larger value of
number can be solved by converting to smaller one till base case is reached.
Python program to find factorial of a given number using recursive function is.
def factorial(n):
if n == 1:
return 1
else:
return (n * factorial(n-1))
num = 5
print("The factorial of", num, "is", factorial(num))
Our recursion ends when the number reduces to 1. This is called the base condition.Every
recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely
Advantages of recursion
Disadvantages of recursion
3.7 STRINGS
A string is a sequence of characters. You can access the characters one at a
time with the bracket operator:
>>>subject = 'python'
>>>letter = subject [1]
The second statement selects character number 1 from fruit and assigns it to
letter. The expression in brackets is called an index. The index indicates which character in
the sequence you want. But you might not get what you expect:
>>>letter
'y'
For most people, the first letter of 'python' is p, not y. But for computer
scientists, the index is an offset from the beginning of the string, and the offset of the first
letter is zero.
>>>letter = subject [0]
>>>letter
3.7.1 len()
len is a built-in function that returns the number of characters in a string:
>>>subject = 'python'
>>>len(subject)
6
To get the last letter of a string, you might be tempted to try something like this:
>>>length = len(subject)
>>>last = subject [length]
IndexError: string index out of range
The reason for the IndexError is that there is no letter in 'python' with the
index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last
character, you have to subtract 1 from length:
>>>last = subject [length-1]
>>>last
't'
Or you can use negative indices, which count backward from the end of the
string. The expression subject [-1] yields the last letter, subject [-2] yields the second to last,
and so on.
Each time through the loop, the next character in the string is assigned to the
variable letter. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a
for loop to generate an abecedarian series (that is, in alphabetical order). In Robert
McCloskey‘s book MakeWay for Ducklings, the names of the ducklings are Jack, Kack,
Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print(letter + suffix)
The output is:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
3.7.3 String Slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
>>> s = 'Monty Python'
>>>s[0:5]
'Monty'
>>>s[6:12]
'Python'
The operator [n:m] returns the part of the string from the ―n-eth‖ character to
the ―m-eth‖ character, including the first but excluding the last. This behavior is
counterintuitive, but it might help to imagine the indices pointing between the characters, as
in Figure 3.8. If you omit the first index (before the colon), the slice starts at the beginning of
the string. If you omit the second index, the slice goes to the end of the string:
>>>subject = 'python'
>>>subject[:3]
. 'pyt'
>>>subject[3:]
'hon'
If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>>subject = 'python'
>>>subject[3:3]
''
>>>subject = 'python'
>>>subject[:]
python
3.7.4 Strings are Immutable
It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string. For example:
>>> greeting = 'Hello, world!'
>>>greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means you can‘t
change an existing string. The best you can do is create a new string that is a variation on the
original:
>>> greeting = 'Hello, world!'
>>>new_greeting = 'J' + greeting[1:]
>>>new_greeting
'Jello, world!'
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
18. upper( )
The method upper takes a string and returns a new string with all uppercase letters.
Instead of the function syntax upper(word), it uses the method syntax word.upper().
>>>word = 'python'
>>>new_word = word.upper()
>>>new_word
'PYTHON
19. find(obj)
It will display the lower index where the value is found otherwise return -1
>>>word = 'python'
>>>index = word.find('t')
>>>index
2
>>>in_both('django','mongodb')
d
n
g
o
3.7.7 String Comparison
The relational operators work on strings. To see if two strings are equal:
if word == 'python':
print('All right, python.')
Other relational operations are useful for putting words in alphabetical order:
if word < ' python ':
print('Your word, ' + word + ', comes before python.')
elif word > ' python ':
print('Your word, ' + word + ', comes after python.')
else:
print('All right, python.')
Python does not handle uppercase and lowercase letters the same way people
do. All the uppercase letters come before all the lowercase letters, so:
Your word, Python, comes before c language
A common way to address this problem is to convert strings to a standard
format, such as all lowercase, before performing the comparison.
3.8 LISTS AS ARRAYS
Most of programs work not only with variables. They also use lists of
variables. For example, a program can handle an information about students in a class by
reading the list of students from the keyboard or from a file. A change in the number of
students in the class must not require modification of the program source code.
To store such data, in Python you can use the data structure called list (in most
programming languages the different term is used — ―array‖).
The list can be set manually by enumerating of the elements the list in square
brackets, like here:
Primes = [2, 3, 5, 7, 11, 13]
Rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
Like the characters in the string, the list elements can also have negative
index, for example, Primes[-1] == 13,Primes[-6] == 2. The negative index means we start at
the last element and go left when reading a list.
Unlike strings, the elements of a list are changeable; they can be changed by
assigning them new values.
Consider several ways of creating and reading lists. First of all, you can create
an empty list (the list with no items, its length is 0), and you can add items to the end of your
list using append. For example, suppose the program receives the number of elements in the
list n, and then n elements of the list one by one each at the separate line. Here is an example
of input data in this format:
a = [] # start an empty list
n = int(input('Enter No of Elements')) # read number of element in the list
for i in range(n):
new_element = int(input('Enter Element :')) # read next element
a.append(new_element) # add it to the list
# the last two lines could be replaced by
one:
# a.append(int(input('Enter Element :')))
print(a)
Output will be
Enter No of Elements5
Enter Element :2
Enter Element :7
Enter Element :4
Enter Element :3
Enter Element :8
[2, 7, 4, 3, 8]
In the demonstrated example the empty list is created, then the number of
elements is read, then you read the list items line by line and append to the end. The same
thing can be done, saving the variable n:
Output will be
Enter No of Elements :3
Enter Element : 2
Enter Element : 4
Enter Element : 3
[2, 4, 3]
You can print elements of a list a with print(a); this displays the list items
surrounded by square brackets and separated by commands. In general, this is inconvenient;
in common, you are about to print all the elements in one line or one item per line. Here are
two examples of that, using other forms of loop:
a = [1, 2, 3, 4, 5]
for i in range(len(a)):
print(a[i])
This algorithm is based on the fact that GCD of two numbers divides their
difference as well. In this algorithm, we divide the greater by smaller and take the remainder.
Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the GCD of 108 and 30, we divide 108 by 30.
The remainder is 18. Now, we divide 30 by 18 and the remainder is 12. Now, we divide 18
by 12 and the remainder is 6. Now, we divide 12 by 6 and the remainder is 0. Hence, 6 is the
required GCD.
defcomputeGCD(x, y):
while(y):F
x, y = y, x % y #can also be written as follows
return x #reminder=x%y
# x=y
#y=reminder
a=108
b=30
print('GCD of ',a ,' and ' , b, ' is ',computeGCD(a,b))
3.9.3 Exponentiation
Simplest way to find the exponentiation of a number xy in python is, the use of ** operator
>>> 4**3
64
Another way to find the exponentiation of a number x y in python is, the use of
pow() function that is available in math module. eg
>>> import math
>>>math.pow(4,3)
64.0
We can also write our own function to find the exponentiation of a number x y using looping
statement.
defmy_pow(x,y):
powered = x
if y == 0:
powered=1
else:
while y > 1:
powered *= x
y -= 1
Iterative Summation:
deflistsum(numList):
Sum = 0
for i in numList:
Sum = Sum + i
return Sum
my_list=[1,3,5,7,9]
print(listsum(my_list))
Output will be:
25
Pretend for a minute that you do not have while loops or for loops. How would
you compute the sum of a list of numbers? If you were a mathematician you might start by
recalling that addition is a function that is defined for two parameters, a pair of numbers. To
redefine the problem from adding a list to adding pairs of numbers, we could rewrite the list
as a fully parenthesized expression. Such an expression looks like this:
((((1+3)+5)+7)+9)
We can also parenthesize the expression the other way around,
(1+(3+(5+(7+9))))
Notice that the innermost set of parentheses, (7+9), is a problem that we can solve without a
loop or any special constructs. In fact, we can use the following sequence of simplifications
to compute a final sum.
total= (1+(3+(5+(7+9))))
total= (1+(3+(5+16)))
total= (1+(3+21))
total= (1+24)
total= 25
How can we take this idea and turn it into a Python program? First, let‘s
restate the sum problem in terms of Python lists. We might say the sum of the list numList is
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
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
[] # empty list
[1, 2, 3] # 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], []
2 'computer'
mark 0 98
1 87
2 94
100
empty
Figure 4.1 shows the state diagram for the lists subject, mark, and empty. 2nd
element of mark,which used to be 94, is now 100
physics
chemistry
computer
>>> t1.extend(t2)
>>> t1
>>>aList.index(123)
1
5. list.insert(index, obj)
>>>aList
>>>aList.pop()
'abc'
>>>aList.pop(2)
'zara'
>>>aList
[123, 'xyz']
7. list.remove(obj)
>>>aList.remove('xyz')
>>>aList
>>>aList.reverse()
>>>aList
9. list.sort([func])
>>>t.sort()
>>> t
10. list.pop(obj)
pop modifies the list and returns the element that was removed.
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>>t
['a', 'c']
>>>x
'b'
11. list.remove(obj)
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
>>>t.remove('b')
>>>t
['a', 'c']
12. list.append(obj)
The append method add the object at the end of a list.
>>> t1 = [10, 20]
>>> t2 = t1.append(30)
>>> t1
[10, 20, 30]
>>> t2
None
one 0 10
1 20
two 2 30
But the problem is if the list is a nested one this method won‘t work.
Example
a = [81, 82, [83,84]]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[2][0] = 5
print(a)
print(b)
Output will be:
True
False
[81, 82, [5, 84]]
[81, 82, [5, 84]]
Change in list b affect list a. In order to overcome this issue python provide a module called
copy. This module provides generic shallow and deep copy operations.
Interface summary:
copy.copy(x)
Return a shallow copy of x.
copy.deepcopy(x)
Return a deep copy of x.
A shallow copy constructs a new compound object and then (to the extent possible)
inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively,
inserts copies into it of the objects found in the original.
import copy
a = [81, 82, [83,84]]
b = copy.copy(a) # make a clone using shallow copy()
print(a == b)
print(a is b)
b[1]=10
b[2][0] = 5
print(a)
print(b)
Output will be:
True
False
[81, 82, [5, 84]]
[81, 10, [5, 84]]
import copy
a = [81, 82, [83,84]]
b = copy.deepcopy(a) # make a clone using deepcopy()
print(a == b)
print(a is b)
b[1]=10
b[2][0] = 5
print(a)
print(b)
Output will be:
True
False
[81, 82, [83, 84]]
[81, 10, [5, 84]]
We can notice the difference between shallow copy and deep copy from the
above examples. In shallow copy method change made in nested list b affect list a also it is
same as copying using slice operator. But in deep copy method changes made in nested list b
does not affect list a.
When you pass a list to a function, the function gets a reference to the list. If
the function modifies the list, the caller sees the change. For example, delete_head removes
the first element from a list:
defdelete_head(t):
del t[0]
Here‘s how it is used:
>>>letters = ['x', 'y', 'z']
>>>delete_head(letters)
>>>letters
['y', 'z']
The parameter t and the variable letters are aliases for the same object. It is
important to distinguish between operations that modify lists and operations that create new
lists. For example, the append method modifies a list, but the + operator creates a new list.
Here‘s an example using append:
>>> t1 = [10, 20]
>>> t2 = t1.append(30)
>>> t1
[10, 20, 30]
>>> t2
None
The return value from append is None.
Here‘s an example using the + operator:
>>> t3 = t1 + [40]
>>> t1
[10, 20, 30]
>>> t3
[10, 20, 30, 40]
The result of the operator is a new list, and the original list is unchanged. This
difference is important when you write functions that are supposed to modify lists. For
example, this function does not delete the head of a list:
defbad_delete_head(t):
t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes t refer to it, but
that doesn‘taffect the caller.
>>> t4 = [10, 20, 30]
>>>bad_delete_head(t4)
>>> t4
[10, 20, 30]
At the beginning of bad_delete_head, t and t4 refer to the same list. At the end,
t refers to a new list, but t4 still refers to the original, unmodified list.An alternative is to
write a function that creates and returns a new list. For example, tail returns all except first
element of a list:
def tail(t):
4.2 TUPLES
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
4.2.1 Creating Tuples
Similar to List, Tuple is a sequence of values. The values can be any type, and
they are indexed by integers. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>>message= 'h','a','i'
>>>type(message)
<type 'tuple'>
Although it is not necessary, it is common to enclose tuples in parentheses:
>>>message= ('h','a','i')
>>>type(message)
<type 'tuple'>
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>>type(t1)
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>>type(t2)
<class 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates
an empty tuple:
>>> t = tuple()
>>>t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
>>>course=tuple('python')
>>>course
('p', 'y', 't', 'h', 'o', 'n')
Because tuple is the name of a built-in function, you should avoid using it as a variable
name.Most list operators also work on tuples. The square bracket operator indexes an
element:
>>>course = ('p', 'y', 't', 'h', 'o', 'n')
>>>cource[0]
>>>defdisplayall(*args):
print(args)
The gather parameter can have any name you like, but args is conventional.
Here‘s how the function works:
>>>displayall('python',355.50,3)
('python', 355.5, 3)
('h', 0)
('a', 1)
('i', 2)
A zip object is a kind of iterator, which is any object that iterates through a
sequence. Iterators are similar to lists in some ways, but unlike lists, you can‘t use an index to
select an element from an iterator.
If you want to use list operators and methods, you can use a zip object to make a list:
>>>list(zip(s, t))
[('h', 0), ('a', 1), ('i', 2)]
The result is a list of tuples; in this example, each tuple contains a character
from the string and the corresponding element from the list.
If the sequences are not the same length, the result has the length of the shorter one.
>>>list(zip('Vinu', 'Ranjith'))
[('V', 'R'), ('i', 'a'), ('n', 'n'), ('u', 'j')]
You can use tuple assignment in a for loop to traverse a list of tuples:
>>> t=[('h',0),('a',1),('i',2)]
>>>forletter,number in t:
print(number,letter)
(0, 'h')
(1, 'a')
(2, 'i')
Each time through the loop, Python selects the next tuple in the list and
assigns the elements to letter and number.
>>> t.index(9)
1
2. t.count(value)
Return the total number of occurrences of value
>>> t=(1,9)
>>> t.count(9)
1
3. sorted( )
This function sorts the elements of the tuple and returns the sorted element in the form of list.
>>> a=(2,4,1)
>>> sorted(a)
[1, 2, 4]
4. len( )
Return the length of the tuple
>>> t=(1,9)
>>> len(t)
2
5. max( )
Return the maximum element of the tuple.
>>> t=(1,9)
>>> max(t)
>>> min(t)
1
7. sum( )
Return the sum of elements in the tuple.
>>>a=[1, 2, 4]
>>> sum(a)
7
8. del()
Delete the entire tuple
>>> del t
>>> d
4.3 DICTIONARIES
Dictionaries are one of Python‘s best features; they are the building blocks of
many efficient and elegant algorithms.
4.3.1 A Dictionary is a Mapping
A dictionary is like a list, but more general. In a list, the indices have to be
integers; in a dictionary they can be (almost) any type.
A dictionary contains a collection of indices, which are called keys, and a
collection of values. Each key is associated with a single value. The association of a key and
a value is called a key-value pair or sometimes an item.
The in operator uses different algorithms for lists and dictionaries. For lists, it
searches theelements of the list in order. As the list gets longer, the search time gets longer in
direct proportion.For dictionaries, Python uses an algorithm called a hashtable that has a
remarkable property: the in operator takes about the same amount of time no matter how
many items are in the dictionary.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
('a', 1)
('g', 2)
('i', 1)
('m', 2)
('n', 1)
('o', 1)
('p', 1)
('r', 2)
defreverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raiseLookupError()
This function is yet another example of the search pattern, but it uses a feature
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
failed.
The effect when you raise an exception is the same as when Python raises one:
it prints atraceback and an error message. The raise statement can take a detailed error
message as an optional argument. For example:
>>> raise LookupError('value does not appear in the dictionary')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
LookupError: value does not appear in the dictionary
A reverse lookup is much slower than a forward lookup; if you have to do it
often, or if the dictionary gets big, the performance of your program will suffer.
Lists can appear as values in a dictionary. For example, if you are given a
dictionary that maps from letters to frequencies, you might want to invert it; that is, create a
dictionary that maps from frequencies to letters. Since there might be several letters with the
same frequency, each value in the inverted dictionary should be a list of letters. Here is a
function that inverts a dictionary:
definvert_dict(d):
inverse = dict()
for key in d:
val = d[key]
ifval not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
Each time through the loop, key gets a key from d and val gets the
corresponding value. If val is not in inverse, that means we haven‘t seen it before, so we
create a new item and initialize it with a singleton (a list that contains a single element).
Otherwise we have seen this value before, so we append the corresponding key to the list.
Here is an example:
>>> d2={'a':'How','b':'are','c':'you'}
>>> d1
{'a': 'How', 1: 'A', 2: 'p', 3: 'p', 4: 'l', 5: 'e', 'c': 'you', 'b': 'are'}
7. d.values()
Return a list of values in dictionary d
>>>d1={1:'A',2:'p',3:'p',4:'l',5:'e'}
>>> d1.values()
['How', 'A', 'p', 'p', 'l', 'e', 'you', 'are']
8. popitem( )
Remove a random key-value from the dictionary.
>>> d={1: 'a', 3: 'p', 4: 'l', 5: 'e'}
>>> d.popitem()
(1, 'a')
9. pop( )
Remove the key-value pair from the dictionary and return the removed value.
>>>d={1:'a',2:'p', 3:'p',4:'l',5:'e'}
>>>d.pop(2)
'p'
10. d.clear()
Remove all items from dictionary d
>>> d1.clear()
>>> d1
{}
4.4.1 Sorting
It is an operation in which all the elements of a list are arranged in a
predetermined order. The elements can be arranged in a sequence from smallest to largest
such that every element is less than or equal to its next neighbour in the list. Such an
arrangement is called ascending order. Assuming an array or List containing N elements, the
ascending order can be defined by the following relation:
It has been estimated that in a data processing environment, 25 per cent of the
time is consumed in sorting of data. Many sorting algorithms have been developed. Some of
the most popular sorting algorithms that can be applied to arrays are in-place sort algorithm.
An in-place algorithm is generally a comparison- based algorithm that stores the sorted
elements of the list in the same array as occupied by the original one. A detailed discussion
on sorting algorithms is given in subsequent sections.
Now the smallest is searched in the unsorted part of the list, i.e., ‗2‘ and
exchange with the element at the head of unsorted part, i.e., ‗20‘ as shown in Figure 4.4.
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.
data = []
print('Selection 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(0,n-1):
small=int(data[i])
pos=i
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']
Given a list of numbers, it divides the list into two part – sorted part and
unsorted part. The first element becomes the sorted part and the rest of the list becomes the
unsorted part as Shown in Figure 4.6. It picks up one element from the front of the unsorted
part as shown in Figure 4.6. It picks up one element from the front of the unsorted part and
inserts it in proper position in the sorted part of the list. The insertion action is repeated till
the unsorted part is exhausted.
Step
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.
2. Insert the element, from unsorted part, into the created space.
This algorithm for the insertion sort is given below. In this algorithm, the elements of
a list stored in an array called List[] are sorted in an ascending order. The algorithm uses two
loops – the outer For loop and inner while loop. The inner while loop shifts the elements of
the sorted part by one step to right so that proper place for incoming element is created. The
outer For loop inserts the element from unsorted part into the created place and moves to next
element of the unsorted part.
Algorithm insertSort()
1.1 Temp = List[I] #Save the element from unsorted part into temp
1.2 J = I-1
1.3 While(Temp < = List[J] AND J >=0)
1.3.2 J = J-I
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:
data[j+1]=data[j]
j=j-1
data[j+1]=temp
print(data)
print('Sorted Array is:')
print(data)
Output
Insertion Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :3
Enter the Element 2 :5
Enter the Element 3 :2
Enter the Element 4 :8
Enter the Element 5 :1
Original Array :
['3', '5', '2', '8', '1']
Intermediate Steps :
['3', '5', '2', '8', '1']
['2', '3', '5', '8', '1']
['2', '3', '5', '8', '1']
['1', '2', '3', '5', '8']
Sorted Array is:
['1', '2', '3', '5', '8']
If a list is empty or it contains only one element, then the list is already sorted. A list
that contains only one element is also called singleton.
In fact, this algorithm divides a given list into two almost equal sub-lists. Each
sub-list, thus obtained, is recursively divided into further two sub-lists and so on till
singletons or empty lists are left as shown in Figure 4.7.
Since the singleton and empty list are inherently sorted, the only step left is to
merge the singletons into sub-lists containing two elements each (see figure 4.7) which are
further merged into sub-lists containing four elements each and so on. This merging operation
is recursively carried out till a final merged list is obtained as shown in figure 4.8.
Merging of lists It is an operation in which two ordered lists are merged into a single
ordered list. The merging of two lists PAR1 and PAR2 can be done by examining the
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
given the figure 4.9. Let Ptr1, Ptr2, and Ptr3 variables point to the first locations of lists
PAR1, PAR2 and PAR3, respectively. The comparison of PAR1[Ptr1] and PAR2[Ptr2]
shows that the element of PAER1 (i.e., ‗2‘) is smaller. Thus, this element will be placed in
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.
4.1.3 ptr3++
4.2 else
4.2.1 mergeList[ptr3] = List[ptr2] #element from second list is taken
4.2.2 ptr2++ #move to next element in the list
4.2.3 ptr3++
5. while(ptr1 < mid) #copy remaining first list
5.1 mergeList [ptr3] = List[ptr1]
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
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
two given sorted lists into a third list, which is also sorted. The mergeSort algorithm takes a
list and stores into an array called List[]. It uses two variables lb and ub to keep track of lower
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
through merge algorithm to produce final sorted list.
Algorithm mergeSort (List, lb, ub)
1. if (lb<ub)
2. Stop
defmergeSort(alist):
print("Splitting ",alist)
iflen(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
Output
Merge Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :4
Enter the Element 2 :8
Enter the Element 3 :2
Enter the Element 4 :9
Enter the Element 5 :1
Original Array :
['4', '8', '2', '9', '1']
Intermediate Steps :
('Splitting ', ['4', '8', '2', '9', '1'])
('Splitting ', ['4', '8'])
('Splitting ', ['4'])
('Merging ', ['4'])
('Splitting ', ['8'])
('Merging ', ['8'])
1. i = lb
2. j=ub
3. while(i<=j)
data = []
print('Quick 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))
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']
Other programs are persistent: they run for a long time (or all the time); they keep at least
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.
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.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
of the file. If the file does not exists, raises I/O error. This is also the default mode in
which file is opened.
5.1.3Opening a File
It is done using the open() function. No module is required to be imported for
this function.
Syntax:
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full
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
string to be treated as special character. For example, if there is \temp in the file address, then
\t is treated as the tab character and error is raised of invalid address. The r makes the string
raw, that is, it tells that the string is without any special characters. The r can be ignored if the
file is in same directory and address is not being placed.
Example:
>>> f1 = open("sample.txt","a")
>>> f2 = open(r"G:\class\python\sample3.txt","w+")
If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position and if it is set to 2
then the end of the file would be taken as the reference position. If the second argument is
omitted, it also means use the beginning of the file as the reference position.
Example:
>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.tell()
0L
>>>f1.readline()
'Read Only\n'
>>>f1.tell()
11L
>>>f1.seek(0)
>>>f1.tell()
0L
>>>f1.seek(5)
>>>f1.tell()
5L
>>>f1.readline()
'Only\n'
>>> f4=open("fruit.txt","w")
>>>fruit_list=['Apple\n','Orange\n','Pineapple\n']
File_object.softspace Returns false if space explicitly required with print, true otherwise.
Example 1
Consider the following script command_line.py
import sys
print 'There are %d arguments'%len(sys.argv)
print 'Argument are', str(sys.argv)
print 'File Name is: ', sys.argv[0]
Now run above script as follows – in Command prompt:
C:\Python27>python.exe command_line.py vinuranjith
This produce following result –
There are 3 arguments
Argument are ['command_line.py', 'vinu', 'ranjith']
File Name is: command_line.py
NOTE: As mentioned above, first argument is always script name and it is also being
counted in number of arguments. Here ‗vinu‘ and ‗ranjith‘ are extra inputs passed to
program through command line argument method while running python program
command_line.py.
1) Open file name with command line argument one as read mode (input file).
2) Open file name with command line argument two as write mode (output file).
3) Read each line from the input file and write it into the output file until the input file
data getsover.
4) Exit.
Program
import sys
source=open(sys.argv[1],'r')
destination=open(sys.argv[2],'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()
Now run above script as follows – in Command prompt:
C:\Python27>python.exe copy_file.py input_file.txt output_file.txt
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
>>> 5+ repeat*2
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
5+ repeat*2
NameError: name 'repeat' is not defined
>>> '5'+5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
'5'+5
TypeError: cannot concatenate 'str' and 'int' objects
The last line of the error message indicates what happened. Exceptions come
in different types, and the type is printed as part of the message: the types in the example
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
need not be true for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).
The rest of the line provides detail based on the type of exception and what caused it.
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
listing source lines; however, it will not display lines read from standard input.
5.4HANDLING EXCEPTIONS
Python provides two very important features to handle any unexpected error
in your Python programs and to add debugging capabilities in them.
Exception Handling:
Assertions:
5.4.1Exception Handling
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block. After the try: block, include
Syntax:
try:
You do your operations here;
......................
exceptExceptionI:
If there is ExceptionI, then execute this block.
exceptExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax −
A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
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.
The else-block is a good place for code that does not need the try: block's protection.
Example:
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all
try:
fp = open("test_exception.txt", "w")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
fp.close()
This produces the following result:
Written successfully
try:
fp = open("test_exception.txt", "r")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
fp.close()
This produces the following result
Error: File don't have read permission
You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
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
though, because it catches all exceptions but does not make the programmer identify the root
cause of the problem that may occur.
You can also use the same except statement to handle multiple exceptions as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list, then execute this block.
......................
else:
If there is no exception then execute this block.
You can use a finally: block along with a try: block. The finally block is a
place to put any code that must execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all
try:
fp = open("test_exception.txt", "w")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
finally:
print "Closing file"
fp.close()
This produces the following result
Written successfully
Closing file
Example
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
try:
fp = open("test_exception.txt", "r")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
finally:
5.4.5Argument of an Exception
try:
You do your operations here;
......................
exceptExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are trapping multiple
exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause
of the exception. The variable can receive a single value or multiple values in the form of a
tuple. This tuple usually contains the error string, the error number, and an error location.
Example
Following is an example for a single exception
deftemp_convert(var):
try:
returnint(var)
exceptValueError, Argument:
print "The argument is not a numbers\n", Argument
temp_convert("abc")
This produces the following result
The argument is not a numbers
invalid literal for int() with base 10: 'abc'
defthis_fails():
x = 1/0
try:
this_fails()
exceptZeroDivisionError, detail:
print 'Handling run-time error:', detail
This produces the following result
Handling run-time error: integer division or modulo by zero
In this example exception is raised in this_fails() function. But, because of
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.
You can raise exceptions in several ways by using the raise statement. The
general syntax for the raise statement is as follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError)
and argument is a value for the exception argument. The argument is optional; if not
supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice),
and if present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that
the Python core raises are classes, with an argument that is an instance of the class. Defining
new exceptions is quite easy and can be done as follows −
deffunctionName( level ):
if level < 1:
raise "Invalid level!", level
# if we raise the exception,code below to this not executed
Note: In order to catch an exception, an "except" clause must refer to the same exception
thrown either class object or simple string. For example, to capture above exception, we
must write the except clause as follows
An assertion is a sanity-check that you can turn on or turn off when you are
done with your testing of the program.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid
input, and after a function call to check for valid output.
Example
defKelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
5.5 MODULES
Before we can use the functions in a module, we have to import it with an import statement:
>>>math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the name of
the function, separated by a dot (also known as a period). This format is called dot notation.
>>>math.log10(200)
2.3010299956639813
>>>math.sqrt(10)
3.1622776601683795
Math module have functions like log(), sqrt(), etc… In order to know what are
the functions available in particular module, we can use dir() function after importing
particular module. Similarly if we want to know detail description about a particular module
or function or variable means we can use help() function.
Example
>>> import math
>>>dir(math)
pow(...)
pow(x, y[, z]) -> number
5.5.1Writing Modules
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named addModule.py with the following code:
def add(a, b):
result = a + b
print(result)
add(10,20)
If you run this program, it will add 10 and 20 and print 30. We can import it like this:
>>> import addModule
30
Now you have a module object addModule
>>>addModule
<module 'addModule' from 'G:/class/python/code\addModule.py'>
The module object provides add():
>>>addModule.add(120,150)
270
So that‘s how you write modules in Python.
The only problem with this example is that when you import the module it
runs the test code at the bottom. Normally when you import a module, it defines new
functions but it doesn‘t run them.
Programs that will be imported as modules often use the following idiom:
if __name__ == '__main__':
add(10,20)
__name__ is a built-in variable that is set when the program starts. If the
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
addModule.py file as given below.
def add(a, b):
result = a + b
print(result)
if __name__ == '__main__':
add(10,20)
5.6 PACKAGES
The __init__.py file can also decide which modules the package exports as the API, while keeping
other modules internal, by overriding the __all__ variable, like so:
__init__.py:
__all__ = ["sample_module"]
Example.
Following program print each word in the specified file occurs how many times.
import sys
defword_count(file_name):
try:
file=open(file_name,"r")
try:
word_count(sys.argv[1])
exceptIndexError:
print("No file name passed as command line Argument")
fname=raw_input("Enter File Name:")
word_count(fname)
Content of a sample file word_count_input.txt is:
word count is the program which count each word in file appears how many times.
try:
word_count(sys.argv[1])
exceptIndexError:
print("No file name passed as command line Argument")
fname=raw_input("Enter File Name:")
word_count(fname)
This produces the following result
c:\Python27>python wordcount2.py
No file name passed as command line Argument
Enter File Name:word_count_input
No file found with name word_count_input
Enter New File Name:word_count_input.txt
This is a Python Program to copy the contents of one file into another. In order to perform
the copying operation we need to follow the following steps.
1. Open source file in read mode.
2. Open destination file in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.
Also we include command line argument for passing source and destination file names to
program. Also exception handling is used to handle exception that occurs when dealing with
files.
import sys
def copy(src,dest):
try:
source=open(src,'r')
destination=open(dest,'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()
exceptIOError:
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: