Download as pdf or txt
Download as pdf or txt
You are on page 1of 133

GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

UNIT 1
ALGORITHMIC PROBLEM SOLVING
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, Basic
algorithms, flowcharts, and pseudocode for sequential, decision processing, and iterative
processing strategies, 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.

PROBLEM-SOLVING
Problem-solving is the systematic approach to defining the problem and creating several solutions.
The problem-solving process starts with the problem specifications and ends with a Correct program.

PROBLEM-SOLVING TECHNIQUES
The problem-solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem-Solving Techniques:
Problem-solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. programs

ALGORITHM
It is defined as a sequence of instructions that describe a method for solving a problem. In other
words, it is a step-by-step procedure for solving a problem.
Properties of Algorithms
• Should be written in simple English
• Each and every instruction should be precise and unambiguous.
• Instructions in an algorithm should not be repeated infinitely.
• An algorithm should conclude after a finite number of steps.
• Should have an endpoint
• Derived results should be obtained only after the algorithm terminates.

P a g e 1 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Qualities of a good algorithm


The following are the primary factors that are often used to judge the quality of the algorithms.
• Time – To execute a program, the computer system takes some amount of time. The lesser
time required, the better the algorithm.
• Memory – To execute a program, the computer system takes some amount of memory space.
The lesser memory required, the better the algorithm.
• Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem,
some of these may provide more accurate results than others, and such algorithms may be
suitable.
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
BUILDING BLOCKS OF ALGORITHMS (statements, state, control flow, functions)
Algorithms can be constructed from basic building blocks namely, sequence, selection, and iteration.
1. Statements:
A statement is a single action in a computer.
In a computer, statements might include some of the following actions
➢ input data information is given to the program
➢ process data-perform operation on a given input
➢ output data-processed result

2. State:
Transitioning from one process to another process under the specified condition within a time is
called a state.
3. Control flow:
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
a) sequence
b) selection
c) iteration
Sequence:
All the instructions are executed one after another is called sequence execution.

P a g e 2 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

a) Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based on the condition.
If the conditional test is true, one part of the program will be executed, otherwise, it will execute the
other part of the program.

Example
Write an algorithm to check whether he is
eligible to vote?
Step 1: Start
Step 2: Get the age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

b) Iteration:
In some programs, a certain set of statements are executed again and again based upon the
conditional tests. i.e. executed more than one time. This type of execution is called looping or
iteration.

P a g e 3 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

4. Functions:
A function is a subprogram that consists of a block of code(set of instructions) that performs a
particular task.
For complex problems, the problem is been divided into smaller and simpler tasks during algorithm
design.
Benefits of Using Functions
• Reduction in line of code
• code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability

Example
Algorithm for the addition of two numbers using function
Main function() sub function add()
Step 1: Start Step 1: Function start
Step 2: Call the function add() Step 2: Get a, b Values
Step 3: Stop Step 3: add c=a+b
Step 4: Print c
Step 5: Return

P a g e 4 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Main Program Sub Program

NOTATIONS
FLOW CHART
A flow chart is defined as a graphical representation of the logic for problem-solving.
The purpose of the flowchart is to make the logic of the program clear in a visual representation.

P a g e 5 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Rules for drawing a flowchart


• The flowchart should be clear, neat, and easy to follow.
• The flowchart must have a logical start and finish.
• Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow lines may leave
the decision symbol.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.


7. Intersection of flow lines should be avoided.

Advantages of flowchart:
i. Communication: - Flowcharts are a better way of communicating the logic of a system to all
concerned.
ii. Effective analysis: - With the help of a flowchart, the problem can be analyzed more
effectively.
iii. Proper documentation: - Program flowcharts serve as good program documentation, which
is needed for various purposes.
iv. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
v. Proper Debugging: - The flowchart helps in debugging process.
vi. Efficient Program Maintenance: - The maintenance of the operating program becomes easy
with the help of a flowchart. It helps the programmer to put efforts more efficiently into that
part.

P a g e 6 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Disadvantages of flow chart:


i. Complex logic: - Sometimes, the program logic is quite complicated. In that case, the
flowchart becomes complex and clumsy.
ii. Alterations and Modifications: - If alterations are required the flowchart may require re-
drawing completely.
iii. Reproduction: - As the flowchart symbols cannot be typed, reproduction of the flowchart
becomes a problem.
iv. Cost: For large applications the time and cost of flowchart drawing become costly.

PSEUDO CODE:
i. Pseudocode consists of short, readable, and formally styled English languages used to
explaining an algorithm.
ii. It does not include details like variable declaration, and subroutines.
iii. It is easier to understand for the programmer or nonprogrammer to understand the general
working of the program because it is not based on any programming language.
iv. It gives us a sketch of the program before actual coding.
v. It is not a machine-readable
vi. Pseudocode can’t be compiled and executed.
vii. There is no standard syntax for pseudo code.
Guidelines for writing pseudo code:
• Write one statement per line
• Capitalize the initial keyword
• Indent to the hierarchy
• End multiline structure
• Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. //: This keyword is used to represent a comment.
2. BEGIN, END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make a decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.

P a g e 7 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

The syntax for if else: Example: Greatest of two numbers


IF (condition)THEN BEGIN
statement READ a,b
... IF (a>b) THEN
ELSE DISPLAY a is greater
statement ELSE
... DISPLAY b is a greater
ENDIF END IF
END

The syntax for For: Example: Print n natural numbers


FOR( start-value to end-value) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END

The syntax for While: Example: Print n natural numbers


WHILE (condition) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END

Advantages:
• Pseudo is independent of any language; it can be used by most programmers.
• It is easy to translate pseudo code into a programming language.
• It can be easily modified as compared to a flowchart.
• Converting a pseudo code to a programming language is very easy compared with converting
a flowchart to a programming language.

Disadvantages:
• It does not provide a visual representation of the program’s logic.
• There are no accepted standards for writing pseudo codes.
• It cannot be compiled or executed.
• For a beginner, It is more difficult to follow the logic or write pseudo code as compared to a
flowchart.
P a g e 8 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END

PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer to perform specific
tasks. The programmers have to follow all the specified rules before writing a program using a
programming language. The user has to communicate with the computer using language that it can
understand.
Types of programming language
i. Machine language
ii. Assembly language
iii. High-level language

i. Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In machine language,
the different instructions are formed by taking different combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language that the computer understands. For executing any program
written in any programming language, the conversion to machine language is necessary. The program
written in machine language can be executed directly on a computer. In this case, any conversion
process is not required.
P a g e 9 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

High speed
The machine language program is translation free. Since the conversion time is saved, the execution
of the machine language program is extremely fast.
Disadvantage:
• It is hard to find errors in a program written in machine language.
• Writing programs in machine language is a time-consuming process.

Machine dependent: According to the architecture used, the computer differs from each other. So
machine language differs from computer to computer. So a program developed for a particular type of
computer may not run on other types of computer.
ii. Assembly language: To overcome the issues in programming language and make the
programming process easier, an assembly language is developed which is logically equivalent to
machine language but is easier for people to read, write and understand.
Assembly language is a symbolic representation of machine language. Assembly languages are
symbolic programming language that uses symbolic notation to represent machine language
instructions. They are called low-level languages because they are so closely related to machines.
Assembler
Assembler is the program that translates assembly language instruction into a machine language.
• Easy to understand and use.
• It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine depends on the architecture
of that computer.
Hard to learn
It is machine-dependent, so the programmer should have the hardware knowledge to create
applications using assembly language.
Less efficient
• Execution time of an assembly language program is more than machine language program.
• Because an assembler is needed to convert from assembly language to machine language.
iii. High-level language
The high-level language contains English words and symbols. The specified rules are to be followed
while writing a program in a high-level language. The interpreter or compilers are used for converting
these programs into machine-readable form.

P a g e 10 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Translating high-level language to machine language


The programs that translate high-level language into machine language are called interpreters or
compilers.
Compiler:
A compiler is a program that translates the source code written in a high-level language into object
code which is in the machine language program. A compiler reads the whole program written in a
high-level language and translates it to machine language. If any error is found it displays an error
message on the screen.
Interpreter:
An interpreter translates the high-level language program in line by line manner. The interpreter
translates a high-level language statement in a source program to a machine code and executes it
immediately before translating the next statement. When an error is found the execution of the program
is halted and an error message is displayed on the screen.
Advantages
• Readability High-level language is closer to natural language so they are easier to learn and
understand
• Machine-independent High-level language programs have the advantage of being portable
between machines.
• Easy debugging Easy to find and correct errors in a high-level language
Disadvantages
Less efficient The translation process increases the execution time of the program. Programs in the
high-level language require more memory and take more execution time to execute.
They are divided into the following categories:
1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Markup programming language
7. Concurrent programming language
8. Object-oriented programming language

P a g e 11 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

ALGORITHMIC PROBLEM SOLVING


Algorithmic problem solving is solving a problem that requires the formulation of an algorithm for
the solution.

Understanding the Problem


• It is the process of finding the input of the problem that the algorithm solves.
• It is very important to specify exactly the set of inputs the algorithm needs to handle.
• A correct algorithm does not work most of the time, but one that works correctly
for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device
• If the instructions are executed one after another, it is called a sequential algorithm.
• If the instructions are executed concurrently, it is called a parallel algorithm.

P a g e 12 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Choosing between Exact and Approximate Problem Solving


• The next principal decision is to choose between solving the problem exactly or solving it
approximately.
• Based on this, the algorithms are classified as exact algorithms and approximation algorithms.

Deciding a data structure:


• Data structure plays a vital role in designing and analyzing algorithms.
• Some of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance
• Algorithm+ Data structure=programs.

Algorithm Design Techniques


• An algorithm design technique (or “strategy” or “paradigm”) is a general approach to
solving problems algorithmically that applies to a variety of problems from different areas of
computing.
• Learning these techniques is of utmost importance for the following reasons.
• First, they provide guidance for designing algorithms for new problems,
• Second, algorithms are the cornerstone of computer science
Methods of Specifying an Algorithm
• Pseudocode is a mixture of a natural language and programming language-like constructs.
Pseudocode is usually more precise than natural language, and its usage often yields more
succinct algorithm descriptions.
• In the earlier days of computing, the dominant vehicle for specifying algorithms was
a flowchart, a method of expressing an algorithm by a collection of connected geometric
shapes containing descriptions of the algorithm’s steps.
• Programming language can be fed into an electronic computer directly. Instead, it needs to
be converted into a computer program written in a particular computer language. We can look
at such a program as yet another way of specifying the algorithm, although it is preferable to
consider it as the algorithm’s implementation.

Proving an Algorithm’s Correctness


• Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount
of time.
• A common technique for proving correctness is to use mathematical induction because an
algorithm’s iterations provide a natural sequence of steps needed for such proofs.
• It might be worth mentioning that although tracing the algorithm’s performance for a few
specific inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness
conclusively. But to show that an algorithm is incorrect, you need just one instance of its
input for which the algorithm fails.
P a g e 13 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Analyzing an Algorithm
1. Efficiency.
• Time efficiency, indicating how fast the algorithm runs,
• Space efficiency indicates how much extra memory it uses.
2. simplicity.
• An algorithm should be precisely defined and investigated with mathematical expressions.
• Simpler algorithms are easier to understand and easier to program.
• Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer programs. Programming an
algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical analysis of the
underlying algorithm. Such an analysis is based on timing the program on several inputs and then
analyzing the results obtained.

SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:

1. Iterations
2. Recursions
1. Iterations:
A sequence of statements is executed until a specified condition is true is called iterations.
[1] for loop
[2] While loop

Syntax for For: Example: Print n natural numbers


FOR( start-value to end-value) DO BEGIN
GET n
Statement INITIALIZE i=1
... FOR (i<=n) DO
ENDFOR PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
GET n
Statement INITIALIZE i=1
... WHILE(i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END

P a g e 14 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some specified condition has
been satisfied.
Algorithm for factorial of n numbers using recursion:
Main function: Sub function factorial(n):
Step1: Start Step1: if(n==1) then fact=1 return fact
Step2: Get n Step2: else fact=n*factorial(n-1) and return fact
Step3: call factorial(n)
Step4: print fact
Step5: Stop

P a g e 15 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Pseudo code for factorial using recursion:

Main function: Sub function factorial(n):


BEGIN IF(n==1) THEN
GET n fact=1
CALL factorial(n) RETURN fact
PRINT fact ELSE
BIN RETURN fact=n*factorial(n-1)

P a g e 16 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

MORE EXAMPLES
1. Write an algorithm to find area of a rectangle
Step 1: Start BEGIN
Step 2: get l,b values READ l,b
Step 3: Calculate A=l*b CALCULATE A=l*b
Step 4: Display A DISPLAY A
Step 5: Stop END

2. Write an algorithm for Calculating area and circumference of circle


BEGIN
Step 1: Start READ r
Step 2: get r value CALCULATE A and C
Step 3: Calculate A=3.14*r*r A=3.14*r*r
Step 4: Calculate C=2.3.14*r C=2*3.14*r
Step 5: Display A,C DISPLAY A
Step 6: Stop END

3. Write an algorithm for Calculating simple interest


Step 1: Start BEGIN
Step 2: get P, n, r value READ P, n, r
Step3:Calculate CALCULATE S
SI=(p*n*r)/100 SI=(p*n*r)/100
Step 4: Display S DISPLAY SI
Step 5: Stop END

P a g e 17 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

4. Write an algorithm for Calculating engineering cutoff


Step 1: Start BEGIN
Step2: get P,C,M value READ P,C,M
Step3:calculate CALCULATE
Cutoff= (P/4+C/4+M/2) Cutoff= (P/4+C/4+M/2)
Step 4: Display Cutoff DISPLAY Cutoff
Step 5: Stop END

5. To check greatest of two numbers

Step 1: Start BEGIN


Step 2: get a,b value READ a,b
Step 3: check if(a>b) IF (a>b) THEN
print a is greater DISPLAY a is greater
Step 4: else b is greater ELSE
Step 5: Stop DISPLAY b is greater
END IF
END

6. To check leap year or not


Step 1: Start BEGIN
Step 2: get y READ y
Step 3: if(y%4==0) print IF (y%4==0) THEN
leap year DISPLAY leap year
Step 4: else print not leap ELSE
year DISPLAY not leap year
Step 5: Stop END IF
END

P a g e 18 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

7. To check positive or negative number


Step 1: Start BEGIN
Step 2: get num READ num
Step 3: check if(num>0) IF (num>0) THEN
print a is positive DISPLAY num is
Step 4: else num is positive
negative ELSE
Step 5: Stop DISPLAY num is
negative
END IF
END

8. To check odd or even number


Step 1: Start BEGIN
Step 2: get num READ num
Step 3: check if(num%2==0) IF (num%2==0) THEN
print num is even DISPLAY num is even
Step 4: else num is odd ELSE
Step 5: Stop DISPLAY num is odd
END IF
END

9. To check greatest of three numbers


Step1: Start BEGIN
Step2: Get A, B, C READ a, b, c
Step3: if(A>B) goto IF (a>b) THEN
Step4 else goto step5 IF(a>c) THEN
Step4: If(A>C) DISPLAY a is greater
print A ELSE
else print C DISPLAY c is greater
Step5: If(B>C) END IF
print B ELSE
else print C IF(b>c) THEN
Step6: Stop DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END

P a g e 19 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

10. Write an algorithm to check whether given number is +ve, -ve or zero.

Step 1: Start BEGIN


Step 2: Get n value. GET n
Step 3: if (n ==0) IF(n==0) THEN
print “Given number is DISPLAY “ n is
Zero” Else goto step4 zero”
Step 4: if (n > 0) then ELSE
Print “Given number IF(n>0) THEN
is +ve” DISPLAY “n is
Step 5: else Print positive”
“Given number is -ve” ELSE
Step 6: Stop DISPLAY “n is
positive”
END IF
END IF
END

11. Write an algorithm to print all natural numbers up to n

Step 1: Start BEGIN


Step 2: get n value. GET n
Step 3: initialize i=1 INITIALIZE i=1
Step 4: if (i<=n) go to WHILE(i<=n) DO
step 5 else go to step 8 PRINT i
Step 5: Print i value i=i+1
step 6 : increment i value ENDWHILE
by 1 END
Step 7: go to step 4
Step 8: Stop

P a g e 20 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

12. Write an algorithm to print n odd numbers

Step 1: start BEGIN


step 2: get n value GET n
step 3: set initial value i=1 INITIALIZE i=1
step 4: check if(i<=n) goto WHILE(i<=n) DO
step 5 else goto step 8 PRINT i
step 5: print i value i=i+2
step 6: increment i value by ENDWHILE
2 END
step 7: goto step 4
step 8: stop

13. Write an algorithm to print n even numbers

Step 1: start BEGIN


step 2: get n value GET n
step 3: set initial value i=2 INITIALIZE i=2
step 4: check if(i<=n) goto WHILE(i<=n) DO
step 5 else goto step8 PRINT i
step 5: print i value i=i+2
step 6: increment i value by ENDWHILE
2 END
step 7: goto step 4
step 8: stop

P a g e 21 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

14. Write an algorithm to print squares of a number

Step 1: start BEGIN


step 2: get n value GET n
step 3: set initial value i=1 INITIALIZE i=1
step 4: check i value WHILE(i<=n) DO
if(i<=n) goto step 5 else PRINT i*i
goto step8 i=i+2
step 5: print i*i value ENDWHILE
step 6: increment i value by END
1
step 7: goto step 4
step 8: stop

15. Write an algorithm to print to print cubes of a number


Step 1: start BEGIN
step 2: get n value GET n
step 3: set initial value i=1 INITIALIZE i=1
step 4: check i value WHILE(i<=n) DO
if(i<=n) goto step 5 else PRINT i*i*i
goto step8 i=i+2
step 5: print i*i *i value ENDWHILE
step 6: increment i value END
by 1
step 7: goto step 4
step 8: stop

P a g e 22 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

16. Write an algorithm to find sum of a given number

Step 1: start BEGIN


step 2: get n value GET n
step 3: set initial value INITIALIZE i=1,sum=0
i=1, sum=0 WHILE(i<=n) DO
Step 4: check i value sum=sum+i
if(i<=n) goto step 5 else i=i+1
goto step8 ENDWHILE
step 5: calculate PRINT sum
sum=sum+i END
step 6: increment i value
by 1
step 7: goto step 4
step 8: print sum value
step 9: stop

17. Write an algorithm to find factorial of a given number

Step 1: start BEGIN


step 2: get n value GET n
step 3: set initial value i=1, INITIALIZE
fact=1 i=1,fact=1
Step 4: check i value if(i<=n) WHILE(i<=n) DO
goto step 5 else goto step8 fact=fact*i
step 5: calculate fact=fact*i i=i+1
step 6: increment i value by 1 ENDWHILE
step 7: goto step 4 PRINT fact
step 8: print fact value END
step 9: stop

P a g e 23 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range

Algorithm: Pseudocode:
Step1: Start BEGIN
Step 2: Declare hidden, guess COMPUTE hidden=random value in range
Step 3: Compute hidden= Choose a random READ guess
value in a range
IF guess=hidden, then
Step 4: Read guess
PRINT Guess is hit
Step 5: If guess=hidden, then
ELSE
Print Guess is hit
PRINT Guess not hit
Else
PRINT hidden
Print Guess not hit
END IF-ELSE
Print hidden
END
Step 6: Stop

Flowchart:

P a g e 24 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

2. Find the minimum in a list


Algorithm: Pseudocode:
Step 1: Start BEGIN READ n
Step 2: Read n FOR i=0 to n, then
Step 3:Initialize i=0 READ a[i]
Step 4: If i<n, then goto INCREMENT i
step 4.1, 4.2 else goto END FOR
step 5 Step4.1: Read a[i] COMPUTE min=a[0]
Step 4.2: i=i+1 goto step 4 FOR i=1 to n, then
Step 5: Compute min=a[0] IF a[i]<min, then
Step 6: Initialize i=1 CALCULATE min=a[i]
Step 7: If i<n, then go to step 8 else goto step 10 INCREMENT i
Step 8: If a[i]<min, then goto ELSE
step 8.1,8.2 else goto 8.2 INCREMENT i
Step 8.1: min=a[i] END IF-ELSE
Step 8.2: i=i+1 goto 7 END FOR
Step 9: Print min PRINT min
Step 10: Stop END

P a g e 25 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Flowchart:

P a g e 26 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

3. Insert a card in a list of sorted cards

Algorithm: Pseudocode:
Step 1: Start BEGIN
Step 2: Read n READ n
Step 3:Initialize i=0 FOR i=0 to n, then
Step 4: If i<n, then goto step 4.1, 4.2 else goto READ a[i]
step 5
INCREMENT i
Step4.1: Read a[i]
END FOR
Step 4.2: i=i+1 goto step 4
READ item
Step 5: Read item
FOR i=n-1 to 0 and item<a[i], then
Step 6: Calculate i=n-1
CALCULATE a[i+1]=a[i]
Step 7: If i>=0 and item<a[i], then go to step
DECREMENT i
7.1, 7.2 else goto step 8
END FOR
Step 7.1: a[i+1]=a[i]
COMPUTE a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
COMPUTE n=n+1
Step 8: Compute a[i+1]=item
FOR i=0 to n, then
Step 9: Compute n=n+1
PRINT a[i]
Step 10: If i<n, then goto step 10.1, 10.2 lse
goto st 11 INCREMENT i
Step10.1: Print a[i] END FOR
Step10.2: i=i+1 goto step 10 END
Step 11: Stop

P a g e 27 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

Flowchart:

P a g e 28 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

4. Tower of Hanoi
Algorithm: Pseudcode:
Step 1: Start BEGIN
Step 2: Read n READ n
Step 3: Calculate move=pow(2,n)-1 CALCULATE move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) FUNCTION T(n,Beg,Aux,End) Recursiv ly
recursively until n=0 until n=0
Step 4.1: If n=0, then goto PROCEDURE
step 5 else goto step IF n=0 then,
4.2 Step No disk to move
4.2: T(n-1,Beg,End,Aux) T(1,Beg,Aux,End) , Else
Move disk from source to desti ation T(n-
T(n-1,Beg,End,Aux)
1,Aux,Beg,End)
T(1,Beg,Aux,End), move isk from source to
Step 5: Stop
destination
T(n-1,Aux,Beg,En )
END PROCEDURE
END

Flowchart:

P a g e 29 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

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

P a g e 30 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

P a g e 31 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

P a g e 32 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1

P a g e 33 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

UNIT 2
INTRODUCTION TO PYTHON
Python Introduction, Technical Strength of Python, Python interpreter and interactive mode,
Introduction to colab, pycharm, and jupyter idle(s), Values and types: int, float, boolean, string,
and list; Built-in data types, variables, Literals, Constants, statements, Operators: Assignment,
Arithmetic, Relational, Logical, Bitwise operators and their precedence, Expressions, tuple
assignment, Accepting input from Console, printing statements, Simple Python programs.

INTRODUCTION TO PYTHON
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming
language.
• It was created by Guido van Rossum during 1985- 1990.
• Python got its name from “Monty Python’s flying circus”. Python was released in the year
2000.
• Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
• Python is Object-Oriented: Python supports an Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for beginner-level programmers
and supports the development of a wide range of applications.
Python Features:
• Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is
very simple. It uses a few keywords.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• Portable: Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
• Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
• Extensible: Programmers can embed python within their C, C++, Java script, ActiveX, etc.
• Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
• High-Level Language: When writing programs, programmers concentrate on solutions to the
current problem, no need to worry about the low-level details.
• Scalable: Python provides a better structure and support for large programs than shell scripting.

P a g e 1 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Applications
• Bit Torrent file sharing
• Google search engine, Youtube
• Intel, Cisco, HP, IBM
• i–Robot
• NASA
• Facebook, Dropbox
Python interpreter
Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all at
once, in preparation for later execution.

MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
Interactive mode & Script mode
1. Interactive mode:
Interactive Mode, as the name suggests, allows us to interact with OS.
When we type a Python statement, the interpreter displays the result(s) immediately.
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small pieces of code.

P a g e 2 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1+1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code.
If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.

2. Script mode:
• In script mode, we type a python program in a file and then use an interpreter to execute the
content of the file.
• Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning
that the filename ends with .py
• Save the code with filename.py and run the interpreter in script mode to execute the script.

P a g e 3 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Integrated Development Learning Environment (IDLE):


• Is a graphical user interface that is completely written in Python.
• It is bundled with the default implementation of the python language and also comes with an
optional part of the Python packaging.
Features of IDLE:
• Multi-window text editor with syntax highlighting.
• Auto-completion with smart indentation.
• Python shell to display output with syntax highlighting.
VALUES AND DATA TYPES

Values
Value can be any letter, number, or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
• Every value in Python has a data type.
• It is a set of values and the allowable operations on those values.
Python has four standard data types:

P a g e 4 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Numbers:
• Number data type stores Numerical Values.
• This data type is immutable [i.e. values/items cannot be changed].
• Python supports integers, floating point numbers and complex numbers. They are defined as,

Sequence:
• A sequence is an ordered collection of items, indexed by positive integers.
• It is a combination of mutable (value can be changed) and immutable (values cannot be
changed) data types.
• There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples

1. Strings
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
• single quotes (' ') Eg, 'This a string in single quotes'
• double quotes (" ") Eg, "'This a string in double quotes'"
• triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines and sentences."""
➢ Individual character in a string is accessed using a subscript (index).
➢ Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
P a g e 5 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

2. Lists
A list is an ordered sequence of items. Values in the list are called elements/items.
It can be written as a list of comma-separated items (values) between square brackets[ ].
Items in the lists can be of different data types.

3. Tuple:
• A tuple is the same as a list, except that the set of elements is enclosed in parentheses instead
of square brackets.
• A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
The benefit of Tuple:
➢ Tuples are faster than lists.
➢ If the user wants to protect the data from accidental changes, a tuple can be used.
➢ Tuples can be used as keys in dictionaries, while lists can't.

4. Dictionaries:
• Lists are ordered sets of objects, whereas dictionaries are unordered sets.
• Dictionary is created by using curly brackets. i,e. {}
• Dictionaries are accessed via keys and not via their position.
• A dictionary is an associative array (also known as hashes). Any key of the dictionary is
associated (or mapped) to a value.
• The values of a dictionary can be any Python data type. So dictionaries are unordered key-
value-pairs(The association of a key and a value is called a key-value pair )
• Dictionaries don't support the sequence operation of the sequence data types like strings, tuples
and lists.

VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
• Named memory locations to store values.
• Programmers generally choose names for their variables that are meaningful.
• It can be of any length. No space is allowed.
• We don't need to declare a variable before using it. In Python, we simply assign a value to a
variable and it will exist.
P a g e 6 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Assigning value to a variable:


The value should be given on the right side of the assignment operator(=) and the variable on the left
side.
>>>counter =45
print(counter)
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
KEYWORDS
Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name, or any other identifier.
• They are used to define the syntax and structure of the Python language.
• Keywords are case-sensitive.

IDENTIFIERS
Identifier is the name given to entities like classes, functions, variables, etc. in Python.
• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits
(0 to 9) or underscore (_). all are valid examples.
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• Cannot use special symbols like! @, #, $, %, etc. in our identifier.
• Identifiers can be of any length.
Example: Names like myClass, var_1, and this_is_a_long_variable

P a g e 7 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

STATEMENTS AND EXPRESSIONS


Statements: Instructions that a Python interpreter can execute are called statements.
A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
Expressions: An expression is a combination of values, variables, and operators.
A value all by itself is considered an expression, and also a variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend
INPUT AND OUTPUT
INPUT: Input is data entered by the user (end-user) in the program.
In python, the input () function is available for input.
Syntax for input() is: variable = input (“data”)
Example:
>>> x=input("enter the name:") enter the name: george
>>> y=int(input("enter the number"))
enter the number 3 #python accepts a string as the default data type. conversion is required for type.
OUTPUT: Output can be displayed to the user using a Print statement.
Syntax: print (expression/constant/variable)
Example: print ("Hello")
Hello
P a g e 8 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

COMMENTS
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100) / 60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
LINES AND INDENTATION
• Most of the programming languages like C, C++, Java use braces { } to define a block of code.
But, python uses indentation.
• Blocks of code are denoted by line indentation.
• It is a space given to the block of codes for class and function definitions or flow control.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
TUPLE ASSIGNMENT
An assignment to all of the elements in a tuple using a single assignment statement.
• Python has a very powerful tuple assignment feature that allows a tuple of variables on the left
of an assignment to be assigned values from a tuple on the right of the assignment.
• The left side is a tuple of variables; the right side is a tuple of values.
• Each value is assigned to its respective variable.
• All the expressions on the right side are evaluated before any of the assignments. This feature
makes tuple assignments quite versatile.
• Naturally, the number of variables on the left and the number of values on the right have to be
the same.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
P a g e 9 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Example:
It is useful to swap the values of two variables. With conventional assignment statements, we have
to use a temporary variable. For example, to swap a and b:
Swap two numbers
a=2;b=3 Output:
print(a,b) (2, 3)
temp = a (3, 2)
a=b
b = temp
print(a,b)
Tuple assignment solves this problem neatly: (a, b) = (b, a)

OPERATORS
Operators are the constructs that can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators: They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5

P a g e 10 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)

P a g e 11 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Comparison (Relational) Operators:


Comparison operators are used to comparing values.
It either returns True or False according to the condition. Assume, a=10 and b=5

Example Output:
a=10 a>b=> True
b=5 a>b=> False
print("a>b=>",a>b) a==b=> False
print("a>b=>",a<b) a!=b=> True
print("a==b=>",a==b) a>=b=> False
print("a!=b=>",a!=b) a>=b=> True
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)

P a g e 12 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Assignment Operators:
Assignment operators are used in Python to assign values to variables.

P a g e 13 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)

Logical Operators:
Logical operators are the and, or, not operators.

Example Output
a = True x and y is False
b = False
print('a and b is',a and b) x or y is True
print('a or b is',a or b)
not x is False
print('not a is',not a)

P a g e 14 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

P a g e 15 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or
not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators
They are used to check if two values (or variables) are located on the same part of the memory.

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

P a g e 16 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

Output
False
True
OPERATOR PRECEDENCE
When an expression contains more than one operator, the order of evaluation depends on the order of
operations.

For mathematical operators, Python follows mathematical conventions.


The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction) is a useful way to remember the rules:

P a g e 17 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

• Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and
(1+1)**(5-2) is 8.
• You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60,
even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2 is 18,
not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1
is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6 find m=? a=2*3+4%5-3//2+6
a=? A=6+4%5-3/2+6 m=-43||8&&0||-2 a=6+4-1+6
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||0||-2 a=10-1+6
a=9-4+6-1 A=6+4-1+6 m=1||-2 a=15
a=5+6-1 A=10-1+6 m=1
a=11-1 A=9+6
a=10 A=15

P a g e 18 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

BASIC PYTHON PROGRAMS


1. Addition of two numbers
a=eval(input(“enter first no”)) Output
b=eval(input(“enter second no”)) enter first no
c=a+b 5
print(“the sum is “,c) enter second no
6
the sum is 11

2. Area of rectangle
l=eval(input(“enter the length of rectangle”)) Output
b=eval(input(“enter the breath of rectangle”)) enter the length of rectangle 5
a=l*b enter the breath of rectangle 6
print(a) 30

3. Area & circumference of a circle


r=eval(input(“enter the radius of circle”)) Output
a=3.14*r*r enter the radius of circle4
c=2*3.14*r the area of circle 50.24
print(“the area of circle”,a) the circumference of circle
print(“the circumference of circle”,c) 25.12

4. Calculate simple interest


p=eval(input(“enter principle amount”)) Output
n=eval(input(“enter no of years”)) enter principle amount 5000
r=eval(input(“enter rate of interest”)) enter no of years 4
si=p*n*r/100 enter rate of interest6
print(“simple interest is”,si) simple interest is 1200.0

P a g e 19 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

5. Calculate engineering cutoff


p=eval(input(“enter physics marks”)) Output
c=eval(input(“enter chemistry marks”)) enter physics marks 100
m=eval(input(“enter maths marks”)) enter chemistry marks 99
cutoff=(p/4+c/4+m/2) enter maths marks 96
print(“cutoff =”,cutoff) cutoff = 97.75

6. Check voting eligibility


age=eval(input(“enter ur age”)) output
If(age>=18): Enter ur age
print(“eligible for voting”) 19
else: Eligible for voting
print(“not eligible for voting”)

7. Find the greatest of three numbers


a=eval(input(“enter the value of a”)) output
b=eval(input(“enter the value of b”)) enter the value of a 9
c=eval(input(“enter the value of c”)) enter the value of a 1
if(a>b): enter the value of a 8
if(a>c): the greatest no is 9
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)

P a g e 20 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

8. Print n natural numbers


i=1 Output
1
while(i<=5): 2
3
print(i)
4
i=i+1 5

9. Print n odd numbers


i=2 Output
2
while(i<=10):
4
print(i) 6
8
i=i+2
10

10. Print n even numbers


i=1 Output
1
while(i<=10):
3
print(i) 5
7
i=i+2
9

11. Print n squares of numbers


i=1 Output
while(i<=5): 1
print(i*i) 4
i=i+1 9
16
25

12. Print n cubes numbers


i=1 Output
while(i<=3): 1
print(i*i*i) 8
i=i+1 27

P a g e 21 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

13. Find the sum of n numbers


i=1 Output
sum=0 55
while(i<=10):
sum=sum+i
i=i+1
print(sum)

14. Factorial of n numbers/product of n numbers


i=1 Output
product=1 3628800
while(i<=10):
product=product*i
i=i+1
print(product)

15. Swap two values of variables


a=eval(input("enter a value")) Output
b=eval(input("enter b value")) enter a value3
c=a enter b value5
a=b a= 5 b= 3
b=c
print("a=",a,"b=",b)

16. Convert the temperature


c=eval(input("enter temperature in centigrade")) Output
f=(1.8*c)+32 enter temperature in centigrade 37
print("the temperature in Fahrenheit is",f) the temperature in Fahrenheit is 98.6
f=eval(input("enter temp in Fahrenheit")) enter temp in Fahrenheit 100
c=(f-32)/1.8 the temperature in centigrade is 37.77
print("the temperature in centigrade is",c)

P a g e 22 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2

17. Program for a basic calculator


a=eval(input("enter a value")) Output
b=eval(input("enter b value")) enter a value 10
c=a+b enter b value 10
print("the sum is",c) the sum is 20
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the diff is 0
print("the diff is",c) enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the mul is 100
c=a*b enter a value 10
print("the mul is",c) enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a/b
print("the div is",c)

P a g e 23 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

UNIT 3
CONTROL FLOW, FUNCTIONS, AND STRINGS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif- else); Iteration: while, for; Loop manipulation using the pass, break,
continue, and else; Modules and Functions, function definition and use, flow of execution,
parameters and arguments; local and global scope, return values, function composition,
recursion; Strings: string slices, immutability, string functions, and methods, string module;
Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search,
binary search.
BOOLEAN VALUES
Boolean:
Boolean data types have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keywords.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
CONDITIONALS

1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else
Conditional (if): conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
if(condition 1):
Statement 1

P a g e 1 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Flowchart:

Examples:
a) Program to provide flat rs 500 if the purchase amount is greater than 2000.
b) Program to provide bonus marks if the category is sports.
a) Program to provide flat rs 500, if the purchase amount is Output
greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase amount
if(purchase>=2000): 2500
purchase=purchase-500 amount to pay
print(“amount to pay”,purchase) 2000

b) Program to provide bonus marks if the category is sports Output


m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90

2. alternative (if-else)
In the alternative, the condition must be true or false. In this else statement can be combined with the
if statement. The else statement contains the block of code that executes when the condition is false. If
the condition is true statements inside the if get executed otherwise else part gets executed. The
alternatives are called branches because they are branches in the flow of execution.
syntax:

P a g e 2 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Flowchart:

Examples:
a) Odd or even number
b) A positive or negative number
c) Leap year or not
d) Greatest of two numbers
e) Eligibility for voting
a) Odd or even number Output
n=eval(input("enter a number")) enter a number: 4
if(n%2==0): even number
print("even number")
else:
print("odd number")
b) Positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")

c) Leap year or not Output


y=eval(input("enter a yaer")) enter a yaer2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")
d) Greatest of two numbers Output
a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:7
if(a>b): greatest: 7
print("greatest:",a)
else:
print("greatest:",b)

P a g e 3 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

e) Eligibility for voting Output


age=eval(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")

3. Chained conditionals(if-elif-else)
• The elif is short for else if.
• This is used to check more than one condition.
• If condition 1 is False, it checks condition 2 of the elif block. If all the conditions are False,
then the else part is executed.
• Among the several, if...elif...else parts, only one part is executed according to the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
• The way to express a computation like that is a chained conditional.
syntax:

Flowchart:

P a g e 4 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Example:
a) Student mark system
b) Traffic light system
c) Compare two numbers
d) Roots of quadratic equation
a) Student mark system Output
mark=eval(input("enter ur mark:"))
enter ur mark:78
if(mark>=90):
grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
b) Traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"):
GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
c) Compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:"))
enter y value:7
if(x == y):
print("x and y are equal") x is less than y
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
d) Roots of quadratic equation Output
a=eval(input("enter a value:")) enter a value:1
b=eval(input("enter b value:"))
c=eval(input("enter c value:")) enter b value:0
d=(b*b-4*a*c) enter c value:0
if(d==0):
print("same and real roots") same and real roots
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
P a g e 5 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Nested conditionals
One conditional can also be nested within another. Any number of the condition can be nested inside
one another. In this, if the condition is true it checks another if condition1. If both the conditions are
true statement 1 gets executed otherwise statement 2 gets to execute. if the condition is false statement3
gets executed
Syntax:

Flowchart:

Examples:
a) Greatest of three numbers
b) Positive negative or zero
a) Greatest of three numbers Output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9

P a g e 6 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
b) Positive negative or zero Output
n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")

ITERATION/CONTROL STATEMENTS:
• state
• while
• for
• break
• continue
• pass
State:
The transition from one process to another process under a specified condition within a time is called
a state.
While loop:
While a loop statement in Python is used to repeatedly executes a set of statements as long as a given
condition is true.
In a while loop, the test expression is checked first. The body of the loop is entered only if the
test_expression is True. After one iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while starting with indentation and the first unindented line marks the end.
Syntax:

P a g e 7 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Flowchart

Examples:
a) Program to find the sum of n numbers:
b) Program to find the factorial of a number
c) Program to find the sum of digits of a number:
d) Program to Reverse the given number:
e) Program to find the number is Armstrong number or not
f) Program to check whether the number is palindrome or not

a) Sum of n numbers: output


n=eval(input("enter n"))
i=1 enter n
sum=0 10
while(i<=n):
sum=sum+i 55
i=i+1
print(sum)
b) Factorial of a numbers: output
n=eval(input("enter n"))
i=1 enter n
fact=1 5
while(i<=n):
fact=fact*i 120
i=i+1
print(fact)

c) Sum of digits of a number: output


n=eval(input("enter a number"))
sum=0 enter a number

P a g e 8 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

while(n>0): 123
a=n%10
sum=sum+a 6
n=n//10
print(sum)
d) Reverse the given number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)
e) Armstrong number or not output
n=eval(input("enter a number")) enter a number153
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
f) Palindrome or not output
n=eval(input("enter a number"))
org=n enter a number121
sum=0 The given no is palindrome
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")

For loop:
for in range:
• We can generate a sequence of numbers using the range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
• In range, a function has to define the start, stop and step size as a range(start, stop, step size).
step size defaults to 1 if not provided.

P a g e 9 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Syntax

Flowchart:

For in sequence

The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a sequence
is called traversal. Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.

Sequence can be a list, strings or tuples

P a g e 10 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Examples:
a) Print nos divisible by 5 not by 10:
b) Program to print the Fibonacci series.
c) Program to find factors of a given number
d) Check whether the given number is perfect or not
e) Check whether the no is prime or not
f) Print first n prime numbers
g) Program to print prime numbers in a range

a) Print nos divisible by 5 not by 10 Output


n=eval(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

b) Fibonacci series Output


a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
c) Find factors of a number Output
n=eval(input("enter a number:")) enter a number:10
for i in range(1,n+1,1): 1
if(n%i==0): 2
print(i) 5
10
d) Check the no is prime or not Output
n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
e) Check a number is perfect number or not Output
n=eval(input("enter a number:")) enter a number:6
sum=0 the number is perfect number
for i in range(1,n,1):
if(n%i==0):

P a g e 11 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")

f) Program to print first n prime numbers Output


number=int(input("enter no of prime enter no of prime numbers to be
numbers to be displayed:")) displayed:5
count=1 2
n=2 3
while(count<=number): 5
for i in range(2,n): 7
if(n%i==0): 11
break
else:
print(n)
count=count+1
n=n+1

g) Program to print prime numbers in range output:


lower=eval(input("enter a lower range")) enter a lower range50
upper=eval(input("enter a upper range")) enter a upper range100
for n in range(lower,upper + 1): 53
if n > 1: 59
for i in range(2,n): 61
if (n % i) == 0: 67
break 71
else: 73
print(n) 79
83
89
97

Loop Control Structures


BREAK
• Break statements can alter the flow of a loop.
• It terminates the current
• Loop and executes the remaining statement outside the loop.
• If the loop has else statement, that will also gets terminated and come out of the loop
completely.

P a g e 12 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Syntax:
Break

Flowchart

Example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)

P a g e 13 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

CONTINUE
It terminates the current iteration and transfers the control to the next iteration in the loop.
Syntax:
Continue

Flowchart

Example: Output
w
for i in "welcome":
e
if(i=="c"): l
o
continue m
print(i) e

P a g e 14 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

PASS
It is used when a statement is required syntactically but you don’t want any code to execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break

Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e

Difference between break and continue

P a g e 15 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

else statement in loops:


else in for loop:
If the else statement is used in for loop, the else statement is executed when the loop has reached the
limit.
The statements inside for loop and statements inside the else will also execute.
Example Output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6

else in while loop:


If the else statement is used within the while loop, the else part will be executed when the condition
becomes false.
The statements inside for loop and statements inside the else will also execute.

Program Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

FRUITFUL FUNCTION
• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion

P a g e 16 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Fruitful function: A function that returns a value is called a fruitful function.


Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

Void Function A function that performs an action but doesn’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values: return keywords are used to return the values from the function.
Example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value

P a g e 17 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

PARAMETERS / ARGUMENTS:
• Parameters are the variables used in the function definition.
• Parameters are inputs to functions.
• Parameter receives the input from the function call.
• It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
i. Required/Positional parameters
ii. Keyword parameters
iii. Default parameters
iv. Variable length parameters
i) Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number of arguments in
the function call.
Example
def student( name, roll ):
print(name,roll)
student(“George”,98)
Output:
George 98
ii) Keyword parameter:
When we call a function with some values, these values get assigned to the parameter according to
their position. When we call functions in keyword parameters, the order of the arguments can be
changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
iii) Default parameter:
Python allows function parameters to have default values; if the function is called without the
argument, the argument gets its default value in a function definition.

P a g e 18 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
iv) Variable length parameter
• Sometimes, we do not know in advance the number of arguments that will be passed into a
function.
• Python allows us to handle this kind of situation through function calls with several arguments.
• In the function definition, we use an asterisk (*) before the parameter name to denote this is the
variable length of the parameter.
Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)
Output:
bala ( 102 ,90)
Local and Global Scope
Global Scope
• The scope of a variable refers to the places where you can see or access a variable.
• A variable with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the function.

P a g e 19 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Local Scope A variable with local scope can be used only within the function .

Function Composition:
 Function Composition is the ability to call one function from within another function
 It is a way of combining functions such that the result of each function is passed as the argument
of the next function.
 In other words the output of one function is given as the input of another function is known as
function composition.
Examples:

math.sqrt(math.log(10))
def add(a,b):
c=a+b Output:
return c 900
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Find sum and average using function output
composition
def sum(a,b): enter a:4
sum=a+b
enter b:8
return sum
def avg(sum): the avg is 6.0
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

P a g e 20 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Recursion
A function calling itself till it reaches the base value - stop point of function call. Example: factorial
of a given number using recursion
Factorial of n
def fact(n):
if(n==1): Output
return 1 enter no. to find fact:5
else:
Fact is 120
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)

Explanation

Example:
a) Sum of n numbers
def sum(n):
if(n==1): Output
return 1
else: enter no. to find sum:10
return n*sum(n-1) Fact is 55
n=eval(input("enter no. to find
sum:"))
sum=sum(n)
print("Fact is",sum)

P a g e 21 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

STRINGS
• Strings
• String slices
• Immutability
• String functions and methods
• String module

Strings:
• A string is defined as a sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “ ).
• An individual character in a string is accessed using an index.
• The index should always be an integer (positive or negative).
• An index starts from 0 to n-1.
• Strings are immutable i.e. the contents of the string cannot be changed after it is created.
• Python will get the input at run time by default as a string.
• Python does not support character data type. A string of size 1 can be treated as a character.

 single quotes (' ')


 double quotes (" ")
 triple quotes(“”” “”””)

Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership

P a g e 22 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

String slices:
A part of a string is called a string slice.
The process of extracting a substring from a string is called slicing.

Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.

P a g e 23 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

String built in functions and methods: A method is a function that “belongs to” an object.

Syntax to access the method


Stringname.method()
a=”happy birthday”
here, a is the string name.

P a g e 24 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

String modules:
 A module is a file containing Python definitions, functions, and statements.
 The standard library of Python is extended as modules.
 Once we import a module, we can reference or use to any of its functions or variables in our
code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example
import string Output
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
Happy Birthday
print(string.hexdigits)
0123456789abcdefABCDEF
print(string.octdigits) 01234567
P a g e 25 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Escape sequences in string

List as an array:

Array:
 An array is a collection of similar elements.
 Elements in the array can be accessed by index. The index starts with 0.
 An array can be handled in python by a module named array.
 To create an array have to import an array module into the program.
Syntax :
import array

Syntax to create array:


Array_name = module_name.function_name(‘datatype’,[elements])

Example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype

P a g e 26 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Example
Program to find sum of array elements
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Output
10

Convert list into an array:


fromlist() function is used to append a list to an array. Here the list acts like an array.
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)

Output
35

P a g e 27 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

Methods in array
a=[2,3,4,5]

P a g e 28 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

ILLUSTRATIVE PROGRAMS:
1. Square root using newtons method:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)

Output:
enter number to find Sqrt: 9
3.0

2. GCD of two numbers


n1=int(input("Enter a number1:"))
n2=int(input("Enter a number2:"))
for i in range(1,n1+1):
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)

Output
Enter a number1:8
Enter a number2:24
8

P a g e 29 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

3. Exponent of number
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)

Output:
Enter base: 2
Enter exponential value:3
Result: 8

4. Sum of array elements:


a=[2,3,4,5,6,7,8]
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)

output:
the sum is 35

P a g e 30 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3

5. Linear search
a=[20,30,40,50,60,70,89]
print(a)
search=eval(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
Output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2

6. Binary search
a=[20, 30, 40, 50, 60, 70, 89]
print(a)
search=eval(input("enter a element to search:"))
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")
Output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
P a g e 31 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

UNIT 4
LISTS, TUPLES, DICTIONARIES
Lists: Defining list and list slicing, list operations, list slices, list methods, list loop, List
Manipulation, mutability, aliasing, cloning lists, list parameters; Lists as arrays, Tuples: tuple
assignment, tuple as return value, Tuple Manipulation; 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 square brackets
([ and ]):
Examples [10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']

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:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty list; you can
create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []

1. Lists are mutable


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 index.
Remember that the indices start at 0:
print cheeses[0]
Cheddar
P a g e 1 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment,
it identifies the element of the list that will be assigned.
>>> 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 is 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']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

2. Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as
for strings:
Example:
for cheese in cheeses:
print cheese

P a g e 2 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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 the functions range and len:

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

This loop traverses the list and updates each element. len returns the number of elements in the list.
range returns a list of indices from 0 to n 1, where n is the length of 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. 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]]

3. List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c=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] three times.
P a g e 3 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

4. List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
t[3:] ['d', 'e', 'f']
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.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle
or mutilate lists.
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']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']

5. 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']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)

P a g e 4 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

>>> 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
['a', 'b', 'c', 'd', 'e']
List methods are all void; they modify the list and return None.

6. List Loop
In Python, lists are considered a type of iterable. An iterable is a data type that can return its elements
separately, i.e., one at a time.
for <item> in <iterable>:
<body>

Example:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
...print("Hi "+ name +"!")
6.1 Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:
def add_all(t):
total = 0
for x in t:
total += x
return total
total is initialized to 0. Each time through the loop, x gets one element from the list. The += operator
provides a short way to update a variable. This augmented assignment statement:
total += x
is equivalent to: total = total + x

P a g e 5 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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]
>>> sum(t)
6
An operation like this that combines a sequence of elements into a single value is some times
called reduce.

7. 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
['a', 'c']
>>> print x
b
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes
and returns the last element.
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']

P a g e 6 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

The return value from remove is None.


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]
>>> print t
['a', 'f']
As usual, the slice selects all the elements up to, but not including, the second index.
8. 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)
>>> print t
['s', 'p', 'a', 'm']
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.
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter) ['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and concatenates the elements. join 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']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

P a g e 7 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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.

9. Objects and values


If we execute these assignment statements:
a = 'banana'
b = 'banana'
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 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
In this example, Python only created one string object, and both a and b refer to it. But when you create
two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
 In this case, we would say that the two lists are equivalent. After all, 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 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.

P a g e 8 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

10. Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b=a
>>> b is a
True
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 object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:

>>> 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 rarely makes a difference whether a and b refer to the same string or not.
11. Coloning Lists
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)

P a g e 9 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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


[10, 22, 44, 23, 4]

12. List arguments


When you pass a list to a function, the function gets a reference to the list. If the 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):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
The parameter t and the variable letters are aliases for the same object.
It is important to distinguish between operations that modify lists and operations that create new lists.
For example, the append method modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
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!
The slice operator creates a new list and the assignment makes t refer to it, but none of that has any
effect on the list that was passed as an argument.
P a g e 10 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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']

TUPLES
1. Tuples are immutable
A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in
that respect tuples are a lot like lists. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1) <type 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
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:

P a g e 11 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples. The 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:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

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

2. 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:
>>> temp = a
>>> a=b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the assignments.

P a g e 12 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

The number of variables on the left and the number of values on the right have to be the 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.
>>> print uname monty
>>> print domain python.org

3. 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:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1
Here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)

P a g e 13 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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.

4. Variable-length argument tuples


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:
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:
>>> t = (7, 3)
>>> divmod(t)
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
Practice: Write a function called sumall that takes any number of arguments and returns their
sum.

P a g e 14 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

5. 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 an iterator of tuples, but
for most purposes, an iterator behaves like a list.
This example zips a string and a list:
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]
The result is a list of tuples where each tuple contains a character from the string and the corresponding
element from the list.
If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk')
[('A', 'E'), ('n', 'l'), ('n', 'k')]
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:
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 and t2, and returns True
if there is an index i such that t1[i] == t2[i]:
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False

P a g e 15 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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
1b
2c
Again.

6. Dictionaries and tuples


Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value
pair.
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
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:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way to create a dictionary:
>>> d = dict(zip('abc', range(3)))
>>> print d
{'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:

P a g e 16 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

for key, val in d.items():


print val, key

The output of this loop is:


0a
2c
1b Again.

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.

for last, first in directory:


print first, last, directory[last,first]
This loop traverses the keys in directory, which are tuples. It assigns the elements of 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 indices and elements just as they appear
in a list.

7. Comparing tuples
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 considered (even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True

P a g e 17 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

>>> (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 Undecorate by extracting the sorted elements of the sequence.
For example, suppose you have 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
The first loop builds a list of tuples, where each tuple is a word preceded by its length. 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 length.

PYTHON DICTIONARY
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.
1. How to create a dictionary?
Creating a dictionary is as simple as placing items inside curly braces {} separated by a comma.
An item has a key and the corresponding value is 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.

# empty dictionary
# my_dict = {}
P a g e 18 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

# dictionary with integer keys


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')])
As you can see above, we can also create a dictionary using the built-in function dict().

2. How to access elements from a dictionary?


While indexing is used with other content types to access values, a 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'])

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

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']
OUTPUT:
Jack
26
P a g e 19 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

3. How to change or add elements in a dictionary?


Dictionary is mutable. We can add new items or change the value of existing items using the
assignment operator.
If the key is already present, the value gets updated, else a new key: value pair is added to the
dictionary.
my_dict = {'name':'Jack', 'age': 26}

# update value
my_dict['age'] = 27

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


print(my_dict)

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

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


print(my_dict)

The output will be:


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

4. How to delete or remove elements from a dictionary?


 We can remove a particular item in a dictionary by using the method pop(). This method
removes an item with the provided key and returns the value.
 The method, pop item () can be used to remove and return an arbitrary item (key, value) from
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}

P a g e 20 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

# remove a particular item


# Output: 16
print(squares.pop(4))

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


print(squares)

# remove an arbitrary item


# Output: (1, 1)
print(squares.popitem())

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


print(squares)

# delete a particular item


del squares[5]

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

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares
# Throws Error
# print(squares)

P a g e 21 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

The output will be:


16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

5. Python Dictionary Methods


Methods that are available with the dictionary are tabulated below. Some of them have already been
used in the above examples.
5.1 Method and Description
 clear(): Remove all items from the dictionary.
 copy(): Return a shallow copy of the dictionary.
 fromkeys(seq[, v]): Return a new dictionary with keys from seq and a value equal to v (defaults
to None).
 get(key[,d]): Return the value of the key. If the key doesn't exist, return d (defaults to None).
 items(): Return a new view of the dictionary's items (key, value).
 keys(): Return a new view of the dictionary's keys.
 pop(key[,d]): Remove the item with the key and return its value or d if the key is not found. If
d is not provided and the key is not found, raise KeyError.
 popitem(): Remove and return an arbitrary item (key, value). Raises KeyError if the dictionary
is empty.
 setdefault(key[,d]): If the key is in the dictionary, return its value. If not, insert a key with a
value of d and return d (defaults to None).
 update([other]): Update the dictionary with the key/value pairs from other, overwriting
existing keys.
 values(): Return a new view of the dictionary's values
Here is a few examples of the use of these methods.
marks = {}.fromkeys(['Math','English','Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']

P a g e 22 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

list(sorted(marks.keys()))

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


('English', 0)
('Math', 0)
('Science', 0)

Out[1]: ['English', 'Math', 'Science']

6. Built-in Functions with Dictionary


Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with a dictionary to
perform different tasks.
6.1 Function and Description
 all(): Return True if all keys of the dictionary are true (or if the dictionary is empty).
 any(): Return True if any key of the dictionary is true. If the dictionary is empty, return False.
 len(): Return the length (the number of items) in the dictionary.
 cmp(): Compares items of two dictionaries.
 sorted(): Return a new sorted list of keys in the dictionary.
Here are some examples that use built-in functions to work with a dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))
Output: 5
[1, 3, 5, 7, 9]

P a g e 23 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

ADVANCED LIST PROCESSING


1. List Comprehension
List comprehension is an elegant and concise way to create a new list from an existing list in Python.
A list comprehension consists of an expression followed by for statement inside square 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)
A list 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']] ['Python Language', 'Python
Programming', 'C Language', 'C Programming']

P a g e 24 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

ILLUSTRATIVE PROGRAM

1. SELECTION SORT PROGRAM

data = []
print('Selection Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
for i in range(0,n-1):
small=int(data[i])
pos=i
for j in range(i+1,n):
if int(data[j])<small:
small=int(data[j])
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)

P a g e 25 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

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))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate 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

def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

P a g e 26 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
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)

P a g e 27 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4

print('Intermediate s :')
mergeSort(data)
print('Sorted Array is:')
print(data)

4. HISTOGRAM PROGRAM

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

P a g e 28 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

UNIT 5
FILES, MODULES, PACKAGES
Files and exception: Concept of Files, Text Files; File opening in various modes and closing of a
file, Format Operators, Reading from a file, Writing onto a file, File functions-open(), close(),
read(), readline(), readlines(),write(), writelines(),tell(),seek(), Command Line arguments.
Errors and exceptions, handling exceptions, modules, packages; introduction to numpy,
matplotlib. Illustrative programs: word count, copy file.

FILES
❖ A file is a named location on a disk to store related information.
❖ It is used to permanently store data in non-volatile memory (e.g. hard disk).
❖ Since random access memory (RAM) is volatile and loses its data when a 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 to the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform the operation)
3. Close the file

1. Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> 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 '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.
The default is reading in text mode. In this mode, we get strings when reading from the file. On the
other hand, the binary mode returns bytes and this is the mode to be used when dealing with non-text
files like image or exe files.
Python File Modes
Mode: Description
❖ 'r': Open a file for reading. (default)
❖ 'w': Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
❖ 'x': Open a file for exclusive creation. If the file already exists, the operation fails.
❖ 'a': Open for appending at the end of the file without truncating it. Creates a new file if it does
not exist.
P a g e 1 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

❖ 't': Open in text mode. (default)


❖ 'b': Open in binary mode.
❖ '+': Open a file for updating (reading and writing)
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')

2. Closing a File
❖ When we are done with operations on the file, we need to properly close it.
❖ Closing a file will free up the resources that were tied to 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.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with
the file, the code exits without closing the file. A safer way is to use a try...finally block.
try:
f= open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing the
program flow to stop.
The best way to do this is by using the statement. This ensures that the file is closed when the block
inside with is exited.
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

P a g e 2 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

3. Reading and writing


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"
>>>fout.write(line1)
Again, the file object keeps track of where it is, so if you call to write again, it adds the new data to the
end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
Here are some of the functions in Python that allow you to read and write files:
❖ read(): This function reads the entire file and returns a string
❖ readline(): This function reads lines from that file and returns them as a string. It fetches the
line n if it is been called the nth time.
❖ readlines(): This function returns a list where each element is a single line of that file.
❖ write(): This function writes a fixed sequence of characters to a file.
❖ writelines(): This function writes a list of strings.
❖ append(): This function appends a string to the file instead of overwriting the file.
❖ tell(): Returns the current file position in a file stream.
❖ seek(): Change the current file position with the
4. 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:
>>> x = 52
>>> fout.write(str(x))

P a g e 3 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

❖ 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.
❖ 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.
For example, the format sequence '%d' means that the second operand should be formatted as an integer
(d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42. A format sequence
can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
❖ 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.
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 elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation

PYTHON COMMAND LINE ARGUMENTS


Python Command Line Arguments provide a convenient way to accept some information at the
command line while running the program. The arguments that are given after the name of the Python
script are known as Command Line Arguments and they are used to pass some information to the
program.
For example -
$ python script.py arg1 arg2 arg3

P a g e 4 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

Here Python script name is script.py and the rest of the three arguments - arg1 arg2 arg3 is command
line arguments for the program. There are following three Python modules that are helpful in parsing
and managing the command line arguments:
1. sys module
2. getopt module
3. argparse module
1. sys module - System-specific parameters
The Python sys module provides access to any command-line arguments via the sys.argv. This serves
two purposes −
• sys.argv is the list of command-line arguments.
• len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Example
Consider the following script test.py −
import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'


print 'Argument List:', str(sys.argv)
Now run the above script as below
$ python test.py arg1 arg2 arg3
This produces the following result −
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
As mentioned above, the first argument is always the script name and it is also counted in a number
of arguments.

2. Parsing Command-Line Arguments


Python provided a getopt module that helps you parse command-line options and arguments. This
module provides two functions and an exception to enable command-line argument parsing.
getopt.getopt method
This method parses command line options and parameter lists. The following is a simple syntax for
this method −

P a g e 5 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

getopt.getopt(args, options, [long_options])


Here is the detail of the parameters −
• args − This is the argument list to be parsed.
• options − This is the string of option letters that the script wants to recognize, with options
that require an argument that should be followed by a colon (:).
• long_options − This is an optional parameter and if specified, must be a list of strings with
the names of the long options, which should be supported. Long options, which require an
argument should be followed by an equal sign ('='). To accept only long options, options
should be an empty string.
This method getopt.getopt() returns a value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list was stripped. Each
option-and-value pair returned has the option as its first element, prefixed with a hyphen for short
options (e.g., '-x') or two hyphens for long options (e.g., '--long option).
Example
Following is a Python program that takes three arguments at the command line:
1. The first command line argument is -h which will be used to display the usage help of the
program.
2. The second argument is either -i or --ifile which we are considering as an input file.
3. The third argument is either -o or --ofile which we are considering as an output file.
4.
3. Python argparse Module
Python argparse module makes it easy to write user-friendly command-line interfaces. The program
defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.
The argparse module also automatically generates help and usage messages. The module will also
issue errors when users give the program invalid arguments.

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.

P a g e 6 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

❖ They occur, for example, when a file we try to open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError), the module we try to import is not found
(ImportError), etc.
❖ Whenever these types of runtime errors occur, Python creates an exception object.
❖ If not handled properly, it prints a traceback to that error along with some details about why
that error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'

1. 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 local() built-in
functions as follows.
>>> locals()['__builtins__']
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 causes them are tabulated below.
Exceptions: Cause of Error
❖ AssertionError: Raised when assert statement fails.
❖ AttributeError: Raised when attribute assignment or reference fails.
❖ EOFError: Raised when the input() functions hit the end-of-file condition.
❖ FloatingPointError: Raised when a floating point operation fails.
❖ GeneratorExit: Raise when a generator's close() method is called.
❖ ImportError: Raised when the imported module is not found.
❖ IndexError: Raised when the 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 the interrupt key (Ctrl+c or delete).
❖ MemoryError: Raised when an operation runs out of memory.
❖ NameError: Raised when a variable is not found in the local or global scope.
P a g e 7 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

❖ NotImplementedError: Raised by abstract methods.


❖ OSError: Raised when system operation causes the system-related error.
❖ OverflowError: Raised when the result of an arithmetic operation is too large to be
represented.
❖ ReferenceError: Raised when a weak reference proxy is used to access a garbage-collected
referent.
❖ RuntimeError: Raised when an error does not fall under any other category.
❖ StopIteration: Raised by the next() function to indicate that there is no further item to be
returned by the iterator.
❖ SyntaxError: Raised by the parser when a syntax error is encountered.
❖ IndentationError: Raised when there is incorrect indentation.
❖ TabError: Raised when indentation consists of inconsistent tabs and spaces.
❖ SystemError: Raised when the interpreter detects an internal error.
❖ SystemExit: Raised by sys. exit() function.
❖ TypeError: Raised when a function or operation is applied to an object of the incorrect type.
❖ UnboundLocalError: Raised when a reference is made to a local variable in a function or
method, but no value has been bound to that variable.
❖ UnicodeError: Raised when a Unicode-related encoding or decoding error occurs.
❖ UnicodeEncodeError: Raised when a Unicode-related error occurs during encoding.
❖ UnicodeDecodeError: Raised when a Unicode-related error occurs during decoding.
❖ UnicodeTranslateError: Raised when a Unicode-related error occurs during translating.
❖ ValueError: Raised when a function gets an argument of correct type but improper value.
❖ ZeroDivisionError: Raised when the 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.

2. Python Exception Handling


❖ Python has many built-in exceptions which force 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 comes to a sudden, unexpected
halt.
2.1 Catching Exceptions in Python
❖ In Python, exceptions can be handled using a try statement.
❖ A critical operation that can raise an exception is placed inside the try clause and the code that
handles the exception is written in except clause.
❖ It is up to us, what operations we perform once we have caught the exception.
Example: Catch Specific Error Type
try:

P a g e 8 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")
Output
Unsupported operation
Out of try except blocks
2.2 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 successful
or not. These actions (closing a file, GUI, or disconnecting from the network) are performed in
the finally clause to guarantee execution.
Syntax and Examples for various try and finally blocks
Syntax: Example: try...except blocks try:
try : a=5
#statements in the try block b='0'
except : print(a/b)
#executed when an error in the try except:
block
print('Some error occurred.')
print("Out of try except blocks.")

Output
Some error occurred.
Out of try except blocks.
Syntax: Example: Multiple except Blocks
try :
try:
#statements in the try block
a=5
except1 :
b=0

P a g e 9 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

#executed when an error in the try print (a/b)


block
except TypeError:
except2 :
print('Unsupported operation')
#executed when an error in the try
except ZeroDivisionError:
block
print ('Division by zero not allowed')
…..
print ('Out of try except blocks')
except n:
Output
#executed when an error in the try
block Division by zero not allowed
Out of try except blocks
Syntax: else and finally Example: try, except, else, finally blocks
try: try:
#statements in try block print('try block')
except: x=int(input('Enter a number: '))
#executed when error in try block y=int(input('Enter another number: '))
else: z=x/y
except ZeroDivisionError:
#executed if try block is error-free
print("except ZeroDivisionError block")
finally:
print("Division by 0 not accepted")
#executed irrespective of exception else:
occured or not print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally
blocks." )

Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.

P a g e 10 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

2.3 How to Raise an exception


If a condition does not meet our criteria but is correct according to the Python interpreter, we can
intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as
follows:
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {l
en(num)}" )

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:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
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:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7

P a g e 11 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

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: if __name__ ==
'__main__':
print linecount('wc.py')
__name__ is a built-in variable that is set when the program starts. If the program is running as a script,
__name__ has the value __main__; in that case, the test code is executed. Otherwise, if the module is
being imported, the test code is skipped.
Example:
# import module import calendar

yy= 2017
mm = 8

# To ask month and year from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

display the calendar


print(calendar.month(yy, mm))

PACKAGE
A package is a collection of modules. A Python package can have sub-packages and modules.
A directory must contain a file named __init__.py for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Here is an example. Suppose we are developing a game, one possible organization of packages and
modules could be as shown in the figure below.

P a g e 12 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

1. Importing module from a package


We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as follows. import
Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it.
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)
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
Now we can directly call this function.
select_difficulty(2)

❖ Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding.
❖ While importing packages, Python looks in the list of directories defined in sys.path, similar
to the module search path.
P a g e 13 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

INTRODUCTION TO NUMPY, MATPLOTLIB


NumPy package contains numpy.linalg module that provides all the functionality required for linear
algebra. Some of the important functions in this module are described in the following table.
Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that
is an effective open-source alternative for MatLab. It can also be used with graphics toolkits like PyQt
and wxPython.
The matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the
principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is
available in binary distribution as well as in the source code form on www.matplotlib.org.
Conventionally, the package is imported into the Python script by adding the following statement −
from matplotlib import pyplot as plt
Here pyplot() is the most important function in matplotlib library, which is used to plot 2D data. The
following script plots the equation y = 2x + 5
Example
import numpy as np
from matplotlib import pyplot as plt

x = np.arange(1,11)
y=2*x+5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()
A ndarray object x is created from np.arange() function as the values on the x axis. The corresponding
values on the y-axis are stored in another ndarray object y. These values are plotted using the
plot() function of pyplot submodule of matplotlib package.
The graphical representation is displayed by show() function.
The above code should produce the following output −

P a g e 14 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

ILLUSTRATION PROGRAM

1. Word Count

import sys
file=open("/Python27/note.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))

P a g e 15 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

EXAMPLE PYTHON PROGRAMS ON FILES, MODULES, PACKAGES

1. Write a function that copies a file reading and writing up to 50 characters at a time.

def copyFile(oldFile, newFile):


f1 = open(oldFile, "r")
f2 = open(newFile, "w")
while True:
text = f1.read(50)
if text == "":
break
f2.write(text)
f1.close()
f2.close()
return

2. (a) Write a program to perform exception handling.

def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False

P a g e 16 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

2. (b) Write a Python program to handle multiple exceptions.


try:
x= float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"

3. Write a python program to count number of lines, words and characters in a text file. def
wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r") for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc+=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()

4. Write a Python program to illustrate the use of command-line arguments.

import sys
def inputCmd():
print ("Name of the script:", sys.argv[0])
print ("Number of arguments:", len(sys.argv))

P a g e 17 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5

print ("The arguments are:", str(sys.argv))

5. Mention the commands and their syntax for the following: get current directory, changing
directory, list, directories and files, make a new directory, renaming and removing directory.

(a) Get current directory: getcwd()


Syntax : import os
os.getcwd()
(b) Changing directory: chdir()
Syntax: os.chdir(‘C:\\Users’)
os.getcwd()
(c) List directories and files: listdir()
Syntax: os.listdir()
(d) Making a new directory: mkdir()
Syntax: os.mkdir(‘Newdir’)
(e) Renaming a directory: rename()
os.rename(‘Newdir’,’Newname’)
os.listdir()
(f) Removing a directory: remove()
os.remove(‘NewName’)

P a g e 18 | 18
St. Joseph’s College of Engineering

You might also like