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

Python For Problem Solving Notes - All Units (2) - 240221 - 093412

Uploaded by

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

Python For Problem Solving Notes - All Units (2) - 240221 - 093412

Uploaded by

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

PYTHON FOR PROBLEM SOLVING UNIT - I

PYTHON FOR PROBLEM SOLVING


UNIT I
ALGORITHMIC PROBLEM SOLVING

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

PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a Correct
program.
PROBLEM SOLVING TECHNIQUES
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.
Algorithm should conclude after a finite number of steps.
Should have an end point
Derived results should be obtained only after the algorithm terminates.

Qualities of a good algorithm


The following are the primary factors that are often used to judge the quality of the algorithms.
PYTHON FOR PROBLEM SOLVING UNIT - I

Time – To execute a program, the computer system takes some amount of time. The lesser is the
time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The
lesser is the memory required, the better is 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.

Statements:
Statement is a single action in a computer.
In a computer statements might include some of the following actions
input data-information given to the program
process data-perform operation on a given input
output data-processed result

State:
Transition from one process to another process under specified condition with in a time is called
state.

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
1. sequence
2. selection
3. iteration

Sequence:
All the instructions are executed one after another is called sequence execution.
PYTHON FOR PROBLEM SOLVING UNIT - I

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

Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based upon 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
PYTHON FOR PROBLEM SOLVING UNIT - I

Step 2: Get age


Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

Iteration:

In some programs, certain set of statements are executed again and again based upon conditional
test. i.e. executed more than one time. This type of execution is called looping or iteration.
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
PYTHON FOR PROBLEM SOLVING UNIT - I

Step 6: go to step 4
Step 7: Stop
Functions:

 Function is a sub program which consists of 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 addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
PYTHON FOR PROBLEM SOLVING UNIT - I

NOTATIONS
FLOW CHART
Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual representation.
PYTHON FOR PROBLEM SOLVING UNIT - I

Rules for drawing a flowchart


1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. 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.
PYTHON FOR PROBLEM SOLVING UNIT - I

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:

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

Disadvantages of flow chart:

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

PSEUDO CODE:

 Pseudo code consists of short, readable and formally styled English languages used for explain
an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to understand the general
working of the program, because it is not based on any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
PYTHON FOR PROBLEM SOLVING UNIT - I

 Pseudo code can’t be compiled and executed.


 There is no standard syntax for pseudo code.

Guidelines for writing pseudo code:


Write one statement per line
Capitalize initial keyword
Indent to hierarchy
End multiline structure
Keep statements language independent

Common keywords used in pseudocode


The following gives common keywords used in pseudocodes.

1. //: This keyword 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 decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.

Syntax for if else:


IF (condition)THEN
statement
...
ELSE
statement
...
ENDIF

Example: Greates of two numbers


BEGIN
READ a,b
PYTHON FOR PROBLEM SOLVING UNIT - I

IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END

Syntax for For:


FOR( start-value to end-value) DO
statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END

Syntax for While:


WHILE (condition) DO
statement
...
ENDWHILE
PYTHON FOR PROBLEM SOLVING UNIT - I

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
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 flowchart.

a flowchart to programming language.

Disadvantages:

 It does not provide visual representation of the program’s logic.


 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.

flowchart.

Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
PYTHON FOR PROBLEM SOLVING UNIT - I

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 program using
programming language. The user has to communicate with the computer using language which it
can understand.
Types of programming language

1. Machine language
2. Assembly language
3. High level language

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 which the computer understands. For executing any
program written in any programming language, the conversion to machine language is necessary.
PYTHON FOR PROBLEM SOLVING UNIT - I

The program written in machine language can be executed directly on computer. In this case any
conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is saved, the execution
of machine language program is extremely fast.
Disadvantage:
It is hard to find errors in a program written in the machine language.
Writhing program in machine language is a time consuming process.

Machine dependent: According to 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 type of computer.

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 it is easier for
people to read, write and understand.
Assembly language is 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 language because they are so closely related to the machines.

Assembler
Assembler is the program which translates assembly language instruction in to 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.
PYTHON FOR PROBLEM SOLVING UNIT - I

Less efficient
Execution time of assembly language program is more than machine language program.
Because assembler is needed to convert from assembly language to machine language.

High level language


High level language contains English words and symbols. The specified rules are to be followed
while writing program in high level language. The interpreter or compilers are used for converting
these programs in to machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are called interpreter or
compiler.
Compiler:
A compiler is a program which translates the source code written in a high level language in to
object code which is in machine language program. Compiler reads the whole program written in
high level language and translates it to machine language. If any error is found it display error
message on the screen.
Interpreter
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 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 program have the advantage of being portable between machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs in high level
language require more memory and take more execution time to execute.
PYTHON FOR PROBLEM SOLVING UNIT - I

They are divided into 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

Interpreted programming languages:


An interpreted language is a programming language for which most of its implementation executes
instructions directly, without previously compiling a program into machine language instructions.
The interpreter executes the program directly translating each statement into a sequence of one or
more subroutines already compiled into machine code.
Examples:
Pascal
Python
Functional programming language:
Functional programming language defines every computation as a mathematical evaluation. They
focus on the programming languages are bound to mathematical calculations
Examples:
Clean
Haskell

Compiled Programming language:


A compiled programming is a programming language whose implementation are typically
compilers and not interpreters.
It will produce a machine code from source code.
Examples:
C
C++
C#
JAVA
PYTHON FOR PROBLEM SOLVING UNIT - I

Procedural programming language:


Procedural (imperative) programming implies specifying the steps that the programs should take
to reach to an intended state.
A procedure is a group of statements that can be referred through a procedure call. Procedures help
in the reuse of code. Procedural programming makes the programs structured and easily traceable
for program flow.
Examples:
Hyper talk
MATLAB

Scripting language:
Scripting language are programming languages that control an application. Scripts can execute
independent of any other application. They are mostly embedded in the application that they
control and are used to automate frequently executed tasks like communicating with external
program.
Examples:
Apple script
VB script

Markup languages:
A markup language is an artificial language that uses annotations to text that define hoe the text is
to be displayed.
Examples:
HTML
XML

Concurrent programming language:


Concurrent programming is a computer programming technique that provides for the execution of
operation concurrently, either with in a single computer or across a number of systems.
Examples:
Joule
Limbo
Object oriented programming language:
PYTHON FOR PROBLEM SOLVING UNIT - I

Object oriented programming is a programming paradigm based on the concept of objects which
may contain data in the form of procedures often known as methods.
Examples:
Lava
Moto

ALGORITHMIC PROBLEM SOLVING:


Algorithmic problem solving is solving problem that require 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 is not one that works most of the time, but one that works correctly
for all legitimate inputs.
PYTHON FOR PROBLEM SOLVING UNIT - I

Ascertaining the Capabilities of the Computational Device

 If the instructions are executed one after another, it is called sequential algorithm.
 If the instructions are executed concurrently, it is called parallel algorithm.

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 algorithm and approximation algorithm.

Deciding a data structure:

 Data structure plays a vital role in designing and analysis the 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 is applicable 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.
PYTHON FOR PROBLEM SOLVING UNIT - I

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 in order to show that an algorithm is
incorrect, you need just one instance of its input for which the algorithm fails.

Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating 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.
PYTHON FOR PROBLEM SOLVING UNIT - I

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:


FOR( start-value to end-value) DO
Statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
PYTHON FOR PROBLEM SOLVING UNIT - I

END

Syntax for While:


WHILE (condition) DO
Statement
...
ENDWHILE

Example: Print n natural numbers


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

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.
PYTHON FOR PROBLEM SOLVING UNIT - I

Algorithm for factorial of n numbers using recursion:

Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop

Sub function factorial(n):


Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact
PYTHON FOR PROBLEM SOLVING UNIT - I

Pseudo code for factorial using recursion:


Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN

Sub function factorial(n):


IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

More examples:

Write an algorithm to find area of a rectangle


Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop

BEGIN
READ l,b
CALCULATE A=l*b
DISPLAY A
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm for Calculating area and circumference of circle


Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop

BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
DISPLAY C
END

Write an algorithm for Calculating simple interest


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

BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm for Calculating engineering cutoff


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

BEGIN
READ P,C,M
CALCULATE
Cutoff= (P/4+C/4+M/2)
DISPLAY Cutoff
END

To check greatest of two numbers


Step 1: Start
Step 2: get a,b value
Step 3: check if(a>b) print a is greater
Step 4: else b is greater
Step 5: Stop

BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
PYTHON FOR PROBLEM SOLVING UNIT - I

To check leap year or not


Step 1: Start
Step 2: get y
Step 3: if(y%4==0) print leap year
Step 4: else print not leap year
Step 5: Stop

BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END

To check positive or negative number


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

To check odd or even number


Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop

BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END

To check greatest of three numbers


Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop

BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
PYTHON FOR PROBLEM SOLVING UNIT - I

DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END

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


Step 1: Start
Step 2: Get n value.
Step 3: if (n ==0) print “Given number is Zero” Else goto step4
Step 4: if (n > 0) then Print “Given number is +ve”
Step 5: else Print “Given number is -ve”
Step 6: Stop
PYTHON FOR PROBLEM SOLVING UNIT - I

BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
PYTHON FOR PROBLEM SOLVING UNIT - I

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 8
Step 5: Print i value
step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm to print n odd numbers


Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop

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

Write an algorithm to print n even numbers


Step 1: start
step 2: get n value
step 3: set initial value i=2
step 4: check if(i<=n) goto step 5 else goto step8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm to print squares of a number


Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm to print to print cubes of a number


Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i *i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm to find sum of a given number


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

BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Write an algorithm to find factorial of a given number


Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop

BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
PYTHON FOR PROBLEM SOLVING UNIT - I

ILLUSTRATIVE PROBLEM

1.Guess an integer in a range

Algorithm:
Step1: Start
Step 2: Declare hidden, guess,range=1 to 100
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then Print
Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop

Pseudocode:

BEGIN
COMPUTE hidden=random value in a range
READ guess
IF guess=hidden, then PRINT
Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - I

2.Find minimum in a list

Algorithm: Step 1:

Start Step 2: Read n

Step 3:Initialize i=0

Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5

Step4.1: Read a[i]

Step 4.2: i=i+1 goto step 4

Step 5: Compute min=a[0]

Step 6: Initialize i=1

Step 7: If i<n, then go to step 8 else goto step 10

Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2

Step 8.1: min=a[i]

Step 8.2: i=i+1 goto 7

Step 9: Print min

Step 10: Stop

Pseudocode:

BEGIN

READ n

FOR i=0 to n, then READ

a[i] INCREMENT -> i

END FOR COMPUTE

min=a[0] FOR i=1 to n, then

IF a[i]<min, then CALCULATE


PYTHON FOR PROBLEM SOLVING UNIT - I

min=a[i] INCREMENT i

ELSE

INCREMENT i
END IF-ELSE

END FOR

PRINT min
END
PYTHON FOR PROBLEM SOLVING UNIT - I

Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - I

3.Insert a card in a list of sorted cards

Algorithm:
Step 1: Start

Step 2: Read n

Step 3:Initialize i=0

Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5

Step4.1: Read a[i]

Step 4.2: i=i+1 goto step 4

Step 5: Read item

Step 6: Calculate i=n-1

Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8

Step 7.1: a[i+1]=a[i]

Step 7.2: i=i-1 goto step 7

Step 8: Compute a[i+1]=item

Step 9: Compute n=n+1

Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11

Step10.1: Print a[i]

Step10.2: i=i+1 goto step 10

Step 11: Stop


PYTHON FOR PROBLEM SOLVING UNIT - I

Pseudocode:

BEGIN
READ n

FOR i=0 to n, then READ

a[i] INCREMENT

END FOR

READ item

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

CALCULATE a[i+1]=a[i]

DECREMENT i

END FOR COMPUTE

a[i+1]=a[i] COMPUTE

n=n+1 FOR i=0 to n, then

PRINT a[i]

INCREMENT i

END FOR

END
PYTHON FOR PROBLEM SOLVING UNIT - I

Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - II

UNIT II

DATA, EXPRESSIONS, STATEMENTS

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

1. 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 Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner- level
programmers and supports the development of a wide range of applications.
 Easy-to-learn:Python is clearly defined and easily readable. The structure of the program is
very simple. It uses 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.
PYTHON FOR PROBLEM SOLVING UNIT - II

 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 of 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.

1.3. 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.
PYTHON FOR PROBLEM SOLVING UNIT - II

1.4 MODES OF PYTHON INTERPRETER:

Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode

1. Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.

 When we type Python statement, 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.

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

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.
PYTHON FOR PROBLEM SOLVING UNIT - II

2. Script mode:
 In script mode, we type python program in a file and then use 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.
PYTHON FOR PROBLEM SOLVING UNIT - II

Integrated Development Learning Environment (IDLE):


 Is a graphical user interface which is completely written in Python.

 It is bundled with the default implementation of the python language and also comes with 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.


PYTHON FOR PROBLEM SOLVING UNIT - II

2.VALUES AND DATA TYPES

Value:

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:

1. 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,
PYTHON FOR PROBLEM SOLVING UNIT - II

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."""
PYTHON FOR PROBLEM SOLVING UNIT - II

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

Indexing:

 Positive indexing helps in accessing the string from the beginning


 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first element.

Example: A[0] or A[-5] will display “H”

Subscript 1 or –ve (n-1) displays the second element.


Example: A[1] or A[-4] will display “E”

Operations on string:

i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
PYTHON FOR PROBLEM SOLVING UNIT - II

2. Lists

 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.
PYTHON FOR PROBLEM SOLVING UNIT - II

Operations on list:

 Indexing
 Slicing
 Concatenation
 Repetitions
 Updation, Insertion, Deletion


PYTHON FOR PROBLEM SOLVING UNIT - II

3. Tuple:

 A tuple is same as 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.
 Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Basic Operations:

Altering the tuple data type leads to error. Following error occurs when user tries to do.

>>> t[0]="a"

Trace back (most recent call last):


PYTHON FOR PROBLEM SOLVING UNIT - II

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

Type Error: 'tuple' object does not support item assignment

Set

Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.

We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.

Example

>>> a = {1,2,2,3,3,3}

>>> a

{1, 2, 3}

Mapping

-This data type is unordered and mutable.

-Dictionaries fall under Mappings.

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.
PYTHON FOR PROBLEM SOLVING UNIT - II

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

If you try to access a key which doesn't exist, you will get an error message:

>>> words = {"house" : "Haus", "cat":"Katze"}

>>> words["car"]

Traceback (most recent call last):

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

KeyError: 'car'
PYTHON FOR PROBLEM SOLVING UNIT - II

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.

Assigning value to variable:

Value should be given on the right side of assignment operator(=) and variable on 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 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.


PYTHON FOR PROBLEM SOLVING UNIT - II

IDENTIFIERS:

Identifier is the name given to entities like class, 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 an underscore (_).
 all are valid example.
 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.

Example:
Names like myClass, var_1, and this_is_a_long_variable

STATEMENTS AND EXPRESSIONS:

Statements:
-Instructions that a Python interpreter can executes 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:
PYTHON FOR PROBLEM SOLVING UNIT - II

>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program.


In python, 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 string as default data type. conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
print ("Hello") Hello

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 FOR PROBLEM SOLVING UNIT - II

 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")

QUOTATION IN PYTHON:

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.

Anything that is represented using quotations are considered as string.


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."""
PYTHON FOR PROBLEM SOLVING UNIT - II

OPERATORS:

 Operators are the constructs which 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

Examples
PYTHON FOR PROBLEM SOLVING UNIT - II

a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)

Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

Comparison (Relational) Operators:


PYTHON FOR PROBLEM SOLVING UNIT - II

 Comparison operators are used to compare values.


 It either returns True or False according to the condition. Assume, a=10 and b=5

Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)

Output:
a>b=> True
PYTHON FOR PROBLEM SOLVING UNIT - II

a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True

Assignment Operators:

-Assignment operators are used in Python to assign values to variables.


PYTHON FOR PROBLEM SOLVING UNIT - II

Example
PYTHON FOR PROBLEM SOLVING UNIT - II

a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
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)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators:

-Logical operators are the and, or, not operators.


PYTHON FOR PROBLEM SOLVING UNIT - II

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

Output
x and y is False
x or y is True
not x is False

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)
PYTHON FOR PROBLEM SOLVING UNIT - II

Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
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

Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
PYTHON FOR PROBLEM SOLVING UNIT - II

Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

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.
PYTHON FOR PROBLEM SOLVING UNIT - II

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

Output
False
True
PYTHON FOR PROBLEM SOLVING UNIT - II

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

 -The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,


Subtraction) is a useful way to remember the rules:
PYTHON FOR PROBLEM SOLVING UNIT - II

 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


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=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10

A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
PYTHON FOR PROBLEM SOLVING UNIT - II

A=6+4-1+6
A=10-1+6
A=9+6
A=15

find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1

a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0

a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1

a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15
PYTHON FOR PROBLEM SOLVING UNIT - II

FUNCTIONS:

Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.

Need For Function:


 When the program is too complex and large they are divided into parts. Each part is
separately coded and combined into single program. Each subprogram is called as function.
 Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.

Types of function:

Functions can be classified into two categories:

1) User defined function


2) Built in function

i) Built in functions

 Built in functions are the functions that are already created and stored in python.

 These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.
PYTHON FOR PROBLEM SOLVING UNIT - II

ii)User Defined Functions:

 User defined functions are the functions that programmers create for their requirement
and use.
 These functions can then be combined to form module which can be used in other
programs by importing them.

 Advantages of user defined functions:


 Programmers working on large project can divide the workload by making
different functions.
 If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
PYTHON FOR PROBLEM SOLVING UNIT - II

Function definition: (Sub program)

 def keyword is used to define a function.


 Give the function name after def keyword followed by parentheses in which arguments
are given.
 End with colon (:)
 Inside the function add the program statements to be executed
 End with or without return statement

Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)

 Once we have defined a function, we can call it from another function, program or even the
Python prompt.
 To call a function we simply type the function name with appropriate arguments.

Example:
x=5
y=4
my_add(x,y)
PYTHON FOR PROBLEM SOLVING UNIT - II

Flow of Execution:

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

statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.

Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.

Function Prototypes:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type

i) Function without arguments and without return type

 In this type no argument is passed through the function call and no output is return to
main function
 The sub function will read the input values perform the operation and print the result in
the same block
PYTHON FOR PROBLEM SOLVING UNIT - II

Example

def add( ):
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
OUTPUT:
enter a 5
enter b 10
15

ii) Function with arguments and without return type

o Arguments are passed through the function call but output is not return to the main function
Example
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)

OUTPUT:
enter a 5
enter b 10
15
PYTHON FOR PROBLEM SOLVING UNIT - II

iii) Function without arguments and with return type

o In this type no argument is passed through the function call but output is return to the main
function.

Example

def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)

OUTPUT:
enter a 5
enter b 10
15

iv) Function with arguments and with return type

In this type arguments are passed through the function call and output is return to the main
function

Example

def add(a,b):
c=a+b
PYTHON FOR PROBLEM SOLVING UNIT - II

return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)

OUTPUT:
enter a 5
enter b 10
15

Parameters And Arguments:

Parameters:

 Parameters are the value(s) provided in the parenthesis when we write function
header.
 These are the values required by function to work.
 If there is more than one value required, all of them will be listed in parameter list
separated by comma.
 Example: def my_add(a,b):

Arguments :

 Arguments are the value(s) provided in function call/invoke statement.


 List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
 Example: my_add(x,y)
PYTHON FOR PROBLEM SOLVING UNIT - II

RETURN STATEMENT:

 The return statement is used to exit a function and go back to the place from
where it was called.

 If the return statement has no arguments, then it will not return any values. But
exits from function.

Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4

print(my_add(x,y))

Output:
9

ARGUMENTS TYPES:

1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
PYTHON FOR PROBLEM SOLVING UNIT - II

1. Required Arguments:
The number of arguments in the function call should match exactly with the function
definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56

2. Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56

3. Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
PYTHON FOR PROBLEM SOLVING UNIT - II

return
my_details(name="george")
Output:
Name: george
Age 40

4. Variable length Arguments

If we want to specify more arguments than specified while defining the function, variable
length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",
ärjun")

Output:
rajan rahul micheal ärjun

MODULES:

 A module is a file containing Python definitions ,functions, statements and


instructions.

 Standard library of Python is extended as modules.

 To use these modules in a program, programmer needs to import the module.

 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.
PYTHON FOR PROBLEM SOLVING UNIT - II

 Every module contains many function.


 To access one of the function , you have to specify the name of the module and the
name of the function separated by dot . This format is called dot notation.

Syntax:
import module_name
module_name.function_name(variable)

Importing Builtin Module:


import math
x=math.sqrt(25)
print(x)

Importing User Defined Module:


import cal
x=cal.add(5,4)
print(x)
PYTHON FOR PROBLEM SOLVING UNIT - II

Built-in python modules are,

1.math – mathematical functions:


some of the functions in math module is,
math.ceil(x) - Return the ceiling of x, the smallest integer greater than or equal to x
math.floor(x) - Return the floor of x, the largest integer less than or equal to x.
math.factorial(x) -Return x factorial.
math.gcd(x,y)- Return the greatest common divisor of the integers a and b

math.sqrt(x)- Return the square root of x


math.log(x)- return the natural logarithm of x math.log10(x) – returns the base-10
logarithms math.log2(x) - Return the base-2 logarithm of x. math.sin(x) – returns sin of x
radians
math.cos(x)- returns cosine of x radians
math.tan(x)-returns tangent of x radians
PYTHON FOR PROBLEM SOLVING UNIT - II

math.pi - The mathematical constant π = 3.141592 math.e – returns The mathematical


constant e = 2.718281

2. .random-Generate pseudo-random numbers


random.randrange(stop)
random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number
PYTHON FOR PROBLEM SOLVING
UNIT III
CONTROL FLOW AND FUNCTIONS
BOOLEAN VALUES:
Boolean:
 Boolean data type has two values. They are 0 and 1.
 0 represents False
 1 represents True
 True and False are keyword.
OPERATORS:
 Operators are the constructs which can manipulate the value of operands.
 Considertheexpression4+5=9.Here, 4 and 5 are called operand sand + is
called operator.
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
Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

Comparison (Relational) Operators:


 Comparison operators are used to compare values.
 It either returns True or False according to the condition.
Assume, a=10 and b=5
Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True

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

Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
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)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators:
Logical operators are the and, or, not operators.
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

BitwiseOperators:
Let x=10(0000 1010in binary)and y= 4(00000100inbinary)

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)

Output
False
True

CONDITIONALS
 Conditional if
 Alternative if… else
 Chained if…elif…else
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
Flowchart:

Example:
1. Program to provide flat rs 500, if the purchase amount is greater than
2000.
2. Program to provide bonus mark if the category is sports.
#Program to provide flat rs 500, if the purchase amount is greater than 2000.
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)

output
enter your purchase
amount
2500
amount to pay
2000

#Program to provide bonus mark if the category is sports


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

output
enter ur mark out of 100
85
enter ur categery G/S
S
mark is 90

alternative (if-else)
In the alternative the condition must be true or false. In this else statement can
be combined with 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:
Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting

#Odd or even number


n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")

Output
enter a number4
even number

#positive or negative number


n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")

Output
enter a number8
positive number

#leap year or not


y=eval(input("enter a yaer"))
if(y%4==0):
print("leap year")
else:
print("not leap year")

Output
enter a yaer2000
leap year

#greatest of two numbers


a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
if(a>b):
print("greatest:",a)
else:
print("greatest:",b)

Output
enter a value:4
enter b value:7
greatest: 7

#eligibility for voting


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

Output
enter ur age:78
you are eligible for vote

Chained conditionals(if-elif-else)
· The elif is short for else if.
· This is used to check more than one condition.
· If the condition1 is False, it checks the condition2 of the elif block.
If all the conditions are False, then the else part is executed.
· Among the several if...elif...else part, 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:

Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
#student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")

Output
enter ur mark:78
grade:B

#traffic light system


colour=input("enter colour of light:")
if(colour=="green"):
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")

Output
enter colour of light:green
GO
#compare two numbers
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")

Output
enter x value:5
enter y value:7
x is less than y

#Roots of quadratic equation


a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")

output
enter a value:1
enter b value:0
enter c value:0
same and real roots

Nested conditionals

One conditional can also be nested within another. Any number of 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 statement1 get executed
otherwise statement2 get execute. if the condition is false statement3 gets
executed

Syntax:

Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero

#greatest of three numbers


a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
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)
output
enter the value of a 9
enter the value of a 1
enter the value of a 8
the greatest no is 9

#positive negative or zero


n=eval(input("enter the value of n:"))
if(n==0):
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")

output
enter the value of n:-9
the number is negative

Importing Built in Module:


import math
x=math.sqrt(25)
print(x)
Importing User Defined Module:
import cal
x=cal.add(5,4)
print(x)

Built-in python modules are,

1.math – mathematical functions:


 some of the functions in math module is,
 math.ceil(x) - Return the ceiling of x, the smallest integer greater than or
equal to x
 math.floor(x) - Return the floor of x, the largest integer less than or equal
to x.
 math.factorial(x) -Return x factorial.
 math.gcd(x,y)- Return the greatest common divisor of the integers a and b
 math.sqrt(x)- Return the square root of x
 math.log(x)- return the natural logarithm of x math.log10(x) – returns
the base-10 logarithms math.log2(x) - Return the base-2 logarithm of x.
math.sin(x) – returns sin of x radians
 math.cos(x)- returns cosine of x radians
 math.tan(x)-returns tangent of x radians
 math.pi - The mathematical constant π = 3.141592 math.e – returns The
mathematical constant e = 2.718281

2.Random-Generate pseudo-random numbers


random.randrange(stop)
random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number

ITERATION/CONTROL STATEMENTS:
· state
· while
· for
· break
· continue
· pass
State:
Transition from one process to another process under specified condition with in
a time is called state.
While loop:
· While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
· In while loop, 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 starts with indentation and the first
unindented line marks the end.
Syntax:

Flowchart

Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)

output
enter n
10
55

#Factorial of a numbers:
n=eval(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)

output
enter n
5
120

#Sum of digits of a number:


n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum+a
n=n//10
print(sum)

output
enter a number
123
6

#Reverse the given number:


n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
print(sum)

output
enter a number
123
321
#Armstrong number or not
n=eval(input("enter a number"))
org=n
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")

output
enter a number153
The given number is Armstrong number

Palindrome or not
n=eval(input("enter a number"))
org=n
sum=0
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")
output
enter a number121
The given no is palindrome
For loop:
for in range:
v
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
v
In range function have to define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided.

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

Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
print nos divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
output
enter a:30
5
15
25

Fibonacci series
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c

output
Enter the number of terms: 6
Fibonacci Series:
01
1
2
3
5
8
#find factors of a number
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
if(n%i==0):
print(i)

Output
enter a number:10
1
2
5
10

check the no is prime or not


n=eval(input("enter a number"))
for i in range(2,n):
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
output
enter a no:7
The num is a prime number.

#check a number is perfect number or not


n=eval(input("enter a number:"))
sum=0
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")

Output
enter a number:6
the number is perfect number

Program to print first n prime numbers


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

Program to print prime numbers in range


lower=eval(input("enter a lower range"))
upper=eval(input("enter a upper range"))
for n in range(lower,upper + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)

output:
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83
89
97
Loop Control Structures

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

example
for i in "welcome":
if(i=="c"):
break
print(i)

Output
w
e
l

CONTINUE
It terminates the current iteration and transfer the control to the next iteration in
the loop.

Syntax:
Continue
Flowchart

Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e
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
for i in “welcome”:
if (i == “c”):
pass
print(i)

Output
w
e
l
c
o
m
e
Difference between break and continue

else statement in loops:

else in for loop:


If 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 else will also execute.
example
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
output
1
2
3
4
5 the number greater than 6
else in while loop:
if else statement is used within while loop , the else part will be executed when
the condition become false.
The statements inside for loop and statements inside else will also execute.
Program
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
output
1
2
3
4
5
the number greater than 5

Fruitful Function
· Fruitful function
· Void function
· Return values
· Parameters
· Local and global scope
· Function composition
· Recursion
Fruitful function:
A function that returns a value is called 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 perform action but don’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

PARAMETERS / ARGUMENTS:

v Parameters are the variables which used in the function definition.


Parameters are inputs to functions. Parameter receives the input from the
function call.
v It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
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

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
parameter, 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

Default parameter:
Python allows function parameter to have default values; if the function is
called without the argument, the argument gets its default value in function
definition.
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17

Variable length parameter


v Sometimes, we do not know in advance the number of arguments that will
be passed into a function.

v Python allows us to handle this kind of situation through function calls


with number of arguments.
v In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)
Output:
bala ( 102 ,90)

Local and Global Scope


Global Scope
v The scope of a variable refers to the places that you can see or access a
variable.
v A variable with global scope can be used anywhere in the program.
v It can be created by defining a variable outside the function.

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

Function Composition:
v Function Composition is the ability to call one function from within
another function
v It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
v In other words the output of one function is given as the input of another
function is known as function composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900

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):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)
Output
enter no. to find fact:5
Fact is 120
Explanation

Strings:
v
Strings
v
String slices
v
Immutability
v
String functions and methods
v
String module

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

1. single quotes (' ')


2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
String slices:
 A part of a string is called string slices.
 The process of extracting a sub string 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.
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.
String modules:
v
A module is a file containing Python definitions, functions, statements.
v
Standard library of Python is extended as modules.
v
To use these modules in a program, programmer needs to import the
module.
v
Once we import a module, we can reference or use to any of its functions or
variables in our code.
v
There is large number of standard modules also available in python.
v
Standard modules can be imported the same way as we import our user-
defined modules.
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happ
y birthday"))
print(string.hexdigits)
print(string.octdigits)

output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
Escape sequences in string
PYTHON FOR PROBLEM SOLVING
UNIT III
LIST, TUPLES
Lists
 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.

Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
List slices:
List slicing is an operation that extracts a subset of elements from
an list and packages them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
 default start value is 0
 default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice
List methods:
 Methods used in lists are used to manipulate the data quickly.
 These methods work only on lists.
 They do not work on the other sequence types that are not mutable,
that is, the values they contain cannot be changed, added, or deleted.
syntax:
list name.method name( element/index/list)
1. List using For Loop:
 The for loop in Python is used to iterate over a sequence (list, tuple,
string) or other iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for val in sequence:

2. List using While loop


 The while loop in Python is used to iterate over a block of code as long
as the test expression (condition) is true.
 When the condition is tested and the result is false, the loop body will
be skipped and the first statement after the while loop will be executed.

Syntax:
while (condition):
body of while
Sum of elements in list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Output:
15

3. Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It
keeps on
running. Such loops are called infinite loop.
Example
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output:
Enter the number 10
you entered:10
Enter the number 12
you entered:12
Enter the number 16
you entered:16
Tuple:

A tuple is same as 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.

But tuple can be converted into list and list can be converted in to tuple.

Benefit of Tuple:

Tuples are faster than lists.

If the user wants to protect the data from accidental changes, tuple can
be used.

Tuples can be used as keys in dictionaries, while lists can't.

Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple methods:
Tuple is immutable so changes cannot be done on the elements of a tuple
once it is assigned.
Tuple Assignment:

Tuple assignment allows, variables on the left of an assignment operator
and values of tuple on the right of the assignment operator.

Multiple assignment works by creating a tuple of expressions from the
right hand side, and a tuple of targets from the left, and then matching each
expression to a target.

Because multiple assignments use tuples to work, it is often termed
tupleassignment.

Example:
Swapping using temporary variable:
a=20
b=50
temp = a
a=b
b = temp
print("value after swapping is",a,b)

Swapping using tuple assignment:


a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)

Tuple as return value:



A Tuple is a comma separated sequence of items.

It is created with or without ( ).

A function can return one value. if you want to return more than one
value from a function. we can use tuple as return value.
Example1:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Output:
enter a value:4
enter b value:3
reminder: 1
quotient: 1

Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,'a')

Output:
(2, 3, 'a')
Different between List and Tuples
PYTHON FOR PROBLEM SOLVING UNIT – V

UNIT V FILES, MODULES, PACKAGES

SYLLABUS : Files and exception: text files, reading and writing files, format operator -
command line arguments - errors and exceptions - handling exceptions – modules –
packages - Illustrative programs: word count, copy file.

FILES
File is a named location on disk to store related information. It is used to permanently store data
in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned
off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs
to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file
operation takes place in the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file

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, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files.
PYTHON FOR PROBLEM SOLVING UNIT – V

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.
't' : Open in text mode. (default)
'b' : Open in binary mode.
'+' : Open a file for updating (reading and w

f = open("test.txt") # equivalent to 'r' or 'rt'


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

Closing a File

When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the close()
method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
PYTHON FOR PROBLEM SOLVING UNIT – V

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 program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when the
block inside with is exited.
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

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)
PYTHON FOR PROBLEM SOLVING UNIT – V

Again, the file object keeps track of where it is, so if you call 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()

Text file –example:

F1=open(“abc.txt”,”x”)
out=open("abc.dat","w")
str= input("Enter string : ")
out.write(str)
out.close()
out=open("abc.dat","r")
str=out.read()
print("File contains")
print(str)
out.close()

Output
Enter string : Welcome to Python file handling
File contains
Welcome to Python file handling

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))

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.
PYTHON FOR PROBLEM SOLVING UNIT – V

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 the 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 FOR PROBLEM SOLVING UNIT – V

Filenames and paths

Files are organized into directories (also called “folders”). Every running program has a “current
directory,” which is the default directory for most operations. For example, when you open a file
for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for
“operating system”). os.getcwd returns the name of the current directory:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd /home/dinsdale

cwd stands for “current working directory.” The result in this example is /home/dinsdale, which
is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current directory.
To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'

os.path.exists checks whether a file or directory exists:


>>> os.path.exists('memo.txt')
True

If it exists, os.path.isdir checks whether it’s a directory:


>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True
PYTHON FOR PROBLEM SOLVING UNIT – V

Similarly, os.path.isfile checks whether it’s a file.


os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']

To demonstrate these functions, the following example “walks” through a directory, prints the
names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.

COMMAND LINE ARGUMENTS:

Input can be directly sent as an argument. When the program is running under command
prompt then inputs can be passed directly in the command and can be fetched using
"sys" module.

Important steps to be followed:

•Import the module ‘sys’.


•Use sys.argv for getting the list of command line arguments.
•Use len(sys.argv) for getting total number of arguments.

Example program:

import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs)
arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)

Output
PYTHON FOR PROBLEM SOLVING UNIT – V

C:\Python27>python cmd1.py one two


Number of arguments :3
Arguments are : ['cmd1.py', 'one', 'two']

EXCEPTION

Errors – referred as bugs in the program.

Errors occurs maximum by the fault of the programmer.

Debugging – Process of finding and correcting errors.

Two types of errors.:

•Syntax errors

– python interpreter find the syntax error when it executes the coding. Once find
the error, it displays the error by stopping the execution.

Common occurring syntax errors are

Putting a keyword at wrong place


Misspelling the keyword
Incorrect indentation
Forgetting symbols like comma, brackets, quotes (“ or ‘)
Empty block

•Run time errors

– if a program is free of syntax errors then it runs by the interpreter and the
errors occurs during the run time of the program due to logical mistake is called runtime errors.

Examples:

Trying to access a file that doesn’t exists


Performing the operations like division by zero
Using an identifier which is not defined
PYTHON FOR PROBLEM SOLVING UNIT – V

These errors are handled using exception handling mechanism


Handling Exceptions:
•Definition
– An exception is an event, which occurs during the execution of the program that
disrupts the normal flow of the program.

•When the program raises an exception, then python must handle the exception otherwise it
terminates and quits

The handling mechanism is done by

•try, except and else blocks

•try block – suspicious code (code that makes exception) placed here

•except block – code that handles the exception placed here and gets executed during exception

•else block – code that is to be executed if no exception is placed here for normal execution

Structure of blocks of exceptions

try:

write the suspicious code here

except exception1:

If exception1 occurs then this block will be executed

except exception2:

If exception2 occurs then this block will be executed


..
else:

If there is no exception then this code will be executed


PYTHON FOR PROBLEM SOLVING UNIT – V

Example program:
try:
n=int(input(“enter a value”))
expert:
print(“you didn’t enter the integer input”)
else:
print(“value entered correctly and stored”)

output:

enter a value:5
value entered correctly and stored

#import module sys to get the type of exception


import sys

randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)

Output
The entry is a
PYTHON FOR PROBLEM SOLVING UNIT – V

Oops! <class 'ValueError'> occured.


Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop until the user enters an integer that has a valid reciprocal. The portion
that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if any exception
occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and ask the
user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.

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:
PYTHON FOR PROBLEM SOLVING UNIT – V

>>> import wc
7

Now you have a module object wc:


>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the test code
at the bottom. Normally when you import a module, it defines new functions but it doesn’t
execute them.
Programs that will be imported as modules often use the following idiom: 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.
Eg:
# 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))
PYTHON FOR PROBLEM SOLVING UNIT – V

PACKAGES:

Packages are namespaces which contain multiple packages and modules themselves. They are
simply directories, but with a twist.

Each package in Python is a directory which must contain a special file called _ _init_
_.py To be a package the folder must contain a file called __init__.py

Packages can be nested to any depth i.e. it contains many sub packages and modules in it.

Accessing Packages:

Step 1: Create a folder name “MyPackage” in the folder where the python files are storing.
Step 2: Create a subfolder name “Add” in the folder “MyPackage”.
Step 3: Type a python program containing the function to add two numbers with function name
“add” and save the file inside the folder

“Add” by the name “addition”

Example Program:
PYTHON FOR PROBLEM SOLVING UNIT – V

Illustrative programs:
Word Count of a file:

import sys
fname=sys.argv[1]
n=0
with open(fname,'r') as f:
for line in f:
words=line.split()
n+=len(words)
print("Number of words:",n)

Copy file:

f1=open(“sourcefile.txt”,”r”)
f2=open(“destinationfile.txt”,”w”)
for line in f1:
f2.write(“\n”+line)
f1.close( )
f2.close( )
print(“Content of Source file:”)
f1=open(“sourcefile.txt”,”r”)
print(f1.read( ))
print(“Content of Copied file:”)
f2=open(“destinationfile.txt”,”r”)
print(f2.read( ))

You might also like