Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
145 views

GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in

The document discusses algorithms and provides examples of algorithms for common problems. It defines an algorithm as a sequence of instructions to solve a problem and lists characteristics like being precise, terminating, and obtaining the desired output. Examples of algorithms provided include finding the maximum of three numbers, calculating even numbers between 0-99, and converting between Fahrenheit and Celsius temperatures. Flowcharts are also defined as a way to represent algorithms graphically using boxes and arrows.

Uploaded by

Ruban Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
145 views

GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in

The document discusses algorithms and provides examples of algorithms for common problems. It defines an algorithm as a sequence of instructions to solve a problem and lists characteristics like being precise, terminating, and obtaining the desired output. Examples of algorithms provided include finding the maximum of three numbers, calculating even numbers between 0-99, and converting between Fahrenheit and Celsius temperatures. Flowcharts are also defined as a way to represent algorithms graphically using boxes and arrows.

Uploaded by

Ruban Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

www.rejinpaul.

com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

UNIT I ALGORITHMIC PROBLEM SOLVING


Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in
a list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi.

ALGORITHM
Definition:
Algorithm is defined as “a sequence of instructions designed in such a way that if the
instructions are executed in the specified sequence, the desired result will be obtained”.

n
It is also defined as “any problem whose solution can be expressed in a list of executable

g.i
instruction”.
 Set of step-by-step instructions that perform a specific task or operation
 Natural language NOT programming language.

rin
 Algorithm is the sequence of steps to be performed in order to solve a problem by the
computer.
 Three reasons for using algorithms are efficiency, abstraction and reusability.
ee
 Algorithms can be expressed in many different notations, including natural languages,
pseudocode, flowcharts and programming languages.
gin
 Analysis of algorithms is the theoretical study of computer program performance and
resource usage, and is often practiced abstractly without the use of specific programming
language or implementation.
 The practical goal of algorithm analysis is to predict the performance of different
En

algorithms in order to guide program design decisions.


 Most algorithms do not perform the same in all cases; normally an algorithm’s
performance varies with the data passed to it.
arn

 Typically, three cases are recognized: the best case, average case and worst case
 Worst case analysis of algorithms is considered to be crucial to applications such as
games, finance and robotics.
Le

 O-notation, also known as Big O-notation, is the most common notation used to express
an algorithm’s performance in a formal manner.
w.

Characteristics of algorithm
1. In the algorithm each and every instruction should be precise and unambiguous.
2. The instruction in an algorithm should not be repeated infinitely.
ww

3. Ensure that the algorithm will ultimately terminate.


4. The algorithm should be written in sequence.
5. It looks like normal English.
6. The desired result should be obtained only after the algorithm terminates.

Qualities of a good algorithm


 Time - Lesser time required.
 Memory - Less memory required.
 Accuracy - Suitable or correct solution obtained.

Department of Information Technology Page 1

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

 Sequence - Must be sequence and some instruction may be repeated in number of times
or until particular condition is met.
 Generability - Used to solve single problem and more often algorithms are designed to
handle a range of input data.

Examples of algorithm
Problem 1: Find the area of a Circle of radius r.
Inputs to the algorithm:
Radius r of the Circle.
Expected output:

n
Area of the Circle

g.i
Algorithm:
Step 1: Start
Step2: Read input the Radius r of the Circle

rin
Step3: Area PI*r*r // calculation of area
Step4: Print Area
Step 5: Stop ee
Problem2: Write an algorithm to read two numbers and find their sum.
Inputs to the algorithm:
First num1.
gin
Second num2.
Expected output:
Sum of the two numbers.
En

Algorithm:
Step1: Start
Step2: Read\input the first num1.
arn

Step3: Read\input the second num2.


Step4: Sum num1+num2 // calculation of sum
Step5: Print Sum
Step6: Stop
Le

Problem 3: Convert temperature Fahrenheit to Celsius


Inputs to the algorithm:
w.

Temperature in Fahrenheit
Expected output:
Temperature in Celsius
ww

Algorithm:
Step1: Start
Step 2: Read Temperature in Fahrenheit F
Step 3: C 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step5: End

Problem 4: Find the largest number between A and B


Inputs to the algorithm:

Department of Information Technology Page 2

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

A, B
Expected output:
Largest A or B
Algorithm:
Step 1: Start
Step 2:Read A, B
Step 3: If A is less than B, then
Big=B
Small=A
Print A is largest

n
Else

g.i
Big=A
Small = B
Step 4: Write (Display) BIG, SMALL

rin
Step 5: Stop

Problem 5: To determine a student’s average grade and indicate whether successful or fail.
ee
Step 1: Start
Step 2: Input mid-term and final
Step 3: average=(mid-term + final)/2
gin
Step 4: if (average < 60) then
Print “FAIL”
else
En

Print “SUCCESS”
Step 5: Stop
arn

Problem 6: A algorithm to find the largest value of any three numbers.


Step1: Start
Step2: Read/input A,B and C
Step3: If (A>=B) and (A>=C) then Max=A
Le

Step4: If (B>=A) and (B>=C) then Max=B


Step5:If (C>=A) and (C>=B) then Max=C
Step6: Print Max
w.

Step7: End

Problem 7: An algorithm to calculate even numbers between 0 and 99.


ww

Step 1: Start
Step 2: Read n or Initialize n=99
Step 3: Initialize i=2
Step 4: If i<=n, then goto step 5 else goto step 7
Step 5: If i%2=0, then goto step 5.1,5.2 else goto step 6
Step 5.1:Print i
Step 5.2:i=i+1 goto step 4
Step 6: i=i+1 goto step4
Step 7: Stop

Department of Information Technology Page 3

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

FLOWCHARTS

Definitions:
A flowchart is a schematic representation of an algorithm or a stepwise process, showing
the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts
are used in designing or documenting a process or program.
A flow chart, or flow diagram, is a graphical representation of a process or system that
details the sequencing of steps required to create output.
A flowchart is a picture of the separate steps of a process in sequential order.
The benefits of flowcharts are as follows:

n
1. Communication: Flowcharts are better way of communicating the logic of a system to all

g.i
concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is

rin
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase. ee
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part
gin

The Limitations of using flowcharts :


1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
En

becomes complex and clumsy.


2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
arn

3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes


a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.
Le

GUIDELINES FOR DRAWING A FLOWCHART


Flowcharts are usually drawn using some standard symbols; however, some special symbols
can also be developed when required. Some standard symbols, which are frequently required for
w.

flowcharting many computer programs.

 Terminator:
ww

An oval flow chart shape indicates the start or end of the process, usually containing the
word “Start” or “End”.
Terminator
 Process:
A rectangular flow chart shape indicates a normal/generic process flow step. For
example, “Add 1 to X”, “M = M*F” or similar.

Process

Department of Information Technology Page 4

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

 Decision:
A diamond flow chart shape indicates a branch in the process flow. This symbol
is used when a decision needs to be made, commonly a Yes/No question or True/False
test.
Decision

No

n
g.i
Yes

 Connector:

rin
A small, labelled, circular flow chart shape used to indicate a jump in the process flow.
Connectors are generally used in complex or multi-sheet diagrams.
ee
gin
 Data:
A parallelogram that indicates data input or output (I/O) for a process. Examples: Get X
from the user, Display X.
En

Input /
Output
 Delay:
arn

Used to indicate a delay or wait in the process for input from some other process.
Le

 Arrow:
w.

Used to show the flow of control in a process. An arrow coming from one symbol and
ending at another symbol represents that control passes to the symbol the arrow points to.
ww

Department of Information Technology Page 5

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

n
g.i
rin
ee
gin
En

These are the basic symbols used generally. Now, the basic guidelines for drawing a
flowchart with the above symbols are that:
arn

 In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
 The flowchart should be neat, clear and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
Le

 The flowchart is to be read left to right or top to bottom.


 A process symbol can have only one flow line coming out of it.
w.

 For a decision symbol, only one flow line can enter it, but multiple lines can leave it to
denote possible answers.
 The terminal symbols can only have one flow line in conjunction with them.
ww

Department of Information Technology Page 6

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Example Flowchart
Problem 1: Draw the flowchart to find the largest number between A and B

n
g.i
rin
ee
gin
En

Problem 2: Find the area of a circle of radius r.


arn
Le
w.
ww

Department of Information Technology Page 7

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Problem 3: Convert temperature Fahrenheit to Celsius.

n
g.i
rin
ee
gin
En

Problem 4: Flowchart for an algorithm which gets two numbers and prints sum of their value
arn
Le
w.
ww

Department of Information Technology Page 8

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Problem5: Flowchart for the problem of printing even numbers between 0 and 99.

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 9

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

PSEUDOCODE
Definition:
 “Pseudo” means initiation or false.
 “Code” means the set of statements or instructions written in a programming language.
 Pseudocode is also called as “Program Design Language [PDL]”.
 Pseudocode is a Programming Analysis Tool, which is commonly used for planning the
program logic.
 Pseudocode is written in normal English and cannot be understood by the computer.
 Set of instructions that mimic programming language instructions
 An informal high-level description of the operating principle of a computer program. It

n
uses the structural conventions of a programming language, but is intended for human

g.i
reading rather than machine reading.

Rules for writing Pseudocode

rin
1. Write one statement per line
2. Capitalize initial keywords (READ, WRITE, IF, WHILE, UNTIL).
3. Indent to show hierarchy. ee
4. End multiline structure.
5. Keep statements language.
gin
Advantages
 It can be done easily in any word processor.
 It can be easily modified as compared to flowchart.
En

 Its implementation is very useful in structured design elements.


 It can be written easily.
 It can be read and understood easily.
arn

 Converting a pseudocode to programming language is very easy compared with


converting a flowchart to programming language.
Le

Disadvantage
 It is not visual.
 We do not get a picture of the design.
w.

 There is no standardized style or format.


 For a beginner, it is more difficult to follow the logic or write pseudocode as compared to
flowchart.
ww

Examples Pseudocode
Problem 1: Calculate sum and average for n numbers.
BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i <=n, then
COMPUTE sum = sum +i
CALCULATE i=i+1

Department of Information Technology Page 10

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

END FOR
COMPUTE avg = sum/n
PRINT sum, avg
END

Problem 2: Calculate area of circle

BEGIN
READ radius, r
INITIALIZE pi=3.14

n
CALCULATE Area=pi * r *r

g.i
PRINT Area
END

rin
Problem 3: Read Number n and print the integers counting upto n

BEGIN ee
READ n
INITIALIZE i to 1
FOR i <= n, then
gin
DISPLAY i
INCREMENT i
END FOR
En

END

Problem 4: Find the greater number between two numbers.


arn

BEGIN
Read A, B
IF A is less than B
BIG = B
Le

SMALL = A
ELSE
BIG = A
w.

SMALL = B
WRITE / DISPLAY BIG, SMALL
END
ww

Problem 5: To determine a student whether successful or fail.


BEGIN
READ student ‘s grade
IF student's grade is greater than or equal to 50
Print "passed"
ELSE
Print "failed“
END

Department of Information Technology Page 11

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

ILLUSTRATIVE PROBLEM
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then
Print Guess is hit
Else

n
Print Guess not hit

g.i
Print hidden
Step 6: Stop
Pseudocode:

rin
BEGIN
COMPUTE hidden=random value in a range
READ guess ee
IF guess=hidden, then
PRINT Guess is hit
ELSE
gin
PRINT Guess not hit
PRINT hidden
END IF-ELSE
En

END
Flowchart:
arn
Le
w.
ww

Department of Information Technology Page 12

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

2. Find minimum in a list

Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4

n
Step 5: Compute min=a[0]

g.i
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2

rin
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min ee
Step 10: Stop

Pseudocode:
gin
BEGIN
READ n
FOR i=0 to n, then
En

READ a[i]
INCREMENT i
END FOR
arn

COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
Le

INCREMENT i
ELSE
INCREMENT i
w.

END IF-ELSE
END FOR
PRINT min
ww

END

Department of Information Technology Page 13

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Flowchart:

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 14

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

3. Insert a card in a list of sorted cards

Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4

n
Step 5: Read item

g.i
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]

rin
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1 ee
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
gin
Step 11: Stop

Pseudocode:
En

BEGIN
READ n
FOR i=0 to n, then
arn

READ a[i]
INCREMENT i
END FOR
READ item
Le

FOR i=n-1 to 0 and item<a[i], then


CALCULATE a[i+1]=a[i]
DECREMENT i
w.

END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
ww

FOR i=0 to n, then


PRINT a[i]
INCREMENT i
END FOR
END

Department of Information Technology Page 15

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Flowchart:

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 16

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

4. Tower of Hanoi
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) recursively until n=0
Step 4.1: If n=0, then goto step 5 else goto step 4.2
Step 4.2: T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) , Move disk from source to destination

n
T(n-1,Aux,Beg,End)

g.i
Step 5: Stop
Pseudcode:

rin
BEGIN
READ n
CALCULATE move=pow(2,n)-1 ee
FUNCTION T(n,Beg,Aux,End) Recursively until n=0
PROCEDURE
gin
IF n=0 then,
No disk to move
Else
En

T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move disk from source to destination
T(n-1,Aux,Beg,End)
arn

END PROCEDURE
END
Flowchart:
Le
w.
ww

Department of Information Technology Page 17

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

Procedure to solve Tower of Hanoi

The goal of the puzzle is to move all the disks from leftmost peg to rightmost peg.

1. Move only one disk at a time.

2. A larger disk may not be p1aced on top of a smaller disk.

For example, consider n=3 disks

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 18

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 19

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 20

Visit For More : www.LearnEngineering.in


www.rejinpaul.com

GE8151 – Problem Solving and Python Programming Unit - I


Visit For More : www.LearnEngineering.in

n
g.i
rin
ee
gin
En
arn
Le
w.
ww

Department of Information Technology Page 21

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

UNIT II DATA, EXPRESSIONS, STATEMENTS


Visit For Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
More : www.LearnEngineering.in
variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and
arguments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points.

What is a program?
A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations or

n
finding the roots of a polynomial, but it can also be a symbolic computation, such as searching

g. i
and replacing text in a document or (strangely enough) compiling a program.
There are few basic instructions appear in every programming language:
input: Get data from the keyboard, a file, or some other device.

in
output: Display data on the screen or send data to a file or other device.

er
math: Perform basic mathematical operations like addition and multiplication.
conditional execution: Check for certain conditions and execute the appropriate code.
ne
repetition: Perform some action repeatedly, usually with some variation.
gi
Python programming language
Python is an example of a high-level language; other high-level languages you might
En

have heard of are C, C++, Perl, and Java. There are also low-level languages, sometimes
referred to as “machine languages” or “assembly languages.
The high-level program is called the source code, and the translatedprogram is called the
rn

object code or the executable. Once a program is compiled, you can execute it repeatedly
without further translation.
ea

Programs written in a high-level language have to be processed before they can run.
Python is considered an interpreted language because Python programs are executed by an
.L

interpreter. There are two ways to use the interpreter: interactive mode and script mode.
In interactive mode, type Python programs and the interpreter displays the result.
w

Eg: >>> 1 + 1
2
ww

Where, >>> is the prompt the interpreter uses to indicate that it is ready
In script mode, type python program in a file and store the file with .py extension and use
the interpreter to execute the contents of the file, which is called a script.
bug: An error in a program.
debugging: The process of finding and removing any of the three kinds of programming errors.
syntax: The structure of a program.
syntax error: An error in a program that makes it impossible to parse (and therefore impossible
to interpret).
exception: An error that is detected while the program is running.
Visit For More : www.LearnEngineering.in
semantics: The meaning of a program.
St.Joseph’s Institute of Technology Common to all Branch Page 1
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

semantic error: An error in a program that makes it do something other than what the
Visit For programmer intended.
More : www.LearnEngineering.in
VARIABLES, EXPRESSIONS AND STATEMENTS
Values and types
A value is one of the basic things a program. There are different values integers, float and
strings. The numbers with a decimal point belong to a type called float. The values written in
quotes will be considered as string, even it’s an integer. If type of value is not known it can be
interpreted as
Eg:
>>> type('Hello, World!')

n
<type 'str'>

g. i
>>> type(17)
<type 'int'>

in
>>> type('17')
<type 'str'>

er
>>> type('3.2')
<type 'str'>
ne
Variables
gi
A variable is a name that refers to a value. A variable is a location in memory used to store some
data (value). They are given unique names to differentiate between different memory locations.
En

The rules for writing a variable name are same as the rules for writing identifiers in Python. The
assignment operator (=) to assign values to a variable. An assignment statement creates new
variables and gives them values:
rn

Eg:
>>> message = 'And now for something completely different'
ea

>>> n = 17
>>> pi = 3.1415926535897932
.L

The type of a variable is the type of the value it refers to.


Eg:
w

>>> type(message)
ww

<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

Variable names and keywords


Variable names can be arbitrarily long and contain both letters and numbers, but they
have to begin with a letter. The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as my_name or airspeed_of_unladen_swallow.
Visit For More : www.LearnEngineering.in
If you give a variable an illegal name, you get a syntax error:
St.Joseph’s Institute of Technology Common to all Branch Page 2
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Eg:
Visit For >>>
More 76trombones = 'big parade'
: www.LearnEngineering.in
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python 2 has 31 keywords. In Python 3, has 33 keywords.
and del from not while

n
as elif global or with

g. i
assert else if pass yield
break except import print nonlocal
class exec in raise false

in
continue finally is return

er
def for lambda try

Python Identifiers
ne
Identifier is the name given to entities like class, functions, variables etc. in Python. It
gi
helps differentiating one entity from another.
Rules for writing identifiers
En

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen,
all are valid example.
rn

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
ea

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.


5. Identifier can be of any length.
.L

Data types in Python


w

In Python programming, data types are actually classes and variables are instance (object)
of these classes. They are defined as int, float and complex class in Python.
ww

Lists
List is an ordered sequence of items. Python knows a number of compound data types,
used to group together other values. The most versatile is the list, which can be written as a list
of comma-separated values (items) between square brackets. List items need not all have the
same type.
Eg:
>>> a = [’spam’, ’eggs’, 100, 1234]
>>> a
Visit For More : www.LearnEngineering.in
Output: [’spam’, ’eggs’, 100, 1234]
St.Joseph’s Institute of Technology Common to all Branch Page 3
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Expressions and statements


An expression is a combination of values, variables, and operators.
Visit For More : www.LearnEngineering.in
Eg:
17
x
x + 17
Instructions that a Python interpreter can execute are called statements. A statement is a
unit of code that the Python interpreter can execute. Two kinds of statement: print and
assignment.
Eg:
a=1+2+3+\

n
4+5+6+\

g. i
7+8+9
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\).

in
Python Indentation

er
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation. ne
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
gi
block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
En

example.
rn
ea
w .L

Python Tuple
ww

Tuple is an ordered sequence of items same as list.The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
It is defined within parentheses () where items are separated by commas.
Eg:
>>> t = (5,'program', 1+3j)
>>> a=(5,7.9,10)

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 4


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to
Visit For More : www.LearnEngineering.in
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Eg:
>>> s = "This is a string"
>>> s = '''a multiline

Comments
Comments indicate Information in a program that is meant for other programmers (or
anyone reading the source code) and has no effect on the execution of the program. In Python,

n
we use the hash (#) symbol to start writing a comment.

g. i
Eg:
#This is a comment
#print out Hello

in
print('Hello')

er
Python Output Using print() function

The actual syntax of the print() function is


ne
gi
print (“Statement”,variable_name)
print (‘Statement’,variable_name)
En

print (“Statement %formatting function”%variable_name)

After all values are printed, end is printed. It defaults into a new line.
rn

The file is the object where the values are printed and its default value is sys.stdout (screen)
Eg:
ea

print ('This sentence is output to the screen')


# Output: This sentence is output to the screen
.L

a=5
w
ww

print ('The value of a is', a)


# Output: The value of a is 5

Python Input
The syntax for input() is

input([prompt])
raw_input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
Eg:
Visit For More : www.LearnEngineering.in
>>> num = input('Enter a number: ')
St.Joseph’s Institute of Technology Common to all Branch Page 5
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Enter a number: 10
Visit For >>>
More num
: www.LearnEngineering.in
'10'
>>>a=raw_input(‘Enter a number’)
10
Modules
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended. A module can contain executable statements as well
as function definitions. Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module. Modules can import other modules.

n
g. i
Python Import
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.

in
Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.

er
Python provides two ways to import modules.

>>> import math


>>> print math
ne
<module 'math' (built-in)>
gi
>>> print math.pi
3.14159265359
En

If you import math, you get a module object named math. The module object contains
constants like pi and functions like sin and exp.
rn

But if you try to access pi directly, you get an error.


>>> print pi
ea

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
.L

NameError: name 'pi' is not defined


w

As an alternative, you can import an object from a module like this:


ww

>>> from math import pi

Now you can access pi directly, without dot notation.


>>> print pi
3.14159265359

Operators and operands


Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 6


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and


Visit For exponentiation.
More : www.LearnEngineering.in
Eg:
20+32
hour-1
hour*60+minute
minute/60
5**2 (5+9)*(15-7)

Precedence Of Operators

n
The order of evaluation depends on the rules of precedence. The acronym PEMDAS is

g. i
a useful way to remember the rules:
 Parentheses have the highest precedence
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3,

in
not 27.
 Multiplication and Division have the same precedence, which is higher than Addition and

er
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8,
not 5.
ne
 Operators with the same precedence are evaluated from left to right.
gi
Type of operators in Python
En

Arithmetic operators
Comparison (Relational) operators
rn

Logical (Boolean) operators


Bitwise operators
ea

Assignment operators
Special operators
.L

Arithmetic operators
w

Arithmetic operators are used to perform mathematical operations like addition,


ww

subtraction, multiplication etc.


Arithmetic operators in Python
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operandVisit
by For
theMore
right: www.LearnEngineering.in
x % y (remainder of

St.Joseph’s Institute of Technology Common to all Branch Page 7


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

x/y)
Visit For More : www.LearnEngineering.in
Floor division - division that results into whole number adjusted
// x // y
to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Example: Arithmetic operators in Python
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)

n
g. i
# Output: x - y = 11
print('x - y =',x-y)

in
# Output: x * y = 60

er
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)
ne
gi
# Output: x // y = 3
En

print('x // y =',x//y)

# Output: x ** y = 50625
rn

print('x ** y =',x**y)
When you run the program, the output will be:
ea

x + y = 19
x - y = 11
.L

x * y = 60
x / y = 3.75
w

x // y = 3
x ** y = 50625
ww

Comparison operators
Comparison operators are used to compare values. It either returns True or False
according to the condition.
Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 8


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

!= Not equal to - True if operands are not equal x != y


Visit For More : www.LearnEngineering.in
Greater than or equal to - True if left operand is greater than or equal to the
>= x >= y
right
<= Less than or equal to - True if left operand is less than or equal to the right x <= y

Example: Comparison operators in Python


x = 10
y = 12

n
# Output: x > y is False

g. i
print('x > y is',x>y)

# Output: x < y is True

in
print('x < y is',x<y)

er
# Output: x == y is False
print('x == y is',x==y)
ne
gi
# Output: x != y is True
print('x != y is',x!=y)
En

# Output: x >= y is False


print('x >= y is',x>=y)
rn

# Output: x <= y is True


ea

print('x <= y is',x<=y)


Output:
.L

x > y is False
x < y is True
w

x == y is False
x != y is True
ww

x >= y is False
x <= y is True

Logical operators

Logical operators are and, or, not operators.

Operator Meaning Example


and True if both the operands are true Visit
x andFor y
More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 9


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

or True if either of the operands is true x or y


Visit For More : www.LearnEngineering.in
not True if operand is false (complements the operand) not x

Example: Logical Operators in Python


x = True
y = False

# Output: x and y is False


print('x and y is',x and y)

n
# Output: x or y is True

g. i
print('x or y is',x or y)

in
# Output: not x is False
print('not x is',not x)

er
Output: ne
x and y is False
x or y is True
gi
not x is False
En

Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by
rn

bit, hence the name.


For example, 2 is 10 in binary and 7 is 111.
ea

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
.L

Bitwise operators in Python


Operator Meaning Example
w

& Bitwise AND x& y = 0 (0000 0000)


ww

| Bitwise OR x | y = 14 (0000 1110)


~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators
Assignment operators are used in Python to assign values
Visit FortoMore
variables. a = 5 is a simple
: www.LearnEngineering.in
assignment operator that assigns the value 5 on the right to the variable a on the left.
St.Joseph’s Institute of Technology Common to all Branch Page 10
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

There are various compound operators in Python like a += 5 that adds to the variable and
Visit For later
More assigns the same. It is equivalent to a = a + 5.
: www.LearnEngineering.in

Assignment operators in Python


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5

n
g. i
/= x /= 5 x=x/5
%= x %= 5 x=x%5

in
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5

er
&= x &= 5 x=x&5
|= x |= 5 x=x|5
ne
^= x ^= 5 x=x^5
gi
>>= x >>= 5 x = x >> 5
En

<<= x <<= 5 x = x << 5

Example: Assignment operators in Python


rn

x = 15
ea

y=4
x+=y
# Output: x + y = 19
.L

print('x + y =',x)
w

x = 15
ww

y=4
x-=y
# Output: x - y = 11
print('x - y =',x)

x = 15
y=4
x*=y
# Output: x * y = 60
print('x * y =',x) Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 11


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

x = 15
Visit For y = 4: www.LearnEngineering.in
More
x/=y
# Output: x / y = 3.75
print('x / y =',x)

x = 15
y=4
x//=y
# Output: x // y = 3

n
print('x // y =',x)

g. i
x = 15
y=4

in
x**=y

er
# Output: x ** y = 50625
print('x ** y =',x)

Special operators
ne
gi
Python language offers some special type of operators like the identity operator or the
membership operator.
En

Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
rn

variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
ea

Identity operators in Python


.L

Operator Meaning Example


is True if the operands are identical (refer to the same object) x is True
w

is not True if the operands are not identical (do not refer to the same object) x is not True
ww

Example: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 12


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

print(x1 is not y1)


Visit For More : www.LearnEngineering.in
# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)

Output:
False

n
True

g. i
False

Here, we see that x1 and y1 are integers of same values, so they are equal as well as

in
identical. Same is the case with x2 and y2 (strings).

er
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.

Membership operators
ne
gi
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).
En

In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example


rn

in True if value/variable is found in the sequence 5 in x


ea

not in True if value/variable is not found in the sequence 5 not in x


.L

Example: Membership operators in Python


x = 'Hello world'
w

y = {1:'a',2:'b'}
ww

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)
Visit For More : www.LearnEngineering.in
# Output: False
St.Joseph’s Institute of Technology Common to all Branch Page 13
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

print('a' in y)
Visit For More : www.LearnEngineering.in
Output:
True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

n
Functions

g. i
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows

in
larger and larger, functions make it more organized and manageable. Furthermore, it avoids
repetition and makes code reusable.

er
Function Definitions ne
In Python each function definition is of the form
def name of function (list of formal
gi
parameters):
En

body of function

For example, we could define the function max by the code


rn

def max(x, y):


if x > y:
ea

return x
else:
.L

return y
def is a reserved word that tells Python that a function is about to be defined.
w

A function definition which consists of following components.


ww

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 14


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Visit For Function Call


More : www.LearnEngineering.in
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.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument
of the function. The resultis called the return value.

n
The return statement

g. i
The return statement is used to exit a function and go back to the place from where it was
called. The Syntax of return statement:
return [expression_list]

in
This statement can contain expression which gets evaluated and the value is returned. If there is

er
no expression in the statement or the return statement itself is not present inside a function, then
the function will return the None object. ne
For example:
>>> print(greet("May"))
gi
Hello, May. Good morning!
None
En

Here, None is the returned value.

How Function works in Python?


rn
ea
w .L
ww

Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 15


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Visit For More : www.LearnEngineering.in


Type conversion functions
Python provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or complains otherwise:

>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello

n
int can convert floating-point values to integers, but it doesn’t round off; it chops off the

g. i
fraction part:
>>> int(3.99999)

in
3
>>> int(-2.3)

er
-2
ne
float converts integers and strings to floating-point numbers:
>>> float(32)
gi
32.0
>>> float('3.14159')
En

3.14159
Finally, str converts its argument to a string:
rn

>>> str(32)
'32'
ea

>>> str(3.14159)
'3.14159'
.L

Math functions
w

Python has a math module that provides mathematical functions.


ww

>>> import math


This statement creates a module object named math. If you print the module object, you
get some information about it:

>>> print 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 andMore
Visit For the :name of the
www.LearnEngineering.in
function, separated by a dot (also known as a period). This format is called dot notation.
St.Joseph’s Institute of Technology Common to all Branch Page 16
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Visit For Eg:


More : www.LearnEngineering.in
>>> math.sqrt(2) / 2.0
0.707106781187

Flow of execution
The order in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. Statements are executed one at a
time, in order from top to bottom. Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not executed until the function is

n
called.

g. i
Parameters and arguments
Some of the built-in functions we have seen require arguments. For example, when you

in
call math.sin you pass a number as an argument. Some functions take more than one argument:

er
math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters. Here is

Eg: def print_twice(bruce):


ne
an example of a user-defined function that takes an argument:
gi
print bruce
print bruce
En

This function assigns the argument to a parameter named bruce. When the function is
called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
rn

>>> print_twice('Spam')
Spam
ea

Spam
>>> print_twice(17)
.L

17
17
w

>>> print_twice(math.pi)
3.14159265359
ww

3.14159265359

Parameter Passing
Parameter passing is the process of passing arguments to a function. There are two types
of arguments: Actual arguments and formal arguments. Actual arguments are the values passed
to a function’s formal parameters to be operated on.
Eg:
def f(x): #name x used as formal parameter
y=1
Visit For More : www.LearnEngineering.in
x=x+y
St.Joseph’s Institute of Technology Common to all Branch Page 17
www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

print 'x =', x


Visit For return x
More : www.LearnEngineering.in
x=3
y=2
z = f(x) #value of x used as actual parameter
print 'z =', z
print 'x =', x
print 'y =', y
When run, this code prints,
x=4

n
z=4

g. i
x=3
y=2
A default argument is an argument that can be optionally provided in a given function

in
call. When not provided, the corresponding parameter provides a default value.
Eg:

er
def greet(name, msg = "Good morning!"):
""" ne
This function greets to
the person with the
gi
provided message.
If message is not provided,
En

it defaults to "Good
morning!"
rn

"""
ea

print("Hello",name + ', ' + msg)


greet("Kate")
.L

greet("Bruce","How do you do?")


w

Output:
Hello Kate, Good morning!
ww

Hello Bruce, How do you do?

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 18


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Eg:
Visit For def
Moremy_func():
: www.LearnEngineering.in
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20

n
Local Scope and Local Variables
A local variable is a variable that is only accessible from within a given function. Such

g. i
variables are said to have local scope .

in
er
ne
gi
En
rn
ea

Global Variables and Global Scope


A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope .
w .L
ww

Variable max is defi ned outside func1 and func2 and therefore “global” to each.
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 19


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

Programs
Visit For More : www.LearnEngineering.in
1. Python program to swap two variables

# To take input from the user


x = input('Enter value of x: ')
y = input('Enter value of y: ')
#x = 5
#y = 10
# create a temporary variable and swap the values

n
x=x+y

g. i
y=x-y
x=x+y
print 'The value of x after swapping:’,x

in
print 'The value of y after swapping:’,y

er
2. Python Program to calculate the square root
ne
# Note: change this value for a different result
gi
num = 8
# uncomment to take the input from the user
En

#num = float(input('Enter a number: '))


num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
rn

3. Distance between two points


ea

import math
p1 = [4, 0]
.L

p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
w

print(distance)
ww

4. Write a function that draws a grid like the following:


+----+----+
| | |
| | |
| | |
| | |
+----+----+
| | |
| | |
| | |
| | |
+----+----+ Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Common to all Branch Page 20


www.rejinpaul.com
GE8151-Problem Solving and Python Programming Unit-II

def print_border():
print ("+", "- " * 4, "+", "- " * 4, "+")
Visit For More : www.LearnEngineering.in

def print_row():
print ("|", " " * 8, "|", " " * 8, "|")

def block():
print_border()
print_row()
print_row()

n
print_row()

g. i
print_row()

block()

in
block()

er
print_border()

5. Adding two numbers using user defined function.


# Program to illustrate
ne
gi
# the use of user-defined functions
def add_numbers(x,y):
En

sum = x + y
return sum
num1 = 5
rn

num2 = 6
print("The sum is", add_numbers(num1, num2))
ea

6. Program to circulate the values of n variables


.L

from collections import deque


lst=[1,2,3,4,5]
w

d=deque(lst)
print d
ww

d.rotate(2)
print d
Output:[3,4,5,1,2]

(OR)
list=[10,20,30,40,50]
n=2 #Shift 2 location
list[n:]+list[:n]
Visit For More : www.LearnEngineering.in
Output: [30,40,50,10,20]
St.Joseph’s Institute of Technology Common to all Branch Page 21
www.rejinpaul.com
1

UNIT
Visit For More : www.LearnEngineering.inIII CONTROL FLOW, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, local and global scope, function composition, recursion; Strings:
string slices, immutability, string functions and methods, string module; Lists as arrays.
Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search,
binary search.

Conditionals and recursion

n
g. i
Modulus operator
The modulus operator works on integers and yields the remainder when the first

in
operand is divided by the second. In Python, the modulus operator is a percent sign (%). The
syntax is the same as for other operators:

er
>>> quotient = 7 / 3
>>> print quotient ne
2
>>> remainder = 7 % 3
gi
>>> print remainder
1
En

So 7 divided by 3 is 2 with 1 left over.


The modulus operator turns out to be surprisingly useful. For example, you can check
whether one number is divisible by another—if x % y is zero, then x is divisible by y.
rn

Also, you can extract the right-most digit or digits from a number. For example, x % 10
yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.
ea

Boolean expressions
.L

A boolean expression is an expression that is either true or false. The following


examples use the operator ==, which compares two operands and produces True if they are equal
w

and False otherwise:


ww

>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
2

The == operator is one of


Visit For More : www.LearnEngineering.in the relational operators; the others are:
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

Logical operators
There are three logical operators: and, or, and not. The semantics (meaning) of these

n
operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is

g. i
greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is

in
false, that is, if x is less than or equal to y. The operands of the logical operators should be
boolean expressions. Any nonzero number is interpreted as “true.”

er
>>> 17 and True
True
ne
gi
Keyboard input
Python 2 provides a built-in function called raw_input that gets input from the keyboard.
En

In Python 3, it is called input.


>>> text = raw_input()
What are you waiting for?
rn

>>> print text


What are you waiting for?
ea

>>> name = raw_input('What...is your name?\n')


What...is your name?
.L

Arthur, King of the Britons!


>>> print name
w

Arthur, King of the Britons!


ww

The sequence \n at the end of the prompt represents a newline, which is a special
character that causes a line break.
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42

Conditional statement (if)


Conditional statements give us the ability to check conditions and change the behavior
of the program accordingly. The syntax for if statement:
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
3

Visit For More :ifwww.LearnEngineering.in


<test_expression>:
<body>

n
g. i
in
er
Eg: ne
num = 3
if num > 0:
gi
print(num, "is a positive number.")
print("This is always printed.")
En

num = -1
if num > 0:
rn

print(num, "is a positive number.")


ea

print("This is also always printed.")

The boolean expression after if is called the condition. If it is true, then the indented
.L

statement gets executed. If not, nothing happens.


w

Alternative execution (if… else)


ww

A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks like this:

if <test_expression>:
<body_1>
else:
<body_2>

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
4

Visit For More : www.LearnEngineering.in

n
g. i
in
Eg:
# Program checks if the number is positive or negative

er
num = 3
if num >= 0:
print("Positive or Zero")
ne
else:
gi
print("Negative number")
En

If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays a message to that effect. If the condition is false, the second set of statements is
executed.
rn

Chained conditionals
ea

Sometimes there are more than two possibilities and we need more than two branches.
The syntax looks like this:
.L

if <test_expression_1>:
<body1>
w

elif <test_expression_2>:
ww

<body2>
elif <test_expression_3>:
<body3>
….
…..
else:
<bodyN>

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
5

Visit For More : www.LearnEngineering.in

n
g. i
in
er
ne
gi
En

Eg:
# In this program,
# we check if the number is positive or
rn

# negative or zero and


# display an appropriate message
ea

num = 3.4
.L

# Try these two variations as well:


w

# num = 0
ww

# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
6

Visit For elif


Moreis: www.LearnEngineering.in
an abbreviation of “else
if.” Again, exactly one branch will be executed. There is no limit
on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()

n
Each condition is checked in order. If the first is false, the next is checked, and so on. If

g. i
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.

in
Nested conditionals

er
One conditional can also be nested within another. We could have written the trichotomy
example like this:
#
#
In this program, we input a number
check if the number is positive or
ne
# negative or zero and display
# an appropriate message
gi
# This time we use nested if
En

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
rn

else:
print("Positive number")
ea

else:
print("Negative number")
.L

The outer conditional contains two branches. The first branch contains a simple
statement. The second branch contains another if statement, which has two branches of its own.
w

Those two branches are both simple statements, although they could have been conditional
statements as well.
ww

Although the indentation of the statements makes the structure apparent, nested
conditionals become difficult to read very quickly.
Logical operators often provide a way to simplify nested conditional statements. For
example, we can rewrite the following code using a single conditional:

if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
The print statement is executed only if we make it past both conditionals, so we can get
Visit For More : www.LearnEngineering.in
the same effect with the and operator:
www.rejinpaul.com
7

Visit For More : www.LearnEngineering.in


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

Recursion
Recursion is the process of calling the function that is currently executing. It is legal for
one function to call another; it is also legal for a function to call itself. An example of recursive
function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For

n
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

g. i
# An example of a recursive function to
# find the factorial of a number

in
def calc_factorial(x):

er
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
ne
else:
gi
return (x * calc_factorial(x-1))
En

num = 4
print("The factorial of", num, "is", calc_factorial(num))
rn

Output:
The factorial of 4 is 24
ea

The Advantages of recursion


.L

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using recursion.
w

3. Sequence generation is easier with recursion than using some nested iteration.
The Disadvantages of recursion
ww

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Iteration
The while statement
The keyword while followed by a test expression (which can be any valid expression),
and a colon. Following the header is an indented body. The
Visittest
For expression is evaluated. If it
More : www.LearnEngineering.in
www.rejinpaul.com
8

Visit For evaluates to True, then thebody of the loop is executed. After executing the body, the test
More : www.LearnEngineering.in
expression is evaluated again. While test expression evaluates to True, the body of the loop is
executed. When the test expression evaluates to False, the loop is terminated and execution
continues with the statement following the body.

while
<test_expression>:
<body>

n
g. i
in
er
ne
gi
En
rn
ea
.L

Eg:
def sequence(n):
w

while n != 1:
ww

print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1

The condition for this loop is n != 1, so the loop will continue until n is 1, which makes
the condition false.
Each time through the loop, the program outputs the value of n and then checks whether
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
9

Visit For it is even


More or odd. If it is even,
n is divided by 2. If it is odd, the value of n is replaced with n*3+1.
: www.LearnEngineering.in
For example, if the argument passed to sequence is 3, the resulting sequence is 3,10, 5, 16, 8, 4,
2, 1.

The for Statement


Python’s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence.

for val in sequence:


Body of for

n
g. i
in
er
ne
gi
En
rn
ea

Eg:
.L

# Program to find the sum of all numbers stored in a list


w

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
ww

# variable to store the sum


sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
10

Visit For The


More range() function
: www.LearnEngineering.in
If you do need to iterate over a sequence of numbers, the built-in function range() comes
in handy. It generates arithmetic progressions:

Eg:
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)

This function does not store all the values in memory, it would be inefficient. So it

n
remembers the start, stop, step size and generates the next number on the go.

g. i
Python break and continue
The break statement terminates the loop containing it. Control of the program flows to

in
the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate

er
the innermost loop.
The working of break statement in for loop and while loop is shown below.
ne
gi
En
rn
ea
w .L
ww

Eg:
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
11

The continue statement


Visit For More : www.LearnEngineering.in is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
The working of continue statement in for and while loop is shown below.

n
g. i
in
er
Eg:
# Prints out only odd numbers - 1,3,5,7,9
ne
for x in range(10):
gi
# Check if x is even
En

if x % 2 == 0:
continue
print(x)
rn

Python pass statement


ea

The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.
.L

Eg:
>>> while True:
w

... pass # Busy-wait for keyboard interrupt (Ctrl+C)


...
ww

This is commonly used for creating minimal classes:


>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body
when you are working on new code, allowing you to keep thinking at a more abstract level. The
pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
12

Visit For More : www.LearnEngineering.in FRUITFUL FUNCTIONS


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

But so far, none of the functions we have written has returned a value. In this chapter, we

n
are going to write functions that return values, which we will call fruitful functions, for want of a

g. i
better name. The first example is area, which returns the area of a circle with the given radius:
def area(radius):

in
temp = 3.14159 * radius**2
return temp

er
We have seen the return statement before, but in a fruitful function the return statement
ne
includes a return value. This statement means: Return immediately from this function and use the
following expression as a return value. The expression provided can be arbitrarily complicated,
so we could have written this function more concisely:
gi
def area(radius):
En

return 3.14159 * radius**2

On the other hand, temporary variables like temp often make debugging easier.
rn

Sometimes it is useful to have multiple return statements, one in each branch of a conditional.
We have already seen the built-in abs, now we see how to write our own:
ea

def absolute_value(x):
if x < 0:
.L

return -x
else:
w

return x
ww

Since these return statements are in an alternative conditional, only one will be executed.
As soon as one is executed, the function terminates without executing any subsequent
statements. Another way to write the above function is to leave out the else and just follow the if
condition by the second return statement.
def absolute_value(x):
if x < 0:
return -x
return x
Visit For More : www.LearnEngineering.in
Think about this version and convince yourself it works the same as the first one.
www.rejinpaul.com
13

Code that appears after


Visit For More : www.LearnEngineering.in a return statement, or any other place the flow of execution can
never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. The following version of absolute_value fails to do this:
def
absolute_value(x):
if x < 0:
return -x
elif x > 0:

n
return x

g. i
This version is not correct because if x happens to be 0, neither condition is true, and the

in
function ends without hitting a return statement. In this case, the return value is a special value

er
called None:
>>> print absolute_value(0) ne
None

None is the unique value of a type called the NoneType:


gi
>>> type(None)
En

All Python functions return None whenever they do not return another value.
rn

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized.
ea

Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory.
.L

The lifetime of variables inside a function is as long as the function executes.


They are destroyed once we return from the function. Hence, a function does not
w

remember the value of a variable from its previous calls.


ww

Eg:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
14

Visit For Local Scope and Local Variables


More : www.LearnEngineering.in
A local variable is a variable that is only accessible from within a given function. Such
variables are said to have local scope .

n
g. i
in
er
Global Variables and Global Scope ne
A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope .
gi
En
rn
ea
w .L

Variable max is defi ned outside func1 and func2 and therefore “global” to each.
ww

Function Composition
As you should expect by now, you can call one function from within another. This ability
is called composition.
As an example, we’ll write a function that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter point
is in xp and yp. The first step is to find the radius of the circle, which is the distance between the
two points. Fortunately, we’ve just written a function, distance, that does just that, so now all we
have to do is use it: Visit For More : www.LearnEngineering.in
www.rejinpaul.com
15

Visit For radius = distance(xc, yc, xp, yp)


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

return result Wrapping that up in a function, we get:


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

n
g. i
We called this function area2 to distinguish it from the area function defined earlier.
There can only be one function with a given name within a given module. The temporary

in
variables radius and result are useful for development and debugging, but once the program is
working, we can make it more concise by composing the function calls:

er
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp)) ne
STRINGS
gi
A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
En

>>> fruit = 'banana'


>>> letter = fruit[1]
rn

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
ea

sequence you want (hence the name).


But you might not get what you expect:
>>> print letter
.L

a
w

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the
index is an offset from the beginning of the string, and the offset of the first letter is zero.
ww

>>> letter = fruit[0]


>>> print letter
b

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the
2th(“two-eth”) letter.
You can use any expression, including variables and operators, as an index, but the value
of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
16

Visit For len


More : www.LearnEngineering.in
len is a built-in function that returns the number of characters in a string:
>>> fruit = 'banana'
>>> len(fruit)
6

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

n
The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since

g. i
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:

in
>>> last = fruit[length-1]
>>> print last

er
a

Alternatively, you can use negative indices, which count backward from the end of the
ne
string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,
and so on.
gi
String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
En

>>> s = 'Monty Python'


>>> print s[0:5]
Monty
rn

>>> print s[6:12]


Python
ea

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
.L

it might help to imagine the indices pointing between the characters, as in Figure 8.1.
If you omit the first index (before the colon), the slice starts at the beginning of the string.
w

If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
ww

>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
''
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
17

An empty string contains


Visit For More : www.LearnEngineering.in no characters and has length 0, but other than that, it is the same
as any other string.

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 “object” in this case is the string and the “item” is the character you tried to assign.

n
For now, an object is the same thing as a value, but we will refine that definition later. An item

g. i
is one of the values in a sequence.
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:

in
>>> greeting = 'Hello, world!'

er
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world! ne
This example concatenates a new first letter onto a slice of greeting. It has no effect on
gi
the original string.
En

String methods
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
rn

uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().
ea

>>> word = 'banana'


>>> new_word =
word.upper()
.L

>>> print new_word


BANANA
w

This form of dot notation specifies the name of the method, upper, and the name of the
ww

string to apply the method to, word. The empty parentheses indicate that this method
takes no argument.
A method call is called an invocation; in this case, we would say that we are invoking
upper on the word.
As it turns out, there is a string method named find that is remarkably similar to the
function we wrote:
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
18

In this example, we invoke find


Visit For More : www.LearnEngineering.in on word and pass the letter we are looking for as a
parameter.
Actually, the find method is more general than our function; it can find substrings, not
just characters:
>>> word.find('na')
2

It can take as a second argument the index where it should start:


>>> word.find('na', 3)
4

n
And as a third argument the index where it should stop:

g. i
>>> name = 'bob'
>>> name.find('b', 1, 2)

in
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).

er
String comparison ne
The relational operators work on strings. To see if two strings are equal:
if word == 'banana':
gi
print 'All right, bananas.'

Other relational operations are useful for putting words in alphabetical order:
En

if word < 'banana':


print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
rn

print 'Your word,' + word + ', comes after banana.'


else:
ea

print 'All right, bananas.'


.L

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

before banana.
A common way to address this problem is to convert strings to a standard format, such as
ww

all lowercase, before performing the comparison. Keep that in mind in case you have to
defend yourself against a man armed with a Pineapple.

Visit For More : www.LearnEngineering.in


www.rejinpaul.com
19

Visit For Program


More : www.LearnEngineering.in
1. Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7
# uncomment to take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero

n
if num < 0:

g. i
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")

in
else:

er
for i in range(1,num + 1):
factorial = factorial*i
ne
print("The factorial of",num,"is",factorial)

2. Python program to find the factorial of a number using recursion.


gi
En

def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
rn

if n == 1:
return n
ea

else:
return n*recur_factorial(n-1)
.L

# Change this value for a different result


w

num = 7
ww

# uncomment to take input from the user


#num = int(input("Enter a number: "))

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
Visit For More : www.LearnEngineering.in
print("The factorial of",num,"is",recur_factorial(num))
www.rejinpaul.com
20

Visit For More3.: www.LearnEngineering.in


Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user

n
#num1 = float(input("Enter first number: "))

g. i
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

in
if (num1 >= num2) and (num1 >= num3):

er
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
ne
largest = num3
gi
En

print("The largest number between",num1,",",num2,"and",num3,"is",largest)


rn

4. Python program to find the sum of natural numbers up to n where n is provided by user
ea

# change this value for a different result


num = 16
.L

# uncomment to take input from the user


w

#num = int(input("Enter a number: "))


ww

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
21

Visit For More5.: www.LearnEngineering.in


Python program to check if the input number is prime or not

num = 407

# take input from the user


# num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:

n
# check for factors

g. i
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")

in
print(i,"times",num//i,"is",num)

er
break
else:
print(num,"is a prime number")
ne
# if input number is less than
gi
# or equal to 1, it is not prime
En

else:
print(num,"is not a prime number")
rn

6. Program to display the Fibonacci sequence up to n-th term where n is provided by the
user
ea

# change this value for a different result


.L

nterms = 10
w

# uncomment to take input from the user


#nterms = int(input("How many terms? "))
ww

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
Visit For More : www.LearnEngineering.in
elif nterms == 1:
www.rejinpaul.com
22

print("Fibonacci
Visit For More sequence upto",nterms,":")
: www.LearnEngineering.in
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2

n
n2 = nth

g. i
count += 1

7. Python Program to Check Armstrong Number

in
er
num = 1634

# Changed num variable to string,


ne
# and calculated the length (number of digits)
gi
order = len(str(num))
En

# initialize sum
sum = 0
rn

# find the sum of the cube of each digit


ea

temp = num
while temp > 0:
.L

digit = temp % 10
sum += digit ** order
w

temp //= 10
ww

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

8. Python program to check if the input number is odd or even.

# A number is even if division by 2 give a remainder of 0.


# If remainder is 1, it is odd number. Visit For More : www.LearnEngineering.in
www.rejinpaul.com
23

Visit For More : www.LearnEngineering.in


num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

9. Program to add two matrices using nested loop

n
X = [[12,7,3],

g. i
[4 ,5,6],
[7 ,8,9]]

in
Y = [[5,8,1],

er
[6,7,3],
[4,5,9]]

result = [[0,0,0],
ne
[0,0,0],
gi
[0,0,0]]
En

# iterate through rows


for i in range(len(X)):
rn

# iterate through columns


for j in range(len(X[0])):
ea

result[i][j] = X[i][j] + Y[i][j]


.L

for r in result:
print(r)
w

10. Program to multiply two matrices using nested loops


ww

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
Visit For More : www.LearnEngineering.in
# result is 3x4
www.rejinpaul.com
24

result = [[0,0,0,0],
Visit For More : www.LearnEngineering.in
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y

n
for k in range(len(Y)):

g. i
result[i][j] += X[i][k] * Y[k][j]

for r in result:

in
print(r)

er
11. Program to transpose a matrix using nested loop

X = [[12,7],
ne
[4 ,5],
gi
[3 ,8]]
En

result = [[0,0,0],
[0,0,0]]
rn

# iterate through rows


ea

for i in range(len(X)):
# iterate through columns
.L

for j in range(len(X[0])):
result[j][i] = X[i][j]
w

for r in result:
ww

print(r)

12. Program to sort alphabetically the words form a string provided by the user

# change this value for a different result


my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user


#my_str = input("Enter a string: ")
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
25

# breakdown the string into


Visit For More : www.LearnEngineering.in a list of words
words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")

n
for word in words:

g. i
print(word)

13. Python program to find the H.C.F of two input number

in
er
# define a function
def computeHCF(x, y):

# choose the smaller number


ne
if x > y:
gi
smaller = y
En

else:
smaller = x
for i in range(1, smaller+1):
rn

if((x % i == 0) and (y % i == 0)):


hcf = i
ea

return hcf
.L

num1 = 54
w

num2 = 24
ww

# take input from the user


# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

14. Linear search

list = [4,1,2,5,3]
Visit For More : www.LearnEngineering.in
#set up array
www.rejinpaul.com
26

search = int(input("Enter
Visit For More : www.LearnEngineering.in search number"))
# ask for a number
for i in range(0,len(list)):
# repeat for each item in list
if search==list[i]:
#if item at position i is search time
print(str(search) + " found at position " + str(i))
#report find

n
15. Binary search

g. i
def binary_search(item_list,item):
first = 0
last = len(item_list)-1

in
found = False

er
while( first<=last and not found):
mid = (first + last)//2
ne
if item_list[mid] == item :
found = True
else:
gi
if item < item_list[mid]:
En

last = mid - 1
else:
first = mid + 1
rn

return found
ea

print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
.L

16. Program to find Fibonacci series upto n


w

>>> def fib(n): # write Fibonacci series up to n


ww

... """Print a Fibonacci series up to n."""


... a, b = 0, 1
... while a < n:
... print(a)
... a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
Visit For More : www.LearnEngineering.in
www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

UNIT IV LISTS, TUPLES, DICTIONARIE


Visit For Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
More : www.LearnEngineering.in
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, mergesort, histogram.

LISTS
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
squarebrackets ([ and ]):
[10, 20, 30, 40]

.in
['crunchy frog', 'ram bladder', 'lark vomit']

ng
The first example is a list of four integers. The second is a list of three strings. The
elements of a list don’t have to be the same type. The following list contains a string, a float,
an integer, and (lo!) another list:

ri
['spam', 2.0, 5, [10, 20]] ee
A list within another list is nested. A list that contains no elements is called an empty
gin
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
En

>>> numbers = [17, 123]


>>> empty = []
>>> print cheeses, numbers, empty
arn

['Cheddar', 'Edam', 'Gouda'] [17, 123] []

Lists are mutable


Le

The syntax for accessing the elements of a list is the same as for accessing the
characters of a string—the bracket operator. The expression inside the brackets specifies the
w.

index.
Remember that the indices start at 0:
>>> print cheeses[0]
ww

Cheddar

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 1


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

Unlike strings, lists are mutable. When the bracket operator appears on the left side of
Visit For anassignment, it identifies the element of the list that will be assigned.
More : www.LearnEngineering.in
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]

The one-eth element of numbers, which used to be 123, is now 5.


A list as a relationship between indices and elements. This relationship is called a
mapping; each index “maps to” one of the elements.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']

.in
>>> 'Edam' in cheeses
True

ng
>>> 'Brie' in cheeses
False

ri
Traversing a list ee
The most common way to traverse the elements of a list is with a for loop. The syntax
is the same as for strings:
gin

for cheese in cheeses:


print cheese
En

This works well if you only need to read the elements of the list. But if you want to
write or update the elements, you need the indices. A common way to do that is to combine
arn

the functions range and len:


for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
Le

This loop traverses the list and updates each element. len returns the number of
w.

elements in the list. range returns a list of indices from 0 to n 􀀀 1, where n is the length of the
list. Each time through the loop i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign the new value.
ww

A for loop over an empty list never executes the body:


for x in []:
print 'This never happens.'

Although a list can contain another list, the nested list still counts as a single element.
The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

List operations
The + operator concatenates lists:
>>> a = [1, 2, 3] Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 2


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

>>> b = [4, 5, 6]
Visit For >>>
More : cwww.LearnEngineering.in
=a+b
>>> print c
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example repeats the list [1, 2, 3]

.in
three times.

ng
List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']

ri
>>> t[1:3] ee
['b', 'c']
>>> t[:4]
gin
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
En

If you omit the first index, the slice starts at the beginning. If you omit the second, the
slice goes to the end. So if you omit both, the slice is a copy of the whole list.
arn

>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Le

Since lists are mutable, it is often useful to make a copy before performing operations
that fold, spindle or mutilate lists.
w.

A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
ww

>>> print t
['a', 'x', 'y', 'd', 'e', 'f']

List methods
Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 3


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

extend takes a list as an argument and appends all of the elements:


Visit For >>>
More : t1 = ['a', 'b', 'c']
www.LearnEngineering.in
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.


sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t

.in
['a', 'b', 'c', 'd', 'e']

ng
List methods are all void; they modify the list and return None.
List Loop
In Python lists are considered a type of iterable . An iterable is a data type that can

ri
return its elements separately, i.e., one at a time.
ee
for <item> in <iterable>:
<body>
gin
Eg:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
En

...print("Hi "+ name +"!")

Map, filter and reduce


arn

To add up all the numbers in a list, you can use a loop like this:
def add_all(t):
total = 0
Le

for x in t:
total += x
w.

return total

total is initialized to 0. Each time through the loop, x gets one element from the list.
ww

The += operator provides a short way to update a variable. This augmented assignment
statement:
total += x
is equivalent to:
total = total + x

As the loop executes, total accumulates the sum of the elements; a variable used this
way is sometimes called an accumulator.
Adding up the elements of a list is such a common operation that Python provides it as a
built-in function, sum:
>>> t = [1, 2, 3] Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 4


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

>>> sum(t)
Visit For 6
More : www.LearnEngineering.in

An operation like this that combines a sequence of elements into a single value is
sometimescalled reduce.

Deleting elements
There are several ways to delete elements from a list. If you know the index of the
elementyou want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t

.in
['a', 'c']
>>> print x

ng
b

pop modifies the list and returns the element that was removed. If you don’t provide

ri
an index, it deletes and returns the last element. ee
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
gin
>>> del t[1]
>>> print t
['a', 'c']
En

If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
arn

>>> t.remove('b')
>>> print t
['a', 'c']
Le

The return value from remove is None.


w.

To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
ww

>>> print t
['a', 'f']

As usual, the slice selects all the elements up to, but not including, the second index.

Lists and strings


A string is a sequence of characters and a list is a sequence of values, but a list of
characters is not the same as a string. To convert from a string to a list of characters, you can
use list:
>>> s = 'spam'
>>> t = list(s) Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 5


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

>>> print t
Visit For ['s',
More'p', 'a', 'm']
: www.LearnEngineering.in
Because list is the name of a built-in function, you should avoid using it as a variable
name. I also avoid l because it looks too much like 1. So that’s why I use t.
The list function breaks a string into individual letters. If you want to break a string
into words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
An optional argument called a delimiter specifies which characters to use as word
boundaries.

.in
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'

ng
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

ri
join is the inverse of split. It takes a list of strings and concatenates the elements. join
ee
is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
gin
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
En

In this case the delimiter is a space character, so join puts a space between words. To
concatenate strings without spaces, you can use the empty string, '', as a delimiter.
arn

Objects and values


If we execute these assignment statements:
Le

a = 'banana'
b = 'banana'
w.

We know that a and b both refer to a string, but we don’t know whether they refer to
the same string. There are two possible states, in one case, a and b refer to two different
ww

objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is operator.

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 6


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

In this example, Python only created one string object, and both a and b refer to it. But
Visit For when
More : you create two lists, you get two objects:
www.LearnEngineering.in
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In this case we would say that the two lists are equivalent, because they have the
same elements,but not identical, because they are not the same object. If two objects are
identical, they are also equivalent, but if they are equivalent, they are not necessarily
identical. Until now, we have been using “object” and “value” interchangeably, but it is more
precise to say that an object has a value. If you execute [1,2,3], you get a list object whose

.in
value is a sequence of integers. If another list has the same elements, we say it has the same
value, but it is not the same object.

ng
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same

ri
object: ee
>>> a = [1, 2, 3]
>>> b = a
gin
>>> b is a
True
En

The association of a variable with an object is called a reference. In this example,


there are two references to the same object.
An object with more than one reference has more than one name, so we say that the
arn

object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
Le
w.
ww

>>> b[0] = 17
>>> print a
[17, 2, 3]

Although this behavior can be useful, it is error-prone. In general, it is safer to avoid


aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana'
b = 'banana'

It almost never makes a difference whether a and b refer Visit


to theForsame string or not.
More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 7


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

Coloning Lists
Visit For More• : www.LearnEngineering.in
Cloning means making an exact but separate copy
• create a new list and copy every element
Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

Output: [10, 22, 44, 23, 4]


[10, 22, 44, 23, 4]

.in
List arguments
When you pass a list to a function, the function gets a reference to the list. If the

ng
function modifies a list parameter, the caller sees the change. For example, delete_head
removes the first element from a list:
def delete_head(t):

ri
del t[0] ee
Here’s how it is used:
gin
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
En

['b', 'c']

The parameter t and the variable letters are aliases for the same object.
arn

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:
Le

>>> t1 = [1, 2]
>>> t2 = t1.append(3)
w.

>>> print t1
[1, 2, 3]
>>> print t2
ww

None
>>> t3 = t1 + [4]
>>> print t3
[1, 2, 3, 4]

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:
def bad_delete_head(t):
t = t[1:] # WRONG!
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 8


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

The slice operator creates a new list and the assignment makes t refer to it, but none of
Visit For that
Morehas any effect on the list that was passed as an argument.
: www.LearnEngineering.in
An alternative is to write a function that creates and returns a new list. For example, tail
returns all but the first element of a list:
def tail(t):
return t[1:]

This function leaves the original list unmodified. Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']

.in
TUPLES

ng
Tuples are immutable
A tuple is a sequence of values. The values can be any type, and they are indexed by

ri
integers, so in that respect tuples are a lot like lists. The important difference is that tuples are
ee
immutable. Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
gin

Although it is not necessary, it is common to enclose tuples in parentheses:


>>> t = ('a', 'b', 'c', 'd', 'e')
En

To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
arn

>>> type(t1)
<type 'tuple'>
Le

A value in parentheses is not a tuple:


>>> t2 = ('a')
w.

>>> type(t2)
<type 'str'>
ww

Another way to create a tuple is the built-in function tuple. With no argument, it creates an
empty tuple:
>>> t = tuple()
>>> print t
()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's') Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 9


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

Visit For Because tuple is the name of a


More : www.LearnEngineering.in built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

And the slice operator selects a range of elements.


>>> print t[1:3]
('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:

.in
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

ng
You can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('A',) + t[1:]

ri
>>> print t ee
('A', 'b', 'c', 'd', 'e')
gin
Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments,
you have to use a temporary variable. For example, to swap a and b:
En

>>> temp = a
>>> a = b
>>> b = temp
arn

This solution is cumbersome; tuple assignment is more elegant:


>>> a, b = b, a
Le

The left side is a tuple of variables; the right side is a tuple of expressions. Each value
w.

is assigned to its respective variable. All the expressions on the right side are evaluated before
any of the assignments.
The number of variables on the left and the number of values on the right have to be the
ww

same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack

More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, you could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain. Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 10


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

>>> print uname


Visit For monty
More : www.LearnEngineering.in
>>> print domain
python.org

Tuples as return values


A function can only return one value, but if the value is a tuple, the effect is the same
as returning multiple values. For example, if you want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values,
the quotient and remainder. You can store the result as a tuple:

.in
>>> t = divmod(7, 3)
>>> print t

ng
(2, 1)

Or use tuple assignment to store the elements separately:

ri
>>> quot, rem = divmod(7, 3) ee
>>> print quot
2
gin
>>> print rem
1
En

Here is an example of a function that returns a tuple:


def min_max(t):
return min(t), max(t)
arn

max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.
Le

Variable-length argument tuples


w.

Functions can take a variable number of arguments. A parameter name that begins
with * gathers arguments into a tuple. For example, printall takes any number of arguments
and prints them:
ww

def printall(*args):
print args

The gather parameter can have any name you like, but args is conventional. Here’s howthe
function works:
>>> printall(1, 2.0, '3')
(1, 2.0, '3')

The complement of gather is scatter. If you have a sequence of values and you want
to pass it to a function as multiple arguments, you can use the * operator. For example,
divmod takes exactly two arguments; it doesn’t work with a tuple:
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 11


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

>>> t = (7, 3)
Visit For >>>
More : divmod(t)
www.LearnEngineering.in
TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:


>>> divmod(*t)
(2, 1)
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3

.in
Write a function called sumall that takes any number of arguments and returns their sum.

ng
Lists and tuples
zip is a built-in function that takes two or more sequences and “zips” them into a list
of tuples where each tuple contains one element from each sequence. In Python 3, zip returns

ri
an iterator of tuples, but for most purposes, an iterator behaves like a list.
ee
This example zips a string and a list:
gin
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
En

[('a', 0), ('b', 1), ('c', 2)]

The result is a list of tuples where each tuple contains a character from the string and the
arn

corresponding element from the list.


If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk')
Le

[('A', 'E'), ('n', 'l'), ('n', 'k')]


w.

You can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
ww

print number, letter

Each time through the loop, Python selects the next tuple in the list and assigns the elements
to letter and number. The output of this loop is:
0a
1b
2c

If you combine zip, for and tuple assignment, you get a useful idiom for traversing two
(or more) sequences at the same time. For example, has_match takes two sequences, t1
Visit
and t2, and returns True if there is an index i such that t1[i] ==For More : www.LearnEngineering.in
t2[i]:

St.Joseph’s Institute of Technology Dept. Of IT Page 12


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

def has_match(t1, t2):


Visit For for
Morex,: ywww.LearnEngineering.in
in zip(t1, t2):
if x == y:
return True
return False

If you need to traverse the elements of a sequence and their indices, you can use the built-in
function enumerate:
for index, element in enumerate('abc'):
print index, element
The output of this loop is:
0a

.in
1b
2c

ng
Again.

Dictionaries and tuples

ri
Dictionaries have a method called items that returns a list of tuples, where each tuple
ee
is a key-value pair.
>>> d = {'a':0, 'b':1, 'c':2}
gin
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
En

As you should expect from a dictionary, the items are in no particular order. In
Python3, items returns an iterator, but for many purposes, iterators behave like lists. Going in
the other direction, you can use a list of tuples to initialize a new dictionary:
arn

>>> t = [('a', 0), ('c', 2), ('b', 1)]


>>> d = dict(t)
>>> print d
Le

{'a': 0, 'c': 2, 'b': 1}


w.

Combining dict with zip yields a concise way to create a dictionary:


>>> d = dict(zip('abc', range(3)))
>>> print d
ww

{'a': 0, 'c': 2, 'b': 1}

The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to
an existing dictionary. Combining items, tuple assignment and for, you get the idiom for
traversing the keys and values of a dictionary:
for key, val in d.items():
print val, key

The output of this loop is:


0a
2c Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 13


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

1b
Visit For Again.
More : www.LearnEngineering.in

It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For
example, a telephone directory might map from last-name, first-name pairs to telephone
numbers. Assuming that we have defined last, first and number, we could write:
directory[last,first] = number

The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary.

.in
ri ng
ee
for last, first in directory:
gin
print first, last, directory[last,first]

This loop traverses the keys in directory, which are tuples. It assigns the elements of
En

each tuple to last and first, then prints the name and corresponding telephone number. There
are two ways to represent tuples in a state diagram. The more detailed version shows the
arn

indices and elements just as they appear in a list.

Comparing tuples
Le

The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not
w.

considered (even if they are really big).


>>> (0, 1, 2) < (0, 3, 4)
ww

True
>>> (0, 1, 2000000) < (0, 3, 4)
True

The sort function works the same way. It sorts primarily by first element, but in the
caseof a tie, it sorts by second element, and so on.

This feature lends itself to a pattern called DSU for


Decorate a sequence by building a list of tuples with one or more sort keys preceding the
elements from the sequence,
Sort the list of tuples, and Visit For More : www.LearnEngineering.in
Undecorate by extracting the sorted elements of the sequence.

St.Joseph’s Institute of Technology Dept. Of IT Page 14


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

Visit For For


Moreexample, suppose you have
: www.LearnEngineering.in a list of words and you want to sort them from longest to
shortest:
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res

.in
The first loop builds a list of tuples, where each tuple is a word preceded by its length.

ng
sort compares the first element, length, first, and only considers the second element to break
ties. The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order of

ri
length. ee
PYTHON DICTIONARY
gin
Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
En

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
arn

An item has a key and the corresponding value expressed as a pair, key: value. While
values can be of any data type and can repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and must be unique.
Le

# empty dictionary
w.

my_dict = {}

# dictionary with integer keys


ww

my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 15


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

As you can see above, we can also create a dictionary using the built-in function dict().
Visit For More : www.LearnEngineering.in
How to access elements from a dictionary?
While indexing is used with other container types to access values, dictionary uses
keys. Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key
is not found.
my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

.in
# Output: 26
print(my_dict.get('age'))

ng
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')

ri
# my_dict['address'] ee
OUTPUT: Jack
gin
26
How to change or add elements in a dictionary?
Dictionary are mutable. We can add new items or change the value of existing items
En

using assignment operator.


If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
arn

my_dict = {'name':'Jack', 'age': 26}

# update value
Le

my_dict['age'] = 27
w.

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)
ww

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

When you run the program, the output will be:


{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 16


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

How to delete or remove elements from a dictionary?


We can remove a particular item in a dictionary by using the method pop(). This
Visit For More : www.LearnEngineering.in
method removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key,
value) form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item


# Output: 16

.in
print(squares.pop(4))

ng
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)

ri
# remove an arbitrary item ee
# Output: (1, 1)
print(squares.popitem())
gin

# Output: {2: 4, 3: 9, 5: 25}


print(squares)
En

# delete a particular item


del squares[5]
arn

# Output: {2: 4, 3: 9}
print(squares)
Le

# remove all items


w.

squares.clear()

# Output: {}
ww

print(squares)

# delete the dictionary itself


del squares

# Throws Error
# print(squares)

When you run the program, the output will be:


16
{1: 1, 2: 4, 3: 9, 5: 25} Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 17


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

(1, 1)
Visit For {2:
More4,: www.LearnEngineering.in
3: 9, 5: 25}
{2: 4, 3: 9}
{}

Python Dictionary Methods


Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.
Python Dictionary Methods
Method Description
clear() Remove all items form the dictionary.

.in
copy() Return a shallow copy of the dictionary.
Return a new dictionary with keys from seq and value equal to v

ng
fromkeys(seq[, v])
(defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).

ri
items() Return a new view of the dictionary's items (key, value).
ee
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not found. If
gin
pop(key[,d])
d is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
En

dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value
setdefault(key[,d])
of d and return d (defaults to None).
arn

Update the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.
Le

values() Return a new view of the dictionary's values


w.

Here are a few example use of these methods.

marks = {}.fromkeys(['Math','English','Science'], 0)
ww

# Output: {'English': 0, 'Math': 0, 'Science': 0}


print(marks)

for item in marks.items():


print(item)

# Output: ['English', 'Math', 'Science']


list(sorted(marks.keys()))

Output: {'English': 0, 'Math': 0, 'Science': 0} Visit For More : www.LearnEngineering.in


('English', 0)
St.Joseph’s Institute of Technology Dept. Of IT Page 18
www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

('Math', 0)
Visit For ('Science', 0)
More : www.LearnEngineering.in
Out[1]: ['English', 'Math', 'Science']

Built-in Functions with Dictionary


Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks.
Built-in Functions with Dictionary
Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
Return True if any key of the dictionary is true. If the dictionary is empty, return

.in
any()
False.
len() Return the length (the number of items) in the dictionary.

ng
cmp() Compares items of two dictionaries.
sorted() Return a new sorted list of keys in the dictionary.

ri
ee
Here are some examples that uses built-in functions to work with dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
gin
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
En

print(sorted(squares))
Output: 5
[1, 3, 5, 7, 9]
arn

ADVANCED LIST PROCESSING


Le

List Comprehension
List comprehension is an elegant and concise way to create new list from an existing
w.

list in Python.
List comprehension consists of an expression followed by for statement inside square
ww

brackets.
Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]


print(pow2)

This code is equivalent to


pow2 = []
for x in range(10):
pow2.append(2 ** x) Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 19


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

Visit For A list: www.LearnEngineering.in


More comprehension can optionally contain more for or if statements. An optional if
statement can filter out items for the new list.
Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]


>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]

.in
['Python Language', 'Python Programming', 'C Language', 'C Programming']

ng
ILLUSTRATIVE PROGRAM
1. SELECTION SORT PROGRAM

ri
data = []
print('Selection Sort :')
ee
n = int(raw_input('Enter Number of Elements in the Array: '))
gin
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
En

print('Original Array :')


print(data)
print('Intermediate s :')
arn

for i in range(0,n-1):
small=int(data[i])
pos=i
Le

for j in range(i+1,n):
if int(data[j])<small:
small=int(data[j])
w.

pos=j
temp=data[i]
ww

data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)
Insertion sort
2. INSERTION SORT PROGRAM

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))
Visit For More : www.LearnEngineering.in
data.append(x)

St.Joseph’s Institute of Technology Dept. Of IT Page 20


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

print('Original Array :')


print(data)
Visit For Moreprint('Intermediate
: www.LearnEngineering.in
s :')
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)

3. MERGE SORT PROGRAM

.in
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:

ng
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

ri
mergeSort(lefthalf) ee
mergeSort(righthalf)
i=0
j=0
gin
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
En

i=i+1
else:
alist[k]=righthalf[j]
arn

j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
Le

i=i+1
k=k+1
while j < len(righthalf):
w.

alist[k]=righthalf[j]
j=j+1
k=k+1
ww

print("Merging ",alist)
data = []
print('Merge 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 s :')
mergeSort(data)
print('Sorted Array is:')
print(data)
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 21


www.rejinpaul.com
GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING 2017-2018

4. HISTOGRAM PROGRAM
Visit For More : www.LearnEngineering.in
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])

Output:
**
***

.in
******
*****

ri ng
ee
gin
En
arn
Le
w.
ww

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. Of IT Page 22


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

UNIT V FILES, MODULES, PACKAGES


Files and exception: text files, reading and writing files, format operator; command line
Visit For arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
More : www.LearnEngineering.in
programs: word count, copy file.

FILES
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed.

.in
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)

ng
3. Close the file

ri
Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also
ee
called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
gin
>>> f = open("C:/Python33/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read
En

'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode
or binary mode.
arn

The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like image or exe files.
Le

Python File Modes


w.

Mode Description
'r' Open a file for reading. (default)
ww

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and w

f = open("test.txt") # equivalent to 'r' or 'rt' Visit For More : www.LearnEngineering.in


f = open("test.txt",'w') # write in text mode
St.Joseph’s Institute of Technology Dept. of IT 1
www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

f = open("img.bmp",'r+b') # read and write in binary mode

Visit For Hence, when working with


More : www.LearnEngineering.in files in text mode, it is highly recommended to specify the
encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')

Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the
close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.

.in
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()

ng
This method is not entirely safe. If an exception occurs when we are performing some

ri
operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
ee
f = open("test.txt",encoding = 'utf-8')
gin
# perform file operations
finally:
f.close()
En

This way, we are guaranteed that the file is properly closed even if an exception is raised,
arn

causing program flow to stop.


The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is exited.
Le

We don't need to explicitly call the close() method. It is done internally.


with open("test.txt",encoding = 'utf-8') as f:
# perform file operations
w.

Reading and writing


ww

A text file is a sequence of characters stored on a permanent medium like a hard drive, flash
memory, or CD-ROM.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>

If the file already exists, opening it in write mode clears out the old data and starts fresh,
so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
Visit For More : www.LearnEngineering.in
>>> fout.write(line1)

St.Joseph’s Institute of Technology Dept. of IT 2


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

Again, the file object keeps track of where it is, so if you call write again, it adds the new data
Visit For to the: www.LearnEngineering.in
More end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)

When you are done writing, you have to close the file.
>>> fout.close()

Format operator
The argument of write has to be a string, so if we want to put other values in a file, we have
to convert them to strings. The easiest way to do that is with str:

.in
>>> x = 52
>>> fout.write(str(x))

ng
An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.

ri
The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
ee
For example, the format sequence '%d' means that the second operand should be formatted as
an integer (d stands for “decimal”):
gin
>>> camels = 42
>>> '%d' % camels
'42'
En

The result is the string '42', which is not to be confused with the integer value 42.
arn

A format sequence can appear anywhere in the string, so you can embed a value in a
sentence:
>>> camels = 42
Le

>>> 'I have spotted %d camels.' % camels


'I have spotted 42 camels.'
w.

If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
ww

The following example uses '%d' to format an integer, '%g' to format a floating-point number
and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number of format sequences in the
string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)


TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
Visit For More : www.LearnEngineering.in
TypeError: illegal argument type for built-in operation

St.Joseph’s Institute of Technology Dept. of IT 3


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

Filenames and paths


directories (also called “folders”). Every running program
Files are organized into
Visit For More : www.LearnEngineering.in
has a “current directory,” which is the default directory for most operations. For example,
when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for
“operating system”). os.getcwd returns the name of the current directory:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale

cwd stands for “current working directory.” The result in this example is /home/dinsdale,

.in
which is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current

ng
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current

ri
directory. To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
ee
gin
os.path.exists checks whether a file or directory exists:
>>> os.path.exists('memo.txt')
True
En

If it exists, os.path.isdir checks whether it’s a directory:


arn

>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
Le

True

Similarly, os.path.isfile checks whether it’s a file.


w.

os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd)
ww

['music', 'photos', 'memo.txt']

To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. of IT 4


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

os.path.join takes a directory and a file name and joins them into a complete path.

Visit For More : www.LearnEngineering.in EXCEPTION


Python (interpreter) raises exceptions when it encounters errors. Error caused by not
following the proper structure (syntax) of the language is called syntax error or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax

Errors can also occur at runtime and these are called exceptions. They occur, for example,

.in
when a file we try to open does not exist (FileNotFoundError), dividing a number by zero
(ZeroDivisionError), module we try to import is not found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception object. If not

ng
handled properly, it prints a traceback to that error along with some details about why that
error occurred.

ri
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
ee
File "<interactive input>", line 1, in <module>
gin
ZeroDivisionError: division by zero

>>> open("imaginary.txt")
En

Traceback (most recent call last):


File "<string>", line 301, in runcode
arn

File "<interactive input>", line 1, in <module>


FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Le

Python Built-in Exceptions


Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that
are raised when corresponding errors occur. We can view all the built-in exceptions using the
w.

local() built-in functions as follows.


>>> locals()['__builtins__']
ww

This will return us a dictionary of built-in exceptions, functions and attributes.


Some of the common built-in exceptions in Python programming along with the error that
cause then are tabulated below.

Python Built-in Exceptions


Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functionsVisit
hitsFor
end-of-file condition.
More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. of IT 5


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

FloatingPointError Raised when a floating point operation fails.


GeneratorExit Raise when a generator's close() method is called.
Visit For More : www.LearnEngineering.in
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.

.in
Raised when result of an arithmetic operation is too large to be
OverflowError
represented.

ng
Raised when a weak reference proxy is used to access a garbage
ReferenceError
collected referent.

ri
RuntimeError Raised when an error does not fall under any other category.
ee
Raised by next() function to indicate that there is no further item to
StopIteration
be returned by iterator.
gin
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
En

TabError Raised when indentation consists of inconsistent tabs and spaces.


SystemError Raised when interpreter detects internal error.
arn

SystemExit Raised by sys.exit() function.


Raised when a function or operation is applied to an object of
TypeError
incorrect type.
Le

Raised when a reference is made to a local variable in a function or


UnboundLocalError
method, but no value has been bound to that variable.
w.

UnicodeError Raised when a Unicode-related encoding or decoding error occurs.


UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
ww

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.


UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
Raised when a function gets argument of correct type but improper
ValueError
value.
ZeroDivisionError Raised when second operand of division or modulo operation is zero.
We can handle these built-in and user-defined exceptions in Python using try, except and
finally statements.

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. of IT 6


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

Python Exception Handling


Visit For Python has many built-in exceptions
More : www.LearnEngineering.in which forces your program to output an error when
something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the calling
process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program come to a sudden, unexpected
halt.

Catching Exceptions in Python

.in
In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and the code that
handles exception is written in except clause.

ng
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.

ri
# import module sys to get the type of exception
import sys
ee
randomList = ['a', 0, 2]
gin

for entry in randomList:


try:
En

print("The entry is", entry)


r = 1/int(entry)
arn

break
except:
print("Oops!",sys.exc_info()[0],"occured.")
Le

print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
w.

Output
The entry is a
ww

Oops! <class 'ValueError'> occured.


Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop until the user enters an integer that has a valid reciprocal. The
Visit For More : www.LearnEngineering.in
portion that can cause exception is placed inside try block.

St.Joseph’s Institute of Technology Dept. of IT 7


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

If no exception occurs, except block is skipped and normal flow continues. But if any
exception occurs, it is caught by the except block.
Visit For Here, we print the name of the exception using ex_info() function inside sys module and ask
More : www.LearnEngineering.in
the user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.

try...finally
The try statement in Python can have an optional finally clause. This clause is
executed no matter what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working
with a file or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was

.in
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution.
Here is an example of file operations to illustrate this.

ng
try:
f = open("test.txt",encoding = 'utf-8')

ri
# perform file operations
finally:
f.close()
ee
gin
MODULES
Any file that contains Python code can be imported as a module. For example, suppose
you have a file named wc.py with the following code:
En

def linecount(filename):
count = 0
arn

for line in open(filename):


count += 1
return count
Le

print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
w.

>>> import wc
7
ww

Now you have a module object wc:


>>> print wc
<module 'wc' from 'wc.py'>
That provides a function called linecount:
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the
test code at the bottom. Normally when you import a module, it defines new functions but
it doesn’t execute them.
Programs that will be imported as modules often use the following idiom:
Visit For More : www.LearnEngineering.in
if __name__ == '__main__':

St.Joseph’s Institute of Technology Dept. of IT 8


www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

print linecount('wc.py')

Visit For __name__ is a built-in variable


More : www.LearnEngineering.inthat 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 is executed.
Otherwise, if the module is being imported, the test code is skipped.
Eg:
# import module
import calendar

yy = 2017
mm = 8

.in
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

ng
# display the calendar

ri
print(calendar.month(yy, mm))

PACKAGE
ee
A package is a collection of modules. A Python package can have sub-packages and
gin
modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
En

package in this file.


Here is an example. Suppose we are developing a game, one possible organization of
arn

packages and modules could be as shown in the figure below.


Le
w.
ww

Importing module from a package


We can import modules from packages using the dot (.) operator.
Visitexample,
For example, if want to import the start module in the above For More : itwww.LearnEngineering.in
is done as follows.
import Game.Level.start
St.Joseph’s Institute of Technology Dept. of IT 9
www.rejinpaul.com
GE8151 – Problem Solving and Python Programming 2017-2018

Now if this module contains a function named select_difficulty(), we must use the full name
Visit For to reference
More it.
: www.LearnEngineering.in
Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as
follows.
from Game.Level import start

We can now call the function simply as follows.


start.select_difficulty(2)

.in
Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from Game.Level.start import select_difficulty

ng
Now we can directly call this function.

ri
select_difficulty(2)
ee
Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding.
gin
While importing packages, Python looks in the list of directories defined in sys.path, similar
as for module search path.
En

ILLUSTRATION PROGRAM
arn

1. Word Count
import sys
file=open("/Python27/note.txt","r+")
wordcount={}
Le

for word in file.read().split():


if word not in wordcount:
wordcount[word] = 1
w.

else:
wordcount[word] += 1
file.close();
ww

print ("%-30s %s " %('Words in the File' , 'Count'))


for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))

Visit For More : www.LearnEngineering.in

St.Joseph’s Institute of Technology Dept. of IT 10

You might also like