/ ALGORITHMIC
PROBLEM SOLVING
ed
[Algorithms, building blocks of algorithms (statements, state, control flow, functions)
tation (pseudo code, flow chart, programming language), algorithmic problen}
solving, simple strategies for developing algorithms (iteration, recursion). Ilustrativ
problems: find minimum in alist, insert a card in a list of sorted cards, guess an intege!
number in a range, Towers of Hanoi
1. 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.
An algorithm is a collection of well-defined, unambiguous and effectively
computable instructions if execute it will return the proper output.
well-defined- The instructions given in an algorithm should be simple and
defined well
Unambiguous- The instructions should be clear, there should not be ambiguity.
effectively computable- The instructions should be written step by step ,which helps
computer to understand the control flow .
1.1 PROPERTIES OF ALGORITHMS
+ 2Should be written in simple English
* Each and every instruction should be precise and unambiguous.
* Instructions in an algorithm should not be repeated infinitely.
+ 2Algorithm should conclude after a finite number of steps.
+ 2Should have an end point
° ?Derived results should be obtained only after the algorithm terminates.2 Problem Solving and Python Programming
1.2 Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the
algorithms.
1. Time - To execute a program, the computer system takes some amount of time.
The lesser is the time required, the better is the algorithm.
2. Memory - To execute a program, computer system takes some amount of
memory space. The lesser is the memory required, the better is the algorithm.
3. 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
We often use algorithm in our day-to-day life, but when and how?
cooking receipe
Calling a friend through phone
Our daily routine as a student
When we buy something
Our class routine
To understand the usage of algorithm, look over the following conversation.
— 4)
Hi Chitti,Bring me brush ®?
aAlgorithmic Problem Solving - 3
—> OOF)
tea:
Hey Chitti, es
Bring me tooth brush — +. ¢» 4 @
Let's discuss about the conversation, tom wants brush his teeth, so he asks chitti to
bring brush, what happens chitti returns cleaning brush.
Why this was happened?
Because the statement given by tom was not well defined and it is ambiguous
statement so chitti get confused and bring some brush to Tom. This is what happen if
the user gives ambiguity statement to the computer. Therefore an algorithm should be
simple and well defined.
How an algorithm should be?
It should be in simple English, what a programmer wants to say. It has a start, a
middle and an end. Probably an algorithm should have,
1. Start
2. In the middle it should have set of tasks that computer wants to do and it should
be in simple English and clear.
3. To avoid ambiguous should give no for each step.
Stop
Lets look over the simple example, The following algorithm helps the
computer to validate user’s email address.
Start
Create a variable to get the user's email address
clear the variable, incase its not empty.
Ask the user for an email address.
Store the response in the variable.Check the stored response to see if it is a valid email address
Not valid? Go back
Stop
Lets see how it works?
°
€ eo), Dr-Paul feed the above algorithm to
? chitti and gonna test how it will
l
tS gy work
Chitti asked Tom to enter email
address-Tom entered ,but chitti gets 4
confused and donot know which Sy
process to be done next??
Why this Happened?
This was happened because the instructions given in an algorithm does not have
numbering for each step. So Chitti gets confused which step have to do. To avoid this
ambiguity, we should number each step while writing an algorithm, So let’s rewrite the
algorithm.
Step1: Start
Step2: Create a variable to get the user's email address
Step3: Clear the variable, incase its not empty.
Step4: Ask the user for an email address.
Step5: Store the response in the variable.
Step6: Check the stored response to see if it is a valid email addressAlgorithmic Problem Solving - 5
Step7: Not valid? Go back
Step8: Stop
Dr-Paul refeed the algorithm to chitti ,now,
lets see how it will
work:
2. BUILDING BLOCKS OF ALGORITHMS
Algorithms can be constructed from basic building blocks namely, sequence,
selection and iteration.
2.1 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
2.2 State
Transition from one process to another process under specified condition with in a time
is called state.6- Problem Solving and Python Programming
2.3 Control flow
The process of executing the individual statements in a given order is called control
flow.
The control can be executed in three ways
1. Sequence
2. Selection
3. Iteration
SEQUENCE
2.3.1 Sequence
SELECTION ITERATION
All the instructions are executed one after another is called sequence execution.
are KE
Flow Diagram
Statement 1 »| Statement 2 »| Statement 3
»| Statement n
Consider an example,
Algorithm for Making Tea
Step 1: put a pan on the stoveAlgorithmic Problem Solving - 7
Step 2: pour some water in it
Step 3: Let the water boils
Step 4: Add some tea leaves
Step 5: let it boil and water color changes
Step 6: Add some sugar and Milk
Step 7: Serve Hot
Every algorithm will have input, processing step and output.
In above example,
Input are the key ingredients such as water, tea leaves sugar and milk.
Processing consists of steps in converting the given ingredients into tea
Outputis Tea
Example:
Add two numbers:
Step 1: Start
Step 2: get ab
Step 3: calculate c=a+b
Step 4: Display
Step 5: Stop
2.3.2 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.8- Problem Solving and Python Programming
Consider an example for choosing a correct destination ?
Step 1: Check for the destination located from current position.
Step 2: If it is located in right then choose right way
Step 3: If it is located in left then choose left way.
Step 4: Else comeback and search for new way.
Flow Diagram
Condition
for decision.
making
False
|
Statement 2
\Statement 1
(
a,
Pp
Example,
Algorithm to find a given number odd or even
Step: Start
Step 2: Get a
Step 3: If a%2=0
Step 3.1: Display “Even”
Step 3.2: Else
Step3.3: Display “Odd”
Step 4: Stop
2.3.3 Iteration
In some programs, certain set of statements are executed again and again based
upon conditional test. ie. executed more than one time. This type of execution is called
looping or iteration.Algorithmic Problem Solving -
Iteration Iteration
0 1
Repeat as needed Iteration
n
Algorithm for Washing Dishes
Stepl: Stack dishes by sink.
Step 2: Fill sink with hot soapy water.
Step 3: While moreDishes
Step 4: Get dish from counter,Wash dish
Step 5: Put dish in drain rack.
Step 6: End While
Step 7: Wipe off counter.
Step 8: Rinse out sink.
Flow Diagram:
Statement 110 - Problem Solving and Python Programming
Example
Write an algorithm to print all natural numbers up ton
Step 1:
Step 2: get n value.
Start
Step 3: initialize i-1
Step 4: if (i<-n) go to step 5 else go to step 7
Step 5: Printi value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
2.4 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:5
top
sub function add()
Step 1: Function start
Step 2: Get a, b ValuesAlgorithmic Problem Solving - 11
Step 3: add a+b
Step 4:
Step 5:
Main Function Sub Function,
()
Call add ()
® EE
Ey
q
3. NOTATIONS
There are three types of notations for developing an algorithm
* Flow Chart
* Pseudocode
+ Programming Language
3.1 FLOW CHART
Flow chart is defined as graphical representation of the logic for problem
solving.12 - Problem Solving and Python Programming
The purpose of flowchart is making the logic of the program clear in a visual
representation.
SLNo. | Symbol Symbol Name Description
Used to represent
start and stop
Used to represent
2 / / Input / Output Symbol input and output
statement
Used to represent
Terminal Symbol
Process Symbol
Processing
4. 5 s
decision to be made|
5 ; Used to represent
. Sub Function Symbol -
function call
6. 7 Used to Connect two
C > Connector Symbol flowchart
a > Used to connect
7 Flow Symbol
J symbols
<<
3.1.1 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,
v
v
4, Only one flow line should enter a decision symbol. However, two or three flow lines
may leave the decision symbol.
NO
YESAlgorithmic Problem Solving - 13
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.
3.1.2 Advantages of flowchart
1, Communication: - Flowcharts are better way of communicating the logic of a system.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way.
3. Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes.
4, Efficient Coding: - The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program becomes
easy with the help of flowchart. It helps the programmer to put efforts more efficiently
on that part.
3.1.3 Disadvantages of flow chart
Although a flowchart is a very useful tool, there are a few limitations in using
flowcharts which are listed below:
* 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-rawing completely.
* Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
3.2 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.14 - Problem Solving and Python Programming
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
Pseudo code can’t be compiled and executed. There is no standard syntax for
pseudo code.
3.2.1 Guidelines for writing pseudo code
4 Write one statement per line
+ Capitalize initial keyword
“ Indent to show hierarchy
+ End multiline structure
* Keep statements language independent
3.2.2 Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. Ik 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:
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
sed for iterative statemen'
Examples
Syntax for if else: Example: Greates of two numbers
IF (condition)THEN BEGIN
statement READ ab
IF (a>b) THEN
SE DISPLAY ais greater
statement ELSE.Algorithmic Problem Solving - 15
= DISPLAY b is greater
ENDIF ENDIF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
statement GETn
oo INITIALIZE i=1
ENDFOR FOR (i<-n) DO
PRINT i
isd
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
statement GETn
we INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINTi
isi
ENDWHILE
END
3.2.3 Advantages:
1. Pseudocode is independent of any language; it can be used by most programmers.
2. ?Itis easy to translate pseudo code into a programming language.
3. Itcan be easily modified as compared to flowchart.
4. Converting a pseudo code to programming language is very easy as compared
5. with converting a flowchart to programming language.
4 Disadvantages:
It does not provide visual representation of the program’s logic.
2.
1
2. There are no accepted standards for writing pseudo codes.
3. It cannot be compiled nor executed
4.
For a beginner, It is more difficult to follow the logic or write pseudo
code as compared to flowchart.16 - Problem Solving and Python Programming
3.3 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,
( Computer Languages
r +
(“% Level Language | {Middle Level Language High Level Language
(Machine Language) (Assembly Language) L J
Use 1's & 0’ sto Use mnenmonics to Similar to
create instructions create instructions human language
Ex Binary Language Assembly Language ‘COBOL, FORTRAN, BASIC
CC, JAVA,
Types of programming language
1. Machine language (01) Low Level Language (or) Binary Language
2. Assembly language (or) Middle Level Language
3. High level language
3.3.1 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.
101010101
010101010Algorithmic Problem Solving - 17
3.3.1.1 Advantages
1. 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. The program written in machine
language can be executed directly on computer. In this case any conversion
process is not required
2. High speed- The machine language program is translation free. Since the
conversion time is saved, the execution of machine language program is
extremely fast.
3.3.1.2 Disadvantage
1. ?It is hard to find errors in a program written in the machine language.
2. Writhing program in machine language is a time consuming process.
3.3.2 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,
s
o onoonnd
00
Assembler
MOV ALA
MOV BL,B
ADD BA
Example : ADD a, b
Assembler
Assembler is the program which translates assembly language instruction in to a
machine language.18 - Problem Solving and Python Programming
3.3.2.1 Advantage
1. ?Easy to understand and use.
2. It is easy to locate and correct errors.
3.3.2.2 Disadvantage
1. Machine dependent-The assembly language program which can be executed on
the machine depends on the architecture of that computer.
2. Hard to leam-It is machine dependent, so the programmer should have the
hardware knowledge to create applications using assembly language.
3. 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.
3.3.3 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.
—
(—)
“yy
Ex
Machine code
Per
sea
Pocencuc!
Girard
Conan
femnny
Prey
Words
Coren
Pent)
ieee
Translating high level language to machine language
The programs that translate high level language in to machine language are
called interpreter or compiler.Algorithmic Problem Solving - 19
1. 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 during compiling process.
Hivexe=
——
11011001
01000100
00010111
10101011
print “hello”
Source file Error Machine code
2. 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 at runtime.20 - Problem Solving and Python Programming
3.3.1 Advantages
1. Readability- High level language is closer to natural language so they are easier
to lear and understand
2. Machine independent- High level language program have the advantage of being
portable between machines.
3. Easy debugging- Easy to find and correct error in high level language
3.3.2 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.
4, ALGORITHMIC PROBLEM SOLVING
Algorithmic problem solving is solving a problem that require the formulation
of an algorithm for the solution.
1. PROBLEM DEFINITION
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.
ry imp specify ly P 8
A correct algorithm is not one that works most of the time, but one that works
correctly for all legitimate inputs.
2. ANALYZE
The purpose of this step is to determine both the starting and ending points for
solving the problem. A good problem descrip tion makes it easier to perform this step
eg ~~
( Review } grammy (Analyze }
LY co) QS
4S
a5 8
ol
(Refine Develop }Algorithmic Problem Solving - 21
3. DEVELOP
An algorithm is a plan for solving a problem, but plans come in several levels of
detail. It's usually better to start with a high-level algorithm that includes the major part
of a solution, but leaves the details until later. We can use an everyday example to
demonstrate a high-level algorithm.
Problem: | need a send a birthday card to my brother, Mark.
Analysis: I don't have a card, | prefer to buy a card rather than make one myself.
High-level algorithm
1. Go to astore that sells greeting cards
2. Select a card
Purchase a card
4. Mail the card
This algorithm is satisfactory for daily use, but it lacks details that would have
to be added were a computer to carry out the solution, These details include answers to
questions such as the following,
* "Which store will I visit?”
+ "How will I get there: walk, drive, ride my bicycle, take the bus?”
+ "What kind of card does Mark like: humorous, sentimental, risqué?"
‘These kinds of details are considered in the next step of our process
4. REFINE
When our goal is to develop algorithms that will lead to computer programs, we
need to consider the capabilities of the computer and provide enough detail so that
someone else could use our algorithm to write a computer program that follows the
steps in our algorithm.
As with the birthday card problem, we need to adjust the level of detail to match
the ability of the programmer. When in doubt, or when you are learning, it is better to
have too much detail than to have too little.22 - Problem Solving and Python Programming
Most of our examples will move from a high-level to a detailed algorithm in a
single step, but this is not always reasonable. For larger, more complex problems, it is
common to go through this process several times, developing intermediate level
algorithms as we go. Each time, we add more detail to the previous algorithm, stopping
when we see no benefit to further refinement.
‘This technique of gradually working from a high-level to a detailed algorithm is
often called stepwise refinement.
Stepwise refinement is a process for developing a detailed algorithm by
gradually adding detail to a high-level algorithm.
5. REVIEW
The final step is to review the algorithm. What are we looking for? First, we
need to work through the algorithm step by step to determine whether or not it will
solve the original problem. Once we are satisfied that the algorithm does provide a
solution to the problem, we start to look for other things.
5. SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS.
The two strategies for developing an algorithm are:
1. Iterations
2. Recursions
5.1 ITERATIONS
A sequence of statements, which is executed repeatedly until a specified
condition is true is called iterations.
The two iterations are:
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN,
statement GETn
oe INITIALIZE il
ENDFOR FOR (i<=n) DOAlgorithmic Problem Solving - 23
PRINT i
isitd
ENDFOR
END
Syntax for While:
Example: Print n natural numbers
WHILE (condition) DO
statement
ENDWHILE
BEGIN
GETn
INITIALIZE i=1
WHILE(i<-n) DO
PRINTi
irit]
ENDWHILE
END
5.2 RECURSIONS
aur
_s
Le]
A function that calls itself again and again is known as recursion. Recursion is a
process by which a function calls itself repeatedly until some specified condition has
been satisfied.24 - Problem Solving and Python Programming
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):
Stepl: if(r
Step2: else fact=n*factorial(n-1) and return fact
1) then fact=1 return fact
"stant >) C tact
C stant > Cres
cere / ves
ito)
parent No
* - >)
J mivta m/
C sro stor) or)
ILLUSTRATIVE PROBLEM
Problem 1: Find minimum in a list
6
Problem Definition: Given a list of positive numbers ,return a smallest number from the list.
Input: List of positive number
Output: Return smallest number from the given list
XR
XXAlgorithmic Problem Solving - 25
ALGORITHM.
Step 1: Start
Step 2: Get the list of elements
Step 3: Assume first element as MIN
Step 4: Compare MIN with next element
Step 5: If MIN is greater than next element; set MIN=next element
Step 6: Repeat steps 4 and 5 till the last element
Step 7: Display MIN element
Step 8: Stop
PSEUDOCODE
SETi-0
READn
SET min=a[0]
IF isn then STOP
ELSE IF a[i]
<<)
—+) xo
.
Problem 2: Guess an integer number in a range
(Problem Definition: Guess an integer number in a range randomly and check whether
the guess is correct or not
Input: Get an integer number
(Output: Correct guess
ALGORITHM
Step 1: Start
Step 2:Ask a number to guess
Step 3: if guess — number then print” Correct Guess”
Step 4: else if guess>number then print “Guess too high”
Step 5:
se print “Guess too low”
Step 6: Repeat steps 3,4,and 4 untill you guess correct number
StepAlgorithmic Problem Solving - 27
PSEUDOCODE
READ num
READ guess
IF guess=-num then PRINT “Correct Guess”
ELSE IF guessnum then PRINT “Guess Too High”
END IF
END IE
END IF
FLOWCHART
<<
¥
v
Read mum
}——_
se rl
(E> 1
MSM28 - Problem Solving and Python Programming
Problem 3: Insert a card in a list of sorted cards
~\
Problem Definition: In general the cards are sorted at first in ascending order, user
will pick a new card and insert in its correct position.
Input: Pick a card
Output: insert in correct position so that the cards are in sorted )
ALGORITHM
Step 1: Start
Step 2: Get target number
Step 3: Initialize the value i-last+1 and first-0
Step 4: if ipfirst and target) a=target
:
yes Print i
=
C sor >
Problem 3: Tower of Hanoi
frroblem Definition: Tt is a mathematical puzzel game in which you have three|
‘stand (pegs). The rings of different size are arranged in decreasing order(from first to)
last) and placed on one side of peg. The objective of the game is to move all the rings of
lone side to another side through auxilary peg.
Input: Three rings of different size and three pegs.
Output: Move three rings of one side to another side.
Conditions:
1. Only the top most ring from the peg should be moved
2._No larger ring can be placed on the smaller ring30 - Problem Solving and Python Programming
3. Only one ring can be moved ata time >
4, The steps taken for moving a ‘n’ number of disk is 2"-1. (i.e) if you have three
rings to move then the number of moves will be 2
s 3
ALGORITHM
Main Function
Step 1:Start
Step 2: Call function TowersOfHanoi(disk,startend auxiliary)
Step 3: Stop
Towers Of Hanoi
Step 1: If only one disk is there then move the first disk to last.
Step 2: If more than one disk is there then
Step 2.1: Call TowersOfHanoi(disk-1, start auxiliary,end)
Step 2.2: Move disk from start to end
Step 2.3: Call TowersOfHanoi(disk-1, auxiliary end, start)Algorithmic Problem Solving - 31
Step 3: Return to main function
PSEUDOCODE
1 then MOVE first to last
ELSE
PROCEDURE TowersOfHanoi(disk-1,start,auxiliary,end)
MOVE disk from start to end
PROCEDURE TowersOfHanoi(disk-1,auxiliary,end,start)
END PROCEDURE
END IF
FLOWCHART
Define
Towers of Hanoi
ves
Move disk from
startto end
¥
Declaren
No
v
Towers of Hanot
(disk, star, auiliary, end)
/ Reedn a
“Move dis fom fist to last,
call
Towers of Hanoi
“Towers of hanat
(isk, auuliay, end, start)
Cw32. - Problem Solving and Python Programming
Example 1: Sum of two numbers
ALGORITHM CO on ‘ART »
nN
Step 1: Start.
¥
Step 2: Input the values of A and B.
Read A,B
Step 3: Find the sum of A and B _
Sum=A+B ¥v
Step 4: Print the value of sum. Sum= A+B
Step 5: Stop. y
READ the value of variables A and B
FIND the sum
PSEUDOCODE / Print Sum,
Oo
NN
Sum=A+B
WRITE the output of sum (ster >)
nN 7
Example 2: Find the area and circumference of circle
ALGORITHM
Step 1: Start.
Step 2: Input the radius of the circle
Step 3: Find the area and circumference using the formula
Area=3.14*r*r / Prin area
drcumference
Circumference=2"3.14*r
Step 4: Print the area and circumference of the circle
Step 5: Stop.Algorithmic Problem Solving - 33
PSEUDOCODE
READ the radius
Area=3.14*r*r
Circumference=2*3.14*r
WRITE area and circumference
Example 3: Find the area of a triangle
ALGORITHM
Step 1: Start
Step 2: Read the values of a,b,c.
Step 3: Calculate the three sides of a triangle use the formula
S=(atb+0)/2
Step 4: Find the area of the triangle using the formula
Area=sqrt(s*(s-a)*(s-b)*(s-c))
Read a,b, ¢
Step 5: Print the area of the triangle I
Step 6: Stop Calculate
Sela+b+o2
PSEUDOCODE
READ the value of a,b,c.
S=(atb+o)/2 Print are
Area=sqrt(s*(s-a)*(s-b)*(s-c)) tf
WRITE the output area C STOP34 - Problem Solving and Python Programming
Example 4: Swapping using temporary variables
ALGORITHM
Step 1: Start
Step 2: Read the values a,b
Step 3: Swap the values using a temporary variable
Step 3.1: ta
Step3.2: a-b
Step 3.3: b=t
Step 4: Print the value of a,b
Step 5: Stop.
PSEUDOCODE
READ the value of ab
a
ab
bet
WRITE the swapped value of a,b
Example 5: Find the given year in a leap year or not
ALGORITHM
Step 1: Start
Step 2: Read the year
Step 3: if (year mod 4)=0 then
Step 3.1: print itis a leap year
Step 3.2:
Step 4: Stop.
se print it is not a leap year
C sae
/ Read a, b, ¢ /
v
U
Print
Leap YearPseudocode
READ the value of year
IF (year mod 4) =0 THEN
WRITE the year is a leap year
ELSE WRITE the year is not leap year
ENDIF
Example 6: find the greatest of 3 numbers
ALGORITHM
Step 1: Start
Step 2: Read the value of a,b,c
Step 3: Compare the values of ab,
Step 4: if a is greater than b, compare a with
Algorithmic Problem Solving - 35
—_
Vas
©
x
Step 4.1: ifa is greater than c then printa is greater Cove)
Step 4.2: ifa is not greater than bé&c then compare b and c.
Step 4.3: If bis greater than c print is greater else print is greater
Step 5: Stop.
PSEUDOCODE
READ the values of a,b,c
IF(a>b) && (a>c) THEN
WRITE ais greater
ELSE
IF (b>c) THEN
WRITE bis greater
ELSE
WRITE cis greater
ENDIF
ENDIF36 - Problem Solving and Python Programming
Example 7: Check whether the given number is even or odd
ALGORITHM ——
CO stant
Step 1: Start
Step 2: Read the values of n / Reda
Step 3: If (n mod 2)-0 then print itis an even number
Else print itis on odd number
Step 4: Stop.
Print
‘ODD Number
PSEUDOCODE
READ the value of n
IF (n%2==0) THEN
WRITE nis even number
ELSE
WRITE nis odd number
ENDIF
Example 8: Find the roots of quadratic equation
ALGORITHM
Step 1: Start
Step 2: READ the values of a,b,c
Step 3: Find the value of D using the formula
D=b*b-4"a*c
Step 4: if the value D is greater than or equal to zero then find the two rootsAlgorithmic Problem Solving - 37
Rootl=(-b+sqrt(GD))/(2*a)
Root2=(-b-sqrt(GD))/(2*a)
Step 5: print the two roots rootl, root2
Step 6: If D less than 0 print the roots are imaginary
—
~
Step 7: Stop. Kosmar)
PSEUDOCODE Read a,b,c
READ the value of a,b,c
Deb-srare
FIND the discriminate |
D=b*b-4*a*e
CALCULATE { YES. e
Root 1=(-b+sqrt(GD))/(2*
oo sqrt(GD))/2*a) roott = Cbesqet (D)/2"=) Print
root = Chae") ots are imaginary
Root2=(-b-sqrt(GD))/(2*a)
WRITE rootl, root2
ELSE
WRITE roots are imaginary
ENDIF
Example 9: Find the factorial of a given number
ALGORITHM
Step 1: Start
Step 2: Initialize the value of fact and to 1
Step 3: read the value of n
Step 4: if i
START
Step 4.2: i-i+1 NN
Step 5: go to step 4. Tales
rel
Step 6: print fact. fact=1
Step 7: Stop.
Read
PSEUDOCODE
SET initial one to fact i
READ the value of n
WHILE(<=n)
vis
Fact-fact'i ¥
fact=fact*1
iit isin
ENDWHILE
REPEAT WHILE until the condition fail
WRITE the value of fact
Example 10: To Print reverse of a number.
ALGORITHM
Step 1: Start
Step 2: Initialize r=0, sum=0
Step 3: Read the value of n
Step 4: if n>0 do the following else go to step 6
Step 4.1: =n mod 10Step 4.2: sum=sum?*10+r
Step 4.3: n=n div 10
Step 5: go to step 4
Step 6: Printsum
Step 7: Stop.
PSEUDOCODE
SET initial of n
READ the value of n
WHILE (n>0)
rn mod 10
sum=sum*10+r
nen div 10
ENDWHILE
REPEAT WHILE until the condition fail
WRITE the sum
Algorithmic Problem Solving - 39
Tnitialize
r=0
fact=0.
yes
Ten 10
um *10+r
n=n/10
Example 11: Find Fibonacci series for the first 'n' terms
ALGORITHM
Step 1: Start
Step 2: Assign F1-0, F2=1, F=0
Step 3: Read the value of n
Step 4: print the values of FI, F2
Step 5: Calculate40 - Problem Solving and Python Programming
FSFI+F2
Step 6: if(F)
NU?
Step 3.2: HRA =0.20* basic :s
Read basic
Step 3.3: CCA =200
Step 3.4: Net salary=basictDA+HRA+CCA.
Calculate
072° basic
basic
0
Step 4: Calculate PF=0.08*basic
Net Salary = basi
Step 5: Calculate Gross Salary 1
= PP Catealate
Gross Salary=net salary-PI cat
Step 6: Print the Gross Salary v
acute
Step 7: Stop. row Say = Net Salary PF
Print
Grose Salary
READ the value of basic calculate the allowances, net salary and gross Falary
PSEUDOCODE
DA=0.72" basic C sr >)
NW
HRA = 0.20* basic
CCA =200
Net salary=basic+DA+HRA+CCA
CALCULATE PF and Gross Salary
PF=0.08*Basic
Gross Salary=net salary - PF
WRITE Gross Salary
Example 13: Check whether the given string in palindrome or not
ALGORITHM,
Step 1: Start
Step 2: Read the input string S1, $242. - Problem Solving and Python Programming
Step 3: Compare SI and $2 Caer)
Step 4: If the strings are same then print “palindrome”
/ next ssa /
else print “not palindrome”
Step 5: Stop CaleaTate
result = stremp
(51,52)
PSEUDOCODE
READ S1, $2 “
CALCULATE y
v
Print Print
Result-stremp(s1,S2) Palindrome Not Palindrom
IF (Result=-0) THEN >
WRITE palindrome
ELSE C sr)
WRITE not palindrome -
ENDIF m=
na
5, av
Example 14: Convert the string into lowercase.
ALGORITHM =,
Step 1: Start xX
Step 2: Enter the string <> ° J
Step 3: Check the loop until null character ralindrome me ney
Step 4: Print the character of the string into \,—_]
lower case using its function
Cor)
Step 5: Stop. —Algorithmic Problem Solving - 43
PSEUDOCODE
READ the string st
WHILE (st[i]!="\0’)
WRITE to lowercase using the function str/wr(st)
in
ENDWHILE
Example 15: Find the sum of all even numbers between 0 and 100
ALGORITHM
Step 1: Start
Step 2: Initialize Sum=0,
Step 3: If i<-100, go to step 4 else go to step 7
Step 4: sum=sum+i
Step 5: i-it2
Initialize
Step 6: Go to step 3
Sum =
Step 8: Stop. it
ice 100
PSEUDOCODE
SET sum=0,i-0
Y Print /
REPEAT Sum=Sum+i
Sum=Sum+i
v
until i<=100 Init2
PRINT Sum44 - Problem Solving and Python Programming
Example 16: Print the following sum of numbers 1,2,3...
ALGORITHM
Step 1: Start
Step 2: Enter the input value, n
Step 3: Initialize count=1
Step 4: Display count
Step 5: Count=Count#1
Step 6: if count<=n
goto Step 4
else
go to Step 7
Step 7: Stop.
PSEUDOCODE
GET the input value, n
SET Count1
REPEAT
PRINT Count
Count-Count+1
until count<=n,
Initialise
count =1
Count = Count +1
x
it
count <= n>-YESDATA, EXPRESSIONS,
STATEMENTS
ed
[Python interpreter and interactive mode; values and types: int, float, boolean, string,
land list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use, flow of execution|
lparameters and arguments; Illustrative programs: exchange the values of two variables
Icirculate the values of n variables, distance between two points.
Python is a powerful high-level, object-oriented programming language created by
Guido van Rossum, It has simple easy-to-use syntax, making it the perfect language for
someone trying to learn computer programming for the first time.
1, PYTHON PROGRAMMING - THE BASICS
Before getting started, lets get familiarized with the language first.
Python is a general-purpose language. It has wide range of applications from
Web development (like: Django and Bottle), scientific and mathematical computing
(Orange, SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D).
The syntax of the language is clean and length of the code is relatively short. It's
fun to work in Python because it allows you to think about the problem rather than
focusing on the syntax.
1.1 HISTORY OF PYTHON
Python is a fairly old language created by Guido Van Rossum. The design began
in the late 1980s and was first released in February 1991.
Why Python was created?
In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating
system group. He wanted to use an interpreted language like ABC (ABC has simple46 - Problem Solving and Python Programming
easy-to-understand syntax) that could access the Amoeba system calls. So, he decided
to create a language that was extensible. This led to design of a new language which
was later named Python.
Why the name Python?
No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series from
late seventies. The name "Python" was adopted from the same series "Monty Python's
Flying Circus’,
1.2 FEATURES OF PYTHON PROGRAMMING.
+ A simple language = which ~—is-_—s easier ~=— to. ——dearn
Python has a very simple and elegant syntax. It's much easier to read and write
Python programs compared to other languages like: C++, Java, C#, Python makes
programming fun and allows you to focus on the solution rather than syntax. If
you are a newbie, it's a great choice to start your journey with Python.
* Free and open-source You can freely use and distribute Python, even for
commercial use. Not only can you use and distribute software's written in it, you
can even make changes to the Python's source code. Python has a large
community constantly improving it in each iteration.
* Open Source General Purpose Language
* Automatic Memory Management
Support variety of Basic Datatypes
* Great Interactive Environemt
Supports Object Oriented Programming
* Runs on All Operating Systems
Interpreted LanguageData, Expressions, Statements -47
Portability
You can move Python programs from one platform to another, and run it without
any changes.
Itruns seamlessly on almost all platforms including Windows, Mac OS X and
Linux.
Extensible and Embeddable
Suppose an application requires high performance. You can easily combine pieces
of C/C+ or other languages with Python code
This will give your application high performance as well as scripting capabilities
which other languages may not provide out of the box.
A high-level, interpreted language
Unlike C/C++, you don't have to worry about daunting tasks like memory
management, garbage collection and so on.
Likewise, when you run Python code, it automatically converts your code to the
language your computer understands. You don't need to worry about any lower-
level operations.
Large standard libraries to solve common tasks
Python has a number of standard libraries which makes life of a programmer
much easier since you don't have to write all the code yourself. For example: Need
to connect MySQL database on a Web server? You can use MySQLdb library
using import MySQLdb .
Standard libraries in Python are well tested and used by hundreds of people. So
you can be sure that it won't break your application.
Object-oriented
Everything in Python is an object. Object oriented programming (OOP) helps
you solve a complex problem intuitively.
With OOP, you are able to divide these complex problems into smaller sets by
creating objects.48 - Problem Solving and Python Programming
1.3 APPLICATIONS OF PYTHON
+ Web Applications
You can create scalable Web Apps using frameworks and CMS (Content
Management System) that are built on Python. Some of the popular platforms for
creating Web Apps are: Django, Flask, Pyramid, Plone, Django CMS,
Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
io
pe acd
* Scientific and Numeric Computing
There are numerous libraries available in Python for scientific and numeric
computing. There are libraries like: SciPy and NumPy that are used in general purpose
computing. And, there are specific libraries like: EarthPy for earth science, AstroPy for
Astronomy and so on.
Also, the language is heavily used in machine learning, data mining and deep
learning.
© Creating software Prototypes
Python is slow compared to compiled languages like C++ and Java. It might not
bea good choice if resources are limited and efficiency is a must.
However, Python is a great language for creating prototypes. For example: You
can use Pygame (library for creating games) to create your game's prototype first. If you
like the prototype, you can use language like C++ to create the actual game.Data, Expressions, Statements -49
* Good Language to Teach Programming,
Python is used by many companies to teach programming to kids and newbies.
It is a good language with a lot of features and capabilities. Yet, it's one of the
easiest language to learn because of its simple easy-to-use syntax.
1.4 REASONS TO CHOOSE PYTHON AS FIRST LANGUAGE
* Simple & Easy To Learn
Python is extremely simple and easy to learn. Itis a very powerful language and it
closely resembles the English language!
Pythonis
+ Free & open source
+ High-level
+ Interpreted
+ Blessed with large community
Furthermore, in Python, you don’t have to deal with complex syntax, you can refer
to the below image:
JAVA Python
public class Helloworld { Print(’Hello, World”)
public static void main(string{ ] age ){ It'S that SIMPLE!
system.out printin(’Hello,woorld”);
; }
If you have to print ‘hello world’, you have to write above three lines whereas in
Python, just one line is sufficient to print “hello world”. It’s that SIMPLE guys!
+ Simple Elegant Syntax
Programming in Python is fun. It's easier to understand and write Python code.
Why? The syntax feels natural. Take this source code for an example:50 - Problem Solving and Python Programming
a=2
b=3
sum=a+b
print(sum)
Even if you have never programmed before, you can easily guess that this
program adds two numbers and prints it.
. Not overly strict
You don't need to define the type of a variable in Python. Also, it's not necessary
to add semicolon at the end of the statement.
Python enforces you to follow good practices (like proper indentation). These
small things can make learning much easier for beginners.
+ Expressiveness of the language
Python allows you to write programs having greater functionality with fewer
lines of code. 1.5 Run Python on Your Operating System
Install and Run Python in Windows
1. Go to Download Python page on the official s
fe and click Download Python
3.6.0 (You may see different version name).
2. When the download is completed, double-click the file and follow the instructions
to install it, When Python is installed, a program called IDLE is also installed
along with it. It provides graphical user interface to work with Python.
3. Open IDLE, copy the following code below and press enter.
print("Hello, World!")
4. To createa file in IDLE, go to File > New Window (Shortcut: Ctrl+N),
5. Write Python code (you can copy the code below for now) and save (Shortcut:
Ctrl+S) with .py file extension like: hello.py or your-first-program.py
print "Hello, World!")
6. Go to Run > Run module (Shortcut: F5) and you can see the output.
Congratulations, you've successfully run your first Python program.Data, Expressions, Statements -51
1.4.1 Your First Python Program
Often, a program called "Hello, World!" is used to introduce a new programming
language to beginners. A "Hello, World!” is a simple program that outputs "Hello,
World!
However, Python is one of the easiest language to learn, and creating "Hello, World!”
program is as simple as writing print("Hello, World!"). So, we are going to write a
different program.
# Add two numbers
num =3
num2=5
sum = num1+num2
soe ey
print(sum)
How this program works?
Line 1: # Add two numbers
Any line starting with # in Python programming is a comment.
Comments are used in programming to describe the purpose of the code. This helps
you as well as other programmers to understand the intent of the code. Comments are
completely ignored by compilers and interpreters.
Line 2: num] =3
Here, num1 is a variable. You can store a value in a variable. Here, 3 is stored in this
variable,
Line 3: num:
Similarly, 5 is stored in num? variable.
Line 4: sum =num1+num2
The variables num1 and num2 are added using + operator. The result of addition is then
stored in another variable sum.
Line 5: print(sum)
‘The print() function prints the output to the screen. In our case, it prints 8 on the screen52. - Problem Solving and Python Programming
Few Important Things to Remember
To represent a statement in Python, newline (enter) is used. The use of
semicolon at the end of the statement is optional (unlike languages like C/C++,
JavaScript, PHP). In fact, it's recommended to omit semicolon at the end of the
statement in Python.
Instead of curly braces {}, indentations are used to represent a block.
im_a_parent:
im_a_child:
im_a_grand_child
im_another_child:
im_another_grand_child
2. PYTHON INTERPRETER AND INTERACTIVE MODE
Let us execute programs in different modes of programming.
2.1 Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt -
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
‘opyright'’, “credits” or “license” for more information.
Type "help",
>>
Type the following text at the Python prompt and press the Enter -
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement
with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this
produces the following result -
Hello, Python!Data, Expressions, Statements -53
2.2 Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no
longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type
the following source code in a test.py file -
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this
program as follows -
$ python test. py
This produces the following result ~
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file
#!/usr/bin/python
print "Hello, Python!”
We assume that you have Python interpreter available in /usr/bin directory. Now, try to
run this program as follows -
$chmod 4x testy # This is to make file executable
$./test.py
This produces the following result ~
Hello, Python!
2. PYTHON VALUES AND TYPES
A value is one of the fundamental things — like a word or a number — that a program
manipulates.54 - Problem Solving and Python Programming
3.1 Data types in Python
Every value in Python has a data type. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these
classes.
Dictionary
1_ 1_} t ]
T | I
Numeric Tuple Set
There are various data types in Python. Some of the important types are listed below.
Numbers
ust
tuple
Strings
Set
& Dietionary
3.1.1 Python Numbers
Integers, floating point numbers and complex numbers falls under Python
numbers category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs
to and the isinstance () function to check if an object belongs to a particular class.Data, Expressions, Statements -55
Program
1 =o
2 print(a, “is of type", type(a))
3
4 a= 2.0
5 print(a, "is of type", type(a))
6
7 a= lj
8 print(a, “is complex number?", isinstance(1+2j,complex))
Output
5 is of type
2.0 is of type
(142) is complex number? True
Integers can be of any length, it is only limited by the memory available.
A floating point number is accurate up to 15 decimal places. Integer and floating
points are separated by decimal points. 1 is integer, 1.0 is floating point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is
the imaginary part. Here are some examples.
>>> a = 1234567890123456789
>> a
1234567890123456789
>>> b = @.1234567890123456789
>>> b
. 12345678901234568
>>> c = 12]
>>> €
(1423)56 - Problem Solving and Python Programming
3.1.2 Python List
List is an ordered sequence of items. It is one of the most used data type in
Python andis very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are
enclosed within brackets [].
>>> a = [1, 2.2, 'python']
We can use the slicing operator | ] to extract an item or a range of items from a
list. Index starts form 0 in Python.
Program
Reeavanbune
Ss
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print(“a[2] =", a[2])
# a[0:3] = [5, 10, 15]
print(” j=", a[@:3])
# a[5:] = [30, 35, 4a]
print("a[5:] =", a[5:])
= 15
] = [5; 10, 15]
= [30, 35, 40]Data, Expressions, Statements -57
Lists are mutable, meaning; value of elements of a list can be altered.
>>> a = [1,2,3]
>>> al2]=4
>>> a
[1, 2, 4]
3.1.3 Python Tuple
Tuple is an ordered sequences of items same as list. The only difference is that
tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot,
change dynamically.
Itis defined within parentheses () where items are separated by commas.
>>> t = (5,'program', 1433)
We can use the slicing operator [] to extract items but we cannot change its
value. Tuples are immutable, meaning; value of elements of a tuple cannot be altered.
Program
& = (5,'progran’, 1433)
#t[1] = ‘program
print("t[1] =", t[1])
# t[0:3] = (5,
print("t[0:3]
"program", (1+3j))
» t[@:3])
# Generates error
# Tuples are inmutable
t[o] = 10
bEeaVaMeUNe
Rs58 - Problem Solving and Python Programming
Output
t[1] = program
t[a:3] = (5, "program", (1+33))
Traceback (most recent call last):
File “>> Ss
>>> Ss
This is a string”
"""a multiline
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Program
5 = "Hello world!"
# s[4] = ‘0
print("s[4] = ", s[4])
# s[6:11] = ‘world’
print("s[6:11] = ", s[6:12))
# Generates error
# Strings are inmutable in Python
s[5] ="4"
ee
eSData, Expressions, Statements -59
Traceback (most recent call last):
File "", line 11, in «moduler
s(5] ="d'
TypeError: "str
object does not support item assignment
3.15 Python 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.
Program
1 f= {5,2,3,1,4}
2
3 # printing set variable
4 print("a =", a)
5
6 # data type of variable a
7 print(type(a))
Output
as {1, 2,3, 4, 5}
We can perform set operations like union, intersection on two sets. Set have
unique values. They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}60 - Problem Solving and Python Programming
Union:
Union of A and B is a set of all the elements from both sets. Union is performed
using | operator. Consider the below example:
1 A={1,2,3,4}
2 B=(3,4,5, 6}
3 print(A |B)
Output = (1, 2, 3, 4, 5, 6}
Intersection:
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator. Consider the example below:
Mm ane
1 A=(1,2,3,4)
2 B=(3,4,5,6)
3 print(A &B)
Output = (3, 4}
Difference: erData, Expressions, Statements -61
Difference of A and B (A - B) is a set of elements that are only in A but not in B.
Similarly, B — A is a set of element in B but not in A. Consider the example below:
1 A={1,2,3,4, 5}
2 B=(4,5, 6,7, 8}
3 print(A - B)
Output = {1, 2, 3}
Symmetric Difference:
Symmetric Difference of A and B is a set of elements in both A and B except
those that are common in both. Symmetric difference is performed using operator.
Consider the example below:
1 A={1,2,3,4, 5}
2 B=(4,5, 6,7, 8}
3 print(A * B)
Output = {1, 2, 3, 6, 7, 8}
Since, set are unordered collection, indexing has no meaning. Hence the slicing
oneratar [does not werk
>>> a = {1,2,3}
>>> a1]
Traceback (most recent call last):
File "", line 301, in runcode
File “interactive input>", line 1, in
TypeError: ‘set" object does not support indexing62. - Problem Solving and Python Programming
3.1.6 Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are
optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair
in the form key:value. Key and value can be of any type.
y>> d = {1:'value", key" :2}
>>> type(d)
We use key to retrieve the respective value, But we cannot use the value to get
the respective key.
Program
1 Wd = {1:"value’, "key" :2}
2 print(type(d))
3
4 print("d[1] = ", d[1]);
5
6 print("d['key"] = ", d["key"]);
7
3 # Generates error
9 print("d[2] = ", d[2])3
Output
a2]
d['kData, Expressions, Statements -63
Traceback (mast recent call last):
File "", line 9, in
print("d[2] » a[2])5
KeyError: 2
2, Python Identifiers
Identifier is the name given to entities like class, functions, variables ete. in
Python. It helps differentiating one entity from another.
4.1 Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1 and
print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. Ivariable is invalid, but variablel is
perfectly fine.
Keywords cannot be used as identifiers.
We cannot use special symbols like !, , #, $, % etc. in our identifier
a
Identifier can be of any length.
5, Python Variables
A variable is a location in memory used to store some data (value).
They are given unique names to differentiate between different memory
locations, The rules for writing a variable name are same as the rules for writing
identifiers in Python.
A-16 Memory
A=16
B=20 p20 | | Memory
C= ‘edureka’
C="edureka’| | Memory64 - Problem Solving and Python Programming
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. We don't even have to declare the type of the
variable. This is handled internally according to the type of value we assign to the
variable.
5.1 Variable assignment
We use the assignment operator (=) to assign values to a variable. Any type of
value can be assigned to any valid variable.
a-=5
Ese
c = “Hello”
oc
0
Here, we have three assignment statements. 5 is an integer assigned to the
variable a.
Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of
characters) assigned to the variables b and c respectively.
5.2 Multiple assignments
In Python, multiple assignments can be made in a single statement as follows:
a, b, ¢ = 5, 3.2, “Hello”
If we want to assign the same value to multiple variables at once, we can do this
as
x y = Zz = “same'Data, Expressions, Statements -65
This assigns the "same" string to all the three variables.
6. Python 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.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.3 version. This number can vary slightly in
course of time.
Alll the keywords except True, False and None are in lowercase and they must
be written as it is.
The lists of all the keywords are given below:
> False > class > finally > is > retum
> None > continue > for > lambda > ey
> Tre > def > from > nonlocal > while
> and > del > global > not > with
> as > lif > if > or > yeild
> assert > else > import > pass
> break > except > in > raise
7. Expression
An expression is a combination of values, variables, operators, and calls to
functions. If you type an expression at the Python prompt, the interpreter evaluates it
and displays the result, which is always a value:66 - Problem Solving and Python Programming
»> Led
2
39> Len( "hello")
5
In this example len is a built-in Python function that returns the number of characters in
a string.
The evaluation of an expression produces a value.
>>> 47
17
>> y = Bde
>>> x = len(‘hello')
>>> x
5
>>> y
3.14
8. Python Statement
Instructions that a Py thon interpreter can execute are called statements.
For example, a= 1 is an assignment statement. if statement, for statement, while
statement ete. are other kinds of statements which will be discussed later.
8.1 Multi-line statement
In Python, end of a statement is marked by a newline character. But we can
make a statement extend over multiple lines with the line continuation character (\).
For example:Data, Expressions, Statements -67
This is explicit line continuation. In Python, line continuation is implied inside
parentheses ( ), brackets [] and braces { }. For instance, we can implement the above
multi-line statement as
w
a= (1
+ +
4+ +
7+
oun
wn
+
+
+ 9)
Here, the surrounding parentheses () do the line continuation implicitly. Same is the
case with [] and
{}. For example:
colors = ['red’,
‘blue’,
‘green']
We could also put multiple statements in a single line using semicolons, as follows
8. Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the
first unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block,68 - Problem Solving and Python Programming
Generally four whitespaces are used for indentation and is preferred over tabs. Here is
an example.
Program
> for d in range(1,11):
2 print(i)
3B if i= 5:
4 break
Output
1
2
3
4
5
The enforcement of indentation in Python makes the code look neat and clean.
This results into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always
indent. It makes the code more readable. For example:
if True:
print ("Hello")
a=5
and
if True: print("Hello’); a = 5Data, Expressions, Statements -69
Both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into Indentation Error.
9. Tuple Assignment
Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the right of
the as
‘ignment.
(name, surname, birth_year, movie, movie year, profession, birthplace) = julia
This does the equivalent of seven assignment statements, all on one easy line.
One requirement is that the number of variables on the left must match the number of
elements in the tuple.
Once in a while, it is useful to swap the values of two variables. With
conventional assignment statements, we have to use a temporary variable. For example,
to swap a and b:
temp = a
a=b
b = temp
Tuple assignment solves this problem neatly:
(a, b) = (by a)
The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments. This feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the
right have to be the same.70 - Problem Solving and Python Programming
>>> (a, b, c, d) = (1, 2, 3)
Valuetrror: need more than 3 values to unpack
10. Precedence and Associativity of Operators in Python
The combination of values, variables, operators and function calls is termed as
an expression. Python interpreter can evaluate a valid expression.
For example:
px» 5B - 7
-2
Here 5 - 7 is an expression, There can be more than one operator in an
expression.
To evaluate these type of expressions there is a rule of precedence in Python. It
guides the order in which operation are carried out.
For example, multiplication has higher precedence than subtraction.
vultiplication has higher precedence
# than subtraction
# Output: 2
lo-4%2
BWR
But we can change this order using parentheses () as it has higher precedence.
1} Parentheses () has higher precendence
2 # Output: 12
3B (19-4) ' 2
The operator precedence in Python is listed in the following table. It is in
descending order, upper group has higher precedence than the lower ones.Data, Expressions, Statements -71
SL.NO | Operators Meaning
~ Jo Parentheses
2 |= Exponent
3. | 4x, -x,-x Unary plus, Unary minus, Bitwise NOT
4S LI, % Multiplication, Division, Floor division, Modulus
5. - Addition, Subtraction
6 cco shift operators
7 |& AND
8 4 Bitwise XOR
9. Bitwise OR
10. . Comparisions, Identity, Membership operators
not, in, not in
1. | not Logical NOT
12. | and Logical AND
13. Jor Logical OR
11.2 Associativity of Python Operators
We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
When two operators have the same precedence, associativity helps to determine
which the order of operations,
Associativity is the order in which an expression is evaluated that has multiple
operator of the same precedence
associativity.
Almost all the operators have left-to-right72 - Problem Solving and Python Programming
For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.
oyan buns
Left-right assaciativity
# Output: 3
print(S5 #2 //
3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
HOU bw Ne
Exponent operator * has right-to-left associativity in Python.
# Right-left associativity of ** exponent operator
# Output: 512
print(2 ** 3 ** 2)
# Shows the right-left associativi
fof *
# Output: 64
print((2 ‘* 3) ** 2)
We can see that 2** 3 ** 2 is equivalent to 2** (3 2).
11.3 Non associative operators
Some operators like assignment operators and comparison operators do not
have associativity in Python. There are separate rules for sequences of this kind of
operator and cannot be expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y >> import example
This does not enter the names of the functions defined in example directly in the
current symbol table. It only enters the module name example there.
Using the module name we can access the function using dot (.) operation. For
example:
>>> example.add(4,5.5)
9.576 - Problem Solving and Python Programming
Python has a ton of standard modules available.
You can check out the full list of Python standard modules and what they are
for. These files are in the Lib directory inside the location where you installed Python.
Standard modules can be imported the same way as we import our user-defined
modules.
13.2 Python import statement
We can import a module using import statement and access the definitions
inside it using the dot operator as described above. Here is an example.
Program
1 inport statement example
2 # to import standard module math
3
4 import math
5 print("The value of pi is", math.pi)
When you run the program, the output will be:
The value of pi is 3.141592653589793
13.3 Import with renaming
We can import a module by renaming it as follows.
% import module by renaming it
1
2
3 import math as m
4 print("The value of pi is", m.pi)
When you run the program, the output will be:Data, Expressions, Statements -77
The value of pi is 3.141592653589793
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, m.pi
is the correct implementation
13.4 Python from...import statement
We can import specific names form a module without importing the module as a
whole. Here is an example.
$e import only pi from math module
1
2
3 from math import pi
4 print("The value of pi is", pi)
Output
The value of pi is 3.141592653589793
We imported only the attribute pi form the module.
In such case we don't use the dot operator. We could have imported multiple attributes
as follows.
>>> from math import pi, e
>>> pi
3. 141592653589793.
>>> @
2.71828182845904578 - Problem Solving and Python Programming
13.5 Import all names
We can import all names (definitions) form a module using the following construct.
1 # import all names form
2. # the standard module math
3
4 from math import #
5 print("The value of pi is", pi)
Output
The value of pi is 3.141592653539793
We imported all the definitions from the math module. This makes all names
except those beginnig with an underscore, visible in our scope.
Importing everything with the asterisk (*) symbol is not a good programming
practice. This can lead to duplicate definitions for an identifier. It also hampers the
readability of our code.
14. Python Functions
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
® Python FunctionsData, Expressions, Statements -79
Syntax of Function
def function_name(parameters ):
"" docstring"™"
statement (s)
Above shown is a function definition which consists of following components.
Keyword def marks the start of function header.
2. A function name to uniquely identify it. Function naming follows the same rules
of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements
must have same indentation level (usually 4 spaces).
7. An optional return statement to retum a value from the function.
Example of a function
1> def greet(name):
2 “""This function greets to
3 the person passed in as
4 parameter"""
5 print("Hello, "+ name +". Good morning!")
6
7 greet ("MAHADEVAN")
Output
Hello, MAHADEVAN. Goad morning!80 - Problem Solving and Python Programming
Function Call
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 parameters.
>>> greet("Paul")
Hello, Paul. Good morning!
The return statement
The return statement is used to exit a function and go back to the place from
where it was called,
Syntax of return,
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.
For example:
>>> print(greet ("May ))
Hello, May. Good morning!
None
Here, None is the returned value.Data, Expressions, Statements -81
Example of return
I> def absolute_value(num):
2 “This function returns the absolute
3 value of the entered number"""
4
57 if num >= @:
6 return num
7 else:
8 return -num
a
16 # Output: 2
11 print(absolute value(2))
130 # Output: 4
14 print(absolute_value(-4))
Output
2
4
14.1 Flow of execution
When you are working with functions itis really important to know the order in
which statements are executed. This 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. Function calls are like a detour in the flow
of execution. Instead of going to the next 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.82. - Problem Solving and Python Programming
def functionName():
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 body of the function until you reach a
point where that function is called.
14.2 Types of Functions
Basically, we can divide functions into the following two types:
1. Bui
-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
14.2.1 Built in Functions:
The Python interpreter has a number of functions that are always available for
use. These functions are called built-in functions. For example, print() function prints
the given object to the standard output device (screen) or to the text stream file.
In Python 36 (latest version), there are 68 builtin functions. They are listed
below alphabetically along with brief description.Data, Expressions, Statements -83
BUILTIN
SL.NO | FUNCTION DESCRIPTION
NAME
1. | abs returns absolute value of a number
allo returns true when all elements in iterable is true
3. [any Checks if any Element of an Iterable is True
ascii() Returns String Containing Printable Representation
5. | bind converts integer to binary string
bool) Coverts a Value to Boolean
7. | bytearray) returns array of given byte size
bytes) returns immutable bytes object
9% | callabled Checks if the Object is Callable
10. | chr0) Returns a Character (a string) from an Integer
11. | classmethod) _| returns class method for given function
12. | compile() Returns a Python code object
13. | complex) Creates a Complex Number
14, | delattrd Deletes Attribute From the Object
15. | dict Creates a Dictionary
16. | dir) Tries to Return Attributes of Object84 - Problem Solving and Python Programming
V7. divmod() Returns a Tuple of Quotient and Remainder
4g, | enumerate() Returns an Enumerate Object
19, | eval Runs Python Code Within Program
49, | exec Executes Dynamically Created Program
nn, | filter constructs iterator from elements which are tue
99, | float) returns floating point number from number, string,
23, | format) returns formatted representation of a value
2g, | frozenset() returns immutable frozenset object
25, getattr) returns value of named attribute of an object
96, | globals0 returns dictionary of current global symbol table
77, | hasattr() returns whether object has named attribute
og, | hash0 returns hash value of an object
9, | helpo Invokes the built-in Help System
30. hex() Converts to Integer to Hexadecimal
31, | id0 Returns Identify of an Object
32, | input) reads and retums a line of string,
int returns integer froma number or stringData, Expressions, Statements -85
isinstance()
Checks if a Object is an Instance of Class
issubclass() Checks if a Object is Subclass of a Class
iter retums iterator for an object
4.| lend Returns Length of an Object
list) creates list in Python
6-| locals) returns dictionary of current local symbol table
map() Applies Function and Returns a List
8.| max() returns largest element
9.] memoryview0 _| returns memory view of an argument
10) min() returns smallest element
11} next Retrieves Next Element from Iterator
12| object Creates a Featureless Object
13+ oct() converts integer to octal
14) open(. Returns a File object
15} ord returns Unicode code point for Unicode character
16| pow() returns x to the power of y
17 print()
Prints the Given Object86 - Problem Solving and Python Programming
49, | PropertyO returns a property attribute
20, | ranged return sequence of integers between start and stop
an, | teprO retums printable representation of an object
99 | reversed retums reversed iterator of a sequence
23, | round(, rounds a floating point number to ndigits places.
2g, | set0 returns a Python set
25, | setatirO sets value of an attribute of object
76, | sliced creates a slice object specified by range()
97, | sortedd retums sorted list from a given iterable
2g, | Staticmethod() creates static method from a function,
29, | stx0 returns informal representation of an object
30, | sum0 Add items of an Iterable|
31, | superO Allow you to Refer Parent Class by super
32, | tupled Creates a Tuple
33, | yPeO Retums Type of an Object
3a, | Yars0 Returns __dict__attribute of a class
35, | APO Retums an Iterator of Tuples
78, | import_0 ‘Advanced Function Called by importData, Expressions, Statements -87
14.2.2 User defined functions
Functions that we define ourselves to do certain specific task are referred as
user-defined functions. The way in which we define and call functions in Python are
already discussed,
Functions that readily come with Python are called built-in functions. If we use
functions written by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined
functions. So, our user-defined function could be a library function to someone else.
Advantages of user-defined functions
1. User-defined functions help to decompose a large program into small segments
which makes program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes
and execute when needed by calling that function.
Programmers working on large project can divide the workload by making
different functions.
Program
1 # Program to illustrate
200 # the use of user-defined functions
3
4> def add_numbers(x,y):
5 sum = x +
6 return sum
a numl = 5
9 num = 6
10
11 print("The sum is", add_numbers(numL, num2))
Output
The sum is 1188 - Problem Solving and Python Programming
Here, we have defined the function my_addition() which adds two numbers and
returns the result.
This is our user-defined function. We could have multiplied the two numbers
inside our function (it's all up to us). But this operation would not be consistent with the
name of the function. It would create ambiguity.
Itis always a good idea to name functions according to the task they perform,
In the above example, input(), print) and float() are builtin functions of the
Python programming language.
14.3 Function Arguments
In user-defined function topic, we learned about defining a function and calling,
it. Otherwise, the function call will result into an error. Here is an example.
> def greet(name,msg) :
"This function greets to
the person with the provided message”
1
2
3
4 print("Hello” name +, * + msg)
5
6
greet ("MAHADEVAIIf ,"Good mornin
Output
Hello MAHADEVAN, Good morning!
Here, the function greet() has two parameters.
Since, we have called this function with two arguments, it runs smoothly and we do not
get any error.
If we call it with different number of arguments, the interpreter will complain. Below is
a call to this function with one and no arguments along with their respective error
messages.Data, Expressions, Statements -89
>>> greet (" # only one argument
TypeError: greet() missing 1 required positional argument: ‘msg’
>>> greet() # no arguments
TypeError: greet() missing 2 required positional arguments: ‘name’ and ‘ms
14.4 Types of Function Arguments
Until now functions had fixed number of arguments. In Python there are other
ways to define a function which can take variable number of arguments.
Three different forms of this type are described below.
1. Default Arguments
2. Keyword Arguments
3. Arbitrary Arguments
14.4.1 Default Arguments
Function arguments can have default values in Python,
We can provide a default value to an argument by using the assignment operator (-)
Here is an example
Program
Ay def greet(name, msg
3 This function greets to
4 the person with the
5 provided message.
6
7 If message is not provided,
8 it defaults to "Good
9 morning!"
10"
a
12 print("Hello"yname +", * + msg)
B
14 greet("ahadevan")
15 greet("Periyasamy!","How do you do")90 - Problem Solving and Python Programming
Output
Hello Mahadevan, Good morning!
Hello Periyasamy, How do you do?
In this function, the parameter name does not have a default value and is required
(mandatory) during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is
optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For
example, if we had defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as
SyntaxError: non-default argument follows default argument
14.4.2 Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
according to their position
For example, in the above function greet(), when we called it as greet("Bruce","How do
you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do
you do?" to msg.
Python allows functions to be called using keyword arguments. When we call functions
in this way, the order (position) of the arguments can be changed. Following calls to the
above function are all valid and produce the same result.Data, Expressions, Statements -91
>>> # 2 keyword arguments
>>> greet(name = “Bruce” ,msg = “Haw da you do?")
>>> # 2 keyword arguments (out of order)
>>> greet(msg = "How do you do?" ,name “Bruce” )
>>> # 1 positional, 1 keyword argument
>>> gpeet(“Bruce”,msg = "How do you do?”)
As we can see, we can mix positional arguments with keyword arguments during a
function call. But we must keep in mind that keyword arguments must follow
positional arguments.
Having a positional argument after keyword arguments will result into errors. For
example the function call as follows:
greet (nane="Bruce”,"Hav do you do?")
Will result into error as:
SyntaxError: non-keyword arg after keyword arg
14.4.3 Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be
passed into a function. Python allows us to handle this kind of situation through
function calls with arbitrary number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote
this kind of argument. Here is an example.
Program
Ly det greet(namas) :
wtThis function greets
the person in the names
4 anes is 9 tuple with arguments
for name in names
prine("Wetlo" ynane)
grent("Vahadevan","pertyanany","Sathiahlirme”", "Vishalakshi")92. - Problem Solving and Python Programming
Output
Hello Mahadevan
Hello periyasamy
Hello Sathishkumar
Hello Vishalakshi
Here, we have called the function with multiple arguments. These arguments
get wrapped up into a tuple before being passed into the function. Inside the function,
we use a for loop to retrieve all the arguments back.
ILLUSTRATIVE PROGRAMS:
Program 1: EXCHANGE THE VALUES OF TWO VARIABLES
Source Code
x=int(input(Enter the value x:"))
y=int(input("Enter the value x:"))
print "Before Swapping x:",x,"y:"\y
temp=x
xy
y=temp
print "After Swapping x:
Output
Enter the value x: 10
Enter the value x: 20
Before Swapping x: 10 y: 20
After Swapping x: 20 y: 10
SCREEN SHOTS
1 ‘int(input("Enter the value x:"))
2 y int input (“enter the value x: )
3 print "Before Swapping x:",x,"y:"
4 temp=x
5 Key
6
7
print “After Swapping xData, Expressions, Statements -93
Program 2:CIRCULATE THE VALUES OF N VARIABLES
Source Code
listcirculation.py
#Function Program
def circulate(mylist):
print("Initial List:",mylist)
output=[]
for index in range(len(mylist)):
temp=mylist.pop(0)
mylist.append(temp)
outputappend(mylist{:])
print output
main.py
#Main Program
import listcirculation
mylist=[10,20,30,40]
listcirculation.circulate(my list)
OUTPUT
(‘Initial List:, [10, 20, 30, 40])
{{20, 30, 40, 10}, [30, 40, 10, 20), [40, 10, 20, 30}, [10, 20, 30, 40]]
SCREEN SHOTS
listcirculation.py94 - Problem Solving and Python Programming
1 #Function Program
2> def circulate(mylist):
3 print("Initial List:",mylist)
4 output=[]
Sr for index in range(len(mylist)):
6 temp=mylist .pop(®)
7 mylist .append(t emp)
8 output .append(mylist[:])
9 print output
1 #Main Program
2 import listcirculation
3. mylist=[10,20,30,40]
4 listcirculation.circulate(mylist)
Enh
re ee
Program 3: DISTANCE BETWEEN TWO POINTS.
Source Code:
def distance(x1, y1, x2, y2):
dx =x2- x1
dy =y2-yl
dsquared = dx**2 + dy**2
result = dsquared**0.5
return resultData, Expressions, Statements -95
x1=int(input("Enter x1")
yl=int(input("Enter y1"))
-int(input("Enter x2"))
y2=int(input("Enter y2"))
print "The distance is",distance(x1, yl, x2, y2)
Output
Enter x15
Enter y12
Enter x26
Enter y23
‘The distance is 1.4142135623730951
SCREENSHOTS
1+ def distance(x1, yl, x2, y2):
a dx = x2 - x1
3 dy = y2- yl
4 ed = dx''2 + dy''2
5 result = dsquared’ ‘0.5
6 return result
7
8 nt(input ("Enter )
9 nt (input ("Enter )
10 nt(input ("Enter )
11 y2=int(input ("Enter )
nt “The distance is",distance(xl, yl, x2, y2)96Control Flow, Functions - 97
/ CONTROL FLOW,
FUNCTIONS
a
Conditionals: Boolean values and operators, conditional (if), alternative (if-else)
lchained conditional (if-clif-else); Iteration: state, while, for, break, continue, pass
lFruitful functions: return values, parameters, local and global scope, functio
composition, recursion; Strings: string slices, immutability, string functions and]
methods, string module; Lists as arrays. Illustrative programs: square root, gcd,
lexponentiation, sum an array of numbers, linear search, binary search.
1, BOOLEAN VALUES
The Python type for storing true and false values is called bool, named after the
British mathematician, George Boole. George Boole created Boolean Algebra, which is the
basis of all modern computer arithmetic.
at
O oe
There are only two boolean values. They are True and False. Capitalization is
important, since true and false are not boolean values (remember Python is case
sensitive).98 - Problem Solving and Python Programming
Program
1 print (True)
2 print (type (True}}
3 print (type (False) }
4
Output
True
2. BOOLEAN EXPRESSION
A boolean expression is an expression that evaluates to a boolean value. The
equality operator, ==, compares two values and produces a boolean value related to
whether the two values are equal to one another.
Program
i print (5
2 print (5
3
= 5}
6)
Output
True
False
In the first statement, the two operands are equal, so the expression evaluates to True.
In the second statement, 5 is not equal to 6, so we get False.
3. PYTHON OPERATORS
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.Control Flow, Functions - 99
For example
>>> 243
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is
the output of the operation.
‘Comparison
Operators
Membership Identity
Operators Operators
Bitwise Logical
Operators |* Operators >| Operators
Assignment 4 \ Arithmetic
Operators Operators
Python has a number of operators which are classified below.
® Aithmetie Operators
4 Relational Operators (Comparison)
4 Logical Operators (Boolean)
& bitwise Operators
4 Assignment Operators,
°
‘Special Operators
3.1 ARITHMETIC OPERATORS
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication ete,100- Problem Solving and Python Programming
INo | Operator | Meaning Example
1 + ‘Add two operands or unary plus x
2 ; Subtract right operand from theleft or unary |»
minus
3. * Multiply two operands xty
4. / Divide left operand by the right one (always |
results into float)
5. % Modulus = remainder of the division of lft] ror xiy)
operand by the right
6 Floor division - division that results into
Wf whole number adjusted to the left in the | x//y
number line
7. Exponent - left operand raised to the power
” xMy (x to the power y)
of right
Program
1 #Apithmetic Operators
2
3
4 2xry)
5 oxy)
6 print ok ty)
7 print aX oy)
8 print sXY)
gq print akhty)
100) print ("x//y="Lx/ sy)Control Flow, Functions - 101
When you run the program, the output will be:
3.2 COMPARISON OPERATORS
Comparison operators are used to compare values. It is a type of Boolean operators
which either returns True or False according to the condition.
SLNo | Operator Meaning Example
1. Greater that - True if left operand is greater
than the right
2 Less that - True if left operand is less than the
< x xy
is greater than or equal to the right
6. Less than or equal to - True if left operand is
=“ ‘ x Bitwise right shift | x>>2=2 (0000 0010)
<< Bitwise left shift | x<<2 = 40 (0010 1000)Control Flow, Functions - 105
3.5 ASSIGNMENT OPERATORS
Assignment operators are used in Python to a
ign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a= a+5.
Assignment operators in Python
Operator | Example | Equivatent to106 - Problem Solving and Python Programming
3.6 SPECIAL OPERATORS
Python language offers some special type of operators like the identity operator
or the membership operator. They are described below with examples.
3.6, .1 Identity operators
is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables that are
equal does not imply that they are identical.
Identity operators in Python
Example
Operator | Meaning
True if the operands are identical (refer to the same object)
print(xl is not y1)
print(x2 is y2)
18 print(x3 is y3)
isnot | True if the operands are not identical (do not refer tothesame] x isnot
object) True
Program
1 #Special Operators
2 xL=5
3 yl=5
4 x2 = ‘Hello’
5 y2 = ‘Hello
6 «3 = [1,2,3]
7 y3 = [1,2,3]
8
gaControl Flow, Functions - 107
Here, we see that x1 and yl are integers of same values, so they are equal as well as
identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable (can be
changed), interpreter locates them separately in memory although they are equal.
3.6.2 Membership operators
in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary),
Ina dictionary we can only test for presence of key, not the value.
Operator | Meaning Example
in True if value/variable is found in the sequence | 5 inx
notin | True if value/variable is not found in the sequence | 5 not in x
Program
1 #"embership Operators
2 x = ‘Hello world
3 y= {i:ta',2:"b'}
4 print(*H" in x)
5 print( "hello" not in x)
64 print(1 in y)
7 print('a’ in y)108 - Problem Solving and Python Programming
Here, 'H' is in x but ‘hello’ is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, ‘a’ in y returns False.
4. CONDITIONAL STATEMENTS,
In programming and scripting languages, conditional statements or conditional
constructs are used to perform different computations or actions depending on the
evaluation of condition
The conditional statements available in python are listed below
> statement
> if else statement
> if -elf ~ else statement
> _Nestedif statement
4.1 if statement
Decision making is required when we want to execute a code only if a certain
condition is satisfied.
Here, the program evaluates the test expression and will execute statement(s)
only if the text expression is True.
If the text expression is False, the statement(s) is not executed
Python if Statement Syntax
if test expression:
statement(s)
In Python, the body of the if statement is indicated by the indentation. Body
starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.Program
Flt
2
3
4
5
6
7
8
9
19
Control Flow, Functions - 109
False
\True
Body of if
I
Fig: Operation of if statement
#if statement
num = 3
if num» @:
print (num,
print("This is
num = -1
if num > @:
print (num,
print("This is
“is a positive number .”)
always printed
“is a positive number
also always printed.")
number.
Pence
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True. When variable num is equal to
3, test expression is true and body inside body of if is executed. If variable num is equal
to -1, test expression is false and body inside body of if is skipped.110 - Problem Solving and Python Programming
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
4.2 Python if...else Statement
The if-else statement evaluates test expression and will execute body of if only
when test condition is True. If the condition is False, body of else is executed.
Indentation is used to separate the blocks.
Syntax of if...else
if test expression:
Body of if
else:
Body of else
Test False
Expression
Body of if | Body of else
j
Fig: Operation of if... else statement
Program
1 #if-else statement
2 num = 3
3+ if num >@:
4 print("Positive")
5+ else:
6 print("Negative number”)Control Flow, Funetions - 111
Output
Positive
In the above example, when num is equal to 3, the test expression is true and body of if
is executed and body of else is skipped.
4.3 Python if...clif...else
The elif is short for else if. It allows us to check for multiple expressions.If the condition
for if is False, it checks the condition of the next elif block and so on. If all the conditions
are False, body of else is executed
Syntax of if...clif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Only one block among the several if...elif...else blocks is executed according to the
condition
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif..else
‘Test
Expression
of if
False
True
Test \patse
Expression
fay oF of lif |
Prue
dy cee] foody ot ee
en
Fig Open112 - Problem Solving and Python Programming
Program,
1 #if-elif-else statement
2
3 num = 3.4
4> if num > 6:
5 print("Positive number")
6- elif num ®:
7 print(" Zero")
8- else:
a print("Negative number")
Output
Positive
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed. If num is negative, Negative number is printed
4.4 Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so must be avoided if
we can.
Program
In this program, we input a number
if the number
fan appropiate
This time we use
mum = Float Snpuc("Enter a ranber: *))
$f mm >= 0:
Te hun == 0:
rine("Zero")
else:
print("Positive number")
else!
print ("Wegative number")Control Flow, Functions - 113
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
llegative number
Output 3
Enter a number: 0
5, LOOPING STATEMENTS
A loop is a sequence of instructions that is continually repeated until a specific
condition is reached
The looping statements used in python are
> for loop
> forloop with else
> while loop
v
while! oop with else
5.1 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.114 - Problem Solving and Python Programming
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
Flowchart of for Loop
for each
item in
sequence
Last
item
reached?
Yes
Body of for
Exit loop
Fig: Operation of for loopControl Flow, Functions - 115
Program
1 # Program ta find the sum of all numbers stored in a list
# List of numbers
humbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = @
9 # iterate over the list
1@~ for val in numbers:
a sum = sumrval
13 # Output: The sum is 48
14 print("The sum is", sum)
Output
The sum is 48
5.1.1 The range( function
We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(startstop,step size). step size
defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list()
The following example will clarify this.
1 #range function in for loop
2 #print numbers from @ to 9 totally 10 values
3> for i in range(@,10):
4 print (i)
5116 - Problem Solving and Python Programming
7 #print particular values from the list
3 print("The List values are
9 list4=[0,1,2,3,4,5,6,7,8,9]
16+ for listl in range (3,8):
dW print (list1)
Output
ameneos
we arus
This List Value are
ane
No
5.2 for loop with else
A for loop can have an optional else block as well. The else part is executed if the items
in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop’s else part runs if no break occurs.
Here is an example to illustrate this.
1 #For loap with else statement
2 digits = [@, 1, 5]
3Control Flow, Functions - 117
4~- for i in digits:
5 print(i)
» Gy else:
7 print("No items left.")
Output
Here, the for loop prints items of the list until the loop exhaus|
. When the for loop
exhausts, it executes the block of code in the else and prints ” No items left.”
5.3 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.
We generally use this loop when we don't know beforehand, the number of
times to iterate.
Syntax of while Loop in Python
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end
Python interprets any non-zero value as True. None and 0 are interpreted as False.118 - Problem Solving and Python Programming
Flowchart of while Loop
Enter while loop
Test
Expression
Body of
While
Exit loop ¥
Fig: Operation of while loop
Program
# Program ta add natural
# numbers upta
# sum = 1+2+3+...4n
n = int(input("Enter n: "))
1
2
3
4
5 # To take input from the user,
6
E)
8 # initialize sum and counter
9
a sum = 8
wa i=l
ai
12+ while i <= on:
1B sum = sum +i
4 i= i+1 — # update counter
15
16 # print the sum
17 print("The sum is", sum)Control Flow, Functions - 119
In the above program, the test expression will be True as long as our counter variable i
isk
s than or equal to n (10 in our program)
We need to increase the value of counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never
ending loop).
Finally the result is displayed
5.4 while loop with else
Same as that of for loop, we can have an optional else block with while loop as.
The else part is executed if the condition in the while loop evaluates to False. The while
loop can be terminated with a break statement.
In such case, the else part is ignored. Hence, a while loop's else part runs if no break
occurs and the condition is false.
Here is an example to illustrate this
1 # Example to illustrate While loop with else
counter = @
+ while counter < 3:
6 print("while loop executes”)
7 counter = counter + 1
& 8~ else:
9 print("Else executes")120 - Problem Solving and Python Programming
Here, we use a counter variable to print the string “While loop executes” three times.
On the fourth iteration, the condition in while becomes False. Hence, the else part is
executed and prints “Else executes”
6. LOOP CONTROL STATEMENTS
In Python, break continue and pass statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes we wish
to terminate the current iteration or even the whole loop without checking test
expression.
The three loop control statements are
Break statement
Continue statement
Pass statement
6.1 Python break statement
The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax of break
break ater oop
Flowchart of break —
Remaining body
ol loepControl Flow, Functions - 121
The working of break statement in for loop and while loop is shown below.
for var in sequence:
# codes inside for loop
if condition:
break
# codes inside for loop
# codes outside for loop
while test expression:
# codes inside while loop
if condition:
break
# codes inside while loop
# codes outside while loop
Program
1 # Use of break statement inside loop
2
3+ for val in “string”:
4 if val == "i":
5 break
a print(val)
7
8 print("The end")
Output122 - Problem Solving and Python Programming
In this program, we iterate through the string” sequenc:
We check if the letter
is "i, upon which we break from the loop. Hence, we see in our output that all the
letters up till "i" gets printed. After that, the loop terminates.
6.2 Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next iteration,
Syntax of Continue
continue
Flowchart of continue |
Enter Loop
test expression
of loop
No
¥
Remaining body
of loop
Exit Loop
The working of continue statement in for and while loop is shown below.
for var So sequence:
4 codes inside for 100p
if condition:
continue
# codes inside for loop
4 codes outside for 1o0p
Uuhile test expression:
"codes inside while 109p
Af condition:
continue
1 codes outside while loopControl Flow, Functions - 123
Program
1 # Program to show the use of continue statement inside loops
2
3 for val in
a> if val
5 continue
6 print(val)
7
8 print("The end")
Output
This program is same as the above example except the break statement has been
replaced with continue.
We continue with the loop, if the string is "i", not executing the rest of the block. Hence,
we see in our output that all the letters except "i" gets printed.
6.3 pass statement
In Python programming, pass is a null statement. The difference between a comment
and pass statement in Python is that, while the interpreter ignores a comment entirely,
pass is not ignored.
However, nothing happens when pass is executed. It results into no operation (NOP).
Syntax of pass
pass
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.124 - Problem Solving and Python Programming
Program
1 #Program to illustrate pass statement
2 sequence = {'p', ‘a’, ‘s', ‘s*}
3> for val in sequence:
4 pass
Output
Blank Screen
We can do the same thing in an empty function or class as well.
def function (args):
pass
class example:
pass
7. Fruitful functions
8, RETURN VALUES
The built-in functions we have used, such as abs, pow, int, max, and range, have
produced results. Calling each of these functions generates a value, which we usually
assign to a variable or use as part of an expression.
1 biggest= max(3, 7, 2, 5)
2x=abs(3-11) +10
we are going to write more functions that return values, which we will call fruitful
functions, for want of a better name. The first example is area, which returns the area of
a circle with the given radius:
1 def area(radius):
2 b=3.14159 * radius™*2
3 return b
We have seen the return statement before, but in a fruitful function the return statement
includes a return value. This statement means: evaluate the return expression, and then
return it immediately as the result (the fruit) of this function. The expression provided
can be arbitrarily complicated, so we could have written this function like this:Control Flow, Functions - 125
1 def area(radius):
2 return 3.14159 * radius * radius
On the other hand, temporary variables like b above often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional. We have already seen the built-in abs, now we see how to write our own:
1 def absolute_value(x):
2 ifx<0:
3 return -x
4 else:
5 return x
Another way to write the above function is to leave out the else and just follow the if
condition by the second return statement,
1 def absolute_value(x):
2 ifx<0:
3 return-x
4 return x
Think about this version and convince yourself it works the same as the first one.
Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code, or unreachable code.
In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. The following version of absolute_value fails to do
this:
1 def bad_absolute_value(x):
2 ifx<0:
3 return-x
4 elifx>0:
5 returnx
This version is not correct because if x happens to be 0, neither condition is true, and the
function ends without hitting a return statement. In this case, the return value is a
special value called None:126 - Problem Solving and Python Programming
>>> print(bad_absolute_value(0))
None
All Python functions return None whenever they do not return another value.
It is also possible to use a return statement in the middle of a for loop, in which case
control immediately returns from the function. Let us assume that we want a function
which looks through a list of words. It should return the first 2-letter word. If there is
not one, it should return the empty string:
1 def find_first_2_letter_word (xs):
for wd in x:
if len(wd) = 2:
return wd
AON
o
return,
>>> find_first_2_letter_word(["This", "is",
is
‘dead’, "parrot"})
>>> find_first_2_letter_word({"I", "like", "cheese"))
Single-step through this code and convince yourself that in the first test case that
we've provided, the function returns while processing the second element in the list: it
does not have to traverse the whole list.
9. SCOPE AND LIFETIME
Not all variables are accessible from all parts of our program, and not all variables exist
for the same amount of time. Where a variable is accessible and how long it exists
depend on how it is defined. We call the part of a program where a variable is
accessible its scope, and the duration for which the variable exists its lifetime.
There are two types of scope
Global Variables
Local VariablesControl Flow, Functions - 127
“Today Tam
Going to expel
9.1 Global Variables
A variable which is defined in the main body of a file is called a global variable.
It will be visible throughout the file, and also inside any file which imports that file.
Global variables can have unintended consequences because of their wide-ranging
effects — that is why we should almost never use them. Only objects which are intended
to be used globally, like functions and classes, should be putin the global namespace.
9.2 Local Variables
A variable which is defined inside a function is local to that function. It is
accessible from the point at which it is defined until the end of the function, and exists
for as long as the function is executing. The parameter names in the function definition
behave like local variables, but they contain the values that we pass into the function
when we call it. When we use the assignment operator (=) inside a function, its default
behaviour is to create a new local variable — unless a variable with the same name is
already defined in the local scope.
#Program that illustrate Global and Local. \
# This is a global variable
a=0
y if'a == 0:
# This is still a global variable
b-1
onyvanbhune128 - Problem Solving and Python Programming
1o- def my_function(c):
41 # this is a local variable
12
B
4
45
16 # low we call the function, passing the value 7 as the first and
only parameter
47 my_function(7)
18
19 # a and b still exist
20 print(a)
21 print(b)
22
23 # c and d don't exist anymore -- these statements will give us
name errors !
6324 print(c)
Fa25— print(d)
Output
10. Function Composition
Function composition is a way of combining functions such that the result of
each function is passed
the argument of the next function. For example, the
composition of two functions f and g is denoted f(g(x)). x is the argument of g, the result
of gis passed as the argument of f and the result of the composition is the result of f.
Let’s define compose2, a function that takes two functions as arguments (f and
g) and returns a function representing their composition.
11. Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name.Control Flow, Functions - 129
While normal functions are defined using the def keyword, in Python anonymous
functions are defined using the lambda key word.
Hence, anonymous functions are also called lambda functions
Lambda Functions
A lambda function has the following syntax
Syntax of Lambda Function
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever function
objects are required
Example of Lambda Function
Here is an example of lambda function that doubles the input value,
a
2 # Program to shaw the use of Lambda functions
3
4 louble = lambda x: x * 2
5
6 # Output: 16
7 print (double(5s))
Output
10
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument
and x* 2s the expression that gets evaluated and returned
This function has no name. It retums a function object which is assigned to the
identifier double. We can now call it as a normal function. The statement
double = lambda x: x *2
is nearly the same as130 - Problem Solving and Python Programming
def double(x)
return x *2
Use of Lambda Function
We use lambda functions when we require a nameless function for a short period of
time.
In Python, we generally use it as an argument to a higher-order function (a function
that takes in other functions as arguments). Lambda functions are used along with
built-in functions like filter(), map() ete.
Example use with filter()
The filter() function in Python takes ina function and a list as arguments.
‘The function is called with all the items in the list and a new list is returned which
contains items for which the function evaluats to True.
Here is an example use of filter() function to filter out only even numbers from a list.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2
0) , my_list))
# Output: (4, 6, 8, 12]
print (new list)
Example use with map()
The map() function in Python takes in a function and a list
The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each itemControl Flow, Functions - 131
is an example use of map() function to double all the items in a list.
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x ' 2 , my_list))
# Output: [2, 16, 8, 12, 16, 22, 6, 24]
print(new_list)
Output
12. PYTHON RECURSION
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other.
Any object in between them would be reflected recursively
Python Recursive Function
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2°3*4*5*6 = 720.
Program
# Factorial using Recursion
def fact (x
if x
return 1
els:
return (x * fact(x-1))
int(input(“enter the lumber
rint("The factorial of", num,
»)
is", fact(num))132 - Problem Solving and Python Programming
Output
In the above example, cal¢_factorial() is a recursive functions as it calls itself.
When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
Each function call multiples the number with the factorial of number 1 until the number
is equal to one. This recursive call can be explained in the following steps.
fact(4) # Ist call with 4
4*fact(3) — # 2nd call with3
4*3*fact(2) # 3rd call with 2
4*3*2* fact(1) # 4th call with 1
4*3*2*1 — #return from 4th call as number=1
4*3"2 # return from 3rd call
4*6 # return from 2nd call
24 # return from Ist call
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
Advantages of recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of recursion
1. Sometimes the logic behind recursion is hard to follow through
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and
time.
3. Recursive functions are hard to debug.Control Flow, Functions - 133
13. PYTHON STRINGS
A string is a sequence of characters
‘A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though
you may see characters on your screen, internally it is stored and manipulated as a
combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encoding used.
In Python, string is a sequence of Unicode character. Unicode was introduced to include
every character in all languages and bring uniformity in encoding.
How to create a string?
Strings can be created by enclosing characters inside a single quote or double quotes
Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.
Program
# all of the following are equivalent
my_string = ‘Hello’
print (my_string)
my_string = “Hella”
print (my_string)
my_string = ‘Hello''*
print (my_string)
# triple quotes string can extend multiple lines
my_string = “""Hello, welcome to
the world of Python"
print (my_string)134 - Problem Solving and Python Programming
Output
pe
13.1 STRING SLICING
We can access individual characters using indexing and a range of characters using
slicing. Index starts from 0. Trying to access a character out of index range will raise an
Index Error. The index must be an integer. We can't use float or other types, this will
result into Type Error.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access
a range of items in a string by using the slicing operator (colon).
Slicing can be best visualized by considering the index to be between the elements as
shown below.
If we want to access a range, we need the index that will slice the portion from the
string
0 1 2 3 4 5 6 Forward
Index
P R oO G R A M.
< 6 3 “4 3 2 A Reverse
Index
Program
str = "program"
print(’str = *, str)
#first character
print('str[@] = ", str[@])Control Flow, Functions - 135
#last character
print('str[-1] = ", str[-4])
#slicing 2nd to 5th character
print('str[1:5] = *, str[l:5])
#slicing 6th ta 2nd last character
print('ste[5:-2] = ', ste[5:-2])
Output
13.2 STRING IMMUTABLE
Strings are immutable. This means that elements of a string cannot be changed once it
has been assigned. We can simply reassign different strings to the same name.
String immutable-cannot be changed
str="program™
print (str)
str[2]=a
Output
We cannot delete or remove characters from a string. But deleting the string entirely is
possible using the keyword del.136 - Problem Solving and Python Programming
Program
#String delete
str="program™
print (str)
del str[1]
del str
Output
14. STRING FUNCTIONS
The various functions that can be applied on a string are listed below
Built-in String Functions in Python.
SLNo | Function Description Example
Name
Returns the String with first character | var = ‘PYTHON’
1. | capitalized) | capitalized and rest of the characters in | print (var-capitalize())
lower case. # Python
Cc rts all the ch te of the Str te var "TechBeamers’
2 | towero omer all he arate of he Sr oer
mowercase. # techbeamers
var = TechBeamers’
Converts all the characters of the String to
3. | upperO °° | rint (varupper()
uppercase. # TECHBEAMERS
Swaps the case of every character in the | var ="TechBeamers
4. | swapease0 | String means that lowercas
characters are | print (varswapcase())
changed to uppercase and vice-versa. # fECHbEAMERSControl Flow, Functions - 137
1. | titteo
count( strbeg,
Lendl)
Returns the ‘titlecased’ version of String | var = ‘welcome to Python
which means that all words start with | programming!
uppercase and rest of the characters in the | print (var.title())
words are in lowercase. # Welcome To Python Programming
Returns the number of times substring ‘st’ |?"
occurs in range [beg, end] if beg and end
index are given. If it is not given then
substring is searched in whole String.
Search is case-s a2
nsitive.
a1
var TechBeamers’
ste’
print (var.count(stx))
varl~Eagle Eyes’
print (varl.count(‘e’)
var2~'Eagle Eyes’
print (var2.count(‘E,05))
Python string comparison functions.
SLNo | Function Name_| Description
Example
1, |islowero
Returns ‘True’ if all the characters in the String
are in lowercase. If any one character is in
‘uppercase it will retum ‘False’,
var~'Python’
print (varislower())
# False
var='python’
print (varislower())
# True
2. |isupperd
Returns ‘True’ if all the characters in the String
are in uppercase. If any one character is in
lowercase it will return False’
var="Python™
print (var.isupper())
4 False
var-'PYTHON’
print (var isupper()
# Tne
3. |isdecimald
Returns ‘True’ if all the characters in String are
decimal. If anyone character in the String is of
other datatype, it will return False’,
Decimal characters are those from Unicode
cate N
Complete list of ‘Nd’ is present at following link:
mum-w2016"
print (numisdecimal())
# Tne138 - Problem Solving and Python Programming
Returns ‘True’ for any character for which | print (2 isdigit)
isdecimal) would retum ‘True and some | # True
characters in ‘No! category. | print (* isdigit)
If there are any characters other than these, it will | # True
retum ‘False’
Precisely, digits are the characters for which
Unicode property includes:
Numeric_Type-Digit or Numeric_Type=Decimal.
For example, superscripts are digits but fractions
not.
Complete list of ‘No’ is present at following link:
Returns ‘True’ if all the characters of the Unicode | num=u'2016
String lie in any one of the category ‘Nd’/’No’ and | print (numisnumeric))
(NI # Tue
If there are any characters other than these, it will | num-u'year2016
retum ‘False’. | print (num.isnumeric))
je ji Precisely, Numeric characters are those for which | # False
5. | isnumericO)
Unicode property includes Numeric_Type-Digit,
Numeric Type-Decimal or
lype-Numeric
Complete list of ‘NI’ is present at following link:
Numeric,
http://wwwfileformat.info/info/unicode/category
/NMlisthtm
int ‘python’ jsalphi
Returns ‘True’ if String contains at least one | Pt Python’ isalphag))
# Te
6. | isalphad character (non-empty String) and alll the
rint (pythons alpha
characters are alphabetic, False’ otherwise. Pomc pha)
Returns ‘True’ if String contains at least one | print (‘python isalnum())
character (non-empty String) and all the] # True
characters are either alphabetic or decimal digits, | print (‘python isalnum())
‘False’ otherwise. # Tue
7. | isalnum0
15. PYTHON STRING OPERATIONS
There are many operations that can be performed with string which makes it one of the
most used datatypes in Python.Control Flow, Functions - 139
15.1 Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also
concatenates them.
The * operator can be used to repeat the string for a given number of times
Program
#String Concatination and String repetition
strl "Hella"
str2 ="World!
# using +
print(‘strl + str2 = ", strl + str2)
# using *
print(‘strl * 3 =", stri ? 3)
Output
15.2 Iterating Through String
Using for loop we can iterate through a string. Here is an example to count the number
of I ina string.
Program
1 #String Iteration
2 count = 6
3> for letter in ‘Hello World’:
4, if(letter "L'):
5 count += 1
6 print(count, Letters found")140 - Problem Solving and Python Programming
Output
15.3 String Membership Test
We can test if a sub string exists within a string or not, using the keyword in.
a" in ‘progran”
‘at’ not in ‘battle’
15.4 Built-in functions to Work with Pytho
Various built-in functions that work with sequence, works with string as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function
returns an enumerate object. It contains the index and value of all the items in the string
as pairs. This can be useful for iteration
Similarly, len() returns the length (number of characters) of the string.
Program
#String Enumeration
a str = ‘cold’
# enumerate()
list_enumerate = list(enumerate(str))
print(‘list(enumerate(str) = ', list_enumerate)
#character count
print("len(str) = ', len(str))
weoUuanewneControl Flow, Functions - 141
Here is a list of all the escape sequence supported by Python.
Escape Sequence in Python
Escape Description
Sequence
\newline Backslash and newline ignored
\ Backslash
Vv Single quote
V Double quote
\a ‘ASCII Bell
\b ‘ASCII Backspace
7 ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ‘ASCII Horizontal Tab
Ww ASCII Vertical Tab
\ooo Character with octal value 000
\xHH Character with hexadecimal value
HH
15.5.2 The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contains curly braces (} as placcholders
or replacement fields which gets replaced.142 - Problem Solving and Python Programming
We can use positional arguments or keyword arguments to specify the order.
Program
1 # default(implicit) order
2 default_order = "{}, {} and {}".format( ‘Haha’ ,*Prez’,"Sathish’)
3 print("\n--- Default Order ---")
4 print (default_order)
5
6
# order using posit
positional_order
onal argument
1}, {0} and {2}".format(*
iaha", "Prez',"Sathish")
8 — print("\n--- Positional Order ---")
9 print (positional_order)
10
11 # order using keyword argument
12 keyword_order = "{s}, {p} and {m}".format(m="Hiaha* ,p="Prez",s="Sathish")
Keyword order
rd_order)
oo)
14 print(key
The format() method can have optional format specifications. They are
separated from field name using colon. For example, we can leftjustify <, right-justify >
or center * a string in the given space. We can also format integers as binary,
hexadecimal etc. and floats can be rounded or displayed in the exponent format. There
are a ton of formatting you can use.
16. LIST AS ARRAYS
One of the most fundamental data structures in any language is the array. Python
doesn't have a native array data structure, but it has the list which is much more general
and can be used as a multidimensional array quite easilyControl Flow, Functions - 143
Basic array operations
So far so good, and it looks as if using a list is as easy as using an array. The first
thing that we tend to need to do is to scan through an array and examine values. For
example, to find the maximum value (forgetting for a moment that there is a built-in
max function) you could use:
m=0
for ein myList:
if mee:
m=e
This uses the for..in construct to scan through each item in the list. This is a very
useful way to access the elements of an array but it isn't the one that most programmers
will be familiar with. In most cases arrays are accessed by index and you can do this in
Python:
m=0
for iin range(len(myList)):
if memyListli}:
me=myListli]
Notice that we are now using range to generate the sequence 0,1, and so on up to the
length of myList.
You have to admit that there is a lot to be said for the simplicity of the non-index
version of the for loop but in many cases the index of the entry is needed. There is the
option of using the index method to discover the index of an element but this has its
problems
For example if you wanted to return not the maximum element but its index position in
the list you could use:
m=0
mi=0
for iin range(len(myList)):
if memyListli}:144 - Problem Solving and Python Programming
m=myListli]
misi
or you could use the non-indexed loop and the index method:
m=0
for ein myList:
if mee:
m=e
mi=myList.index(m)
print mi
The only problem is that index(m) returns the index of m in the list or an error if
m isn't in the list. There is also the slight problem that behind the scenes it is clear that
index is performing another scan of the entire list.
ILLUSTRATIVE PROBLEMS:
Problem 1: Square root of a given number
Program Coding
Typel: Using Math Function
square.py
import math
num-float(input("Enter a number")
sroot-math.sqrt(num)
print("The square root of %0.3f is %0.3f"%(num, sroot))
Output
Enter a number 25
The square root of 25.000is 5.000Control Flow, Functions - 145
Screen shots
1 import math
2 num=float(input("Enter a number
3. sroot=math.sqrt(num)
4 print(“The square root of %0.3f is %@.3f"%(num,sroat))
Output
Problem 2: GCD of two numbers
336 360
/ 336
laxraaxrs
/
360)
ay )
G.C.D=2X2X2X3
=24
Program Coding
Type 1: Using Fractions function
gcd.py
import fractions
a=int(input("Enter the first number:"))
b-int(input("Enter the second number:"))
print("The GCD of the two numbers is" fractions.ged(a,b))146 - Problem Solving and Python Programming
Output
Enter the first number: 15
5
Enter the second number:
The GCD of the two numbers is 5
Screenshots
1 import fractions
2 asint(input("Enter the first number:"))
3 b-intCinput("Enter the second number:"))
4 print("The GCD of the two numbers is", fractions .gcd(a,b))
Output
SiS het med Lt
Enter the
‘Type 2: Without using Fractions function
ged.py
acint(input("Enter a number:"))
b=int(input("Enter another number")
rem=a%b
while rem!=0
ab
berem
rem=a%b
print ("ged of given numbers is : %d" %(b))
Output
Enter a number: 15Control Flow, Functions - 147
Enter another number
ged of given numbers is
Screenshots
1 a-int(input("Enter a number:"))
2 beint(input("Enter another number"))
3 rem-a%sb
47 while rem!-0
5 a=b
6 bsrem
7 rem=a‘sb
8 print ("ged of given numbers is : %d" %(b))
Type 3: Using Recursion
ged.py
def ged(ab):
returna
else:
return ged(b,a%b)
a-int(input("Enter first number:"))
b-int(input("Enter second number:"))
GCD=ged(a/b)
print("The ged of two numbers is :",GCD)148 - Problem Solving and Python Programming
Output
Enter first number: 336
Enter second number: 360
The ged of two numbers is : 24
Screenshots
1- def gced(a,b):
Qe if(b==0):
return a
return gcd(b,a%b)
nt(input("Enter first number:
=int(input("Enter second number:
8 GCD=gced(a,b)
9 print("The gcd of two numbers is : ",GCD)
»)
»)
Problem 3: Exponentiation (OR )Power of a number
Program Coding
Type 1: Using Math functions
exponentiation. py
import math
bas
--int(input("Enter the Base Value:"))
power-int(input("Enter the Power Value:"))
num=math. pow (base, power)
print("%i power %i is %i"% (base, power,num))Control Flow, Functions - 149
Output
Enter the Base Value: 2
Enter the Power Value: 3
2 power 3is 8
Screenshots
1 import math
2 base=int(input("Enter the Base Value:
3 power=int(input("Enter the Power Value
4 num=math.pow (base, power)
5 print("%i power Si is %i"%(base,power,num))
Hs eee
Type 2: Without Using Math functions
exponentiation.py
base=int(input("Enter the Base Value:"))
power-int(input("Enter the Power Value:"))
num-base power
print("%i power %i is %i"¥%(base, power, num))
Output
Enter the Base Value: 2
Enter the Power Value: 3
2 power 3is 8
Screenshots
1 base-int(input("Enter the Base Value:"))
2 power-int(input("Enter the Power Value:"))
3 num=base! 'power
4 print¢” power %i is %i"%(base,power ,num))150 - Problem Solving and Python Programming
Output
arta rant
cs tl ces
Type 3: Using Recursion
exponentiation.py
def num (base power):
if(power=1):
return(base)
if(power!=1):
return(base*num (base, power-1))
base=int(input(’ Enter Base Value: "))
power-int(input("Enter Power Value: "))
print("Result:" num (base, power))
Output
Enter Base Value: 2
Enter Power Value: 3
Result: 8
Screenshots
1+ def num(base, power):
a- if(power==1):
3 retur
4> if(power!=1):
5 peturn(base'num(base, pawer-1))
6
7 base=int(input("Enter Base Value
8 power=int(input("Enter Power Value:
9 print¢"Result:",num(base, power) )Control Flow, Functions - 151
Program 4: Sum of an Array
Program Coding
array.c
array=(]
size=int(input("Enter the array siz
for nin range(size)
numbers=int(input("Enter the numbers")
array.append(numbers)
print("Sum of an Array is ",sum(array))
Output
Enter the array size: 3
Enter the numbers 1
Enter the numbers 2
Enter the numbers 3
Sum ofan Array is 6
Screenshots
1s array=[]
2 sizesint(input("Enter the array size:"))
3+ for n in range(size):
4 numbers=int (input ("Enter the numbers”))
5 array .append( numbers)
6 print("Sum of an Array is
"sum(a152 - Problem Solving and Python Programming
Problem 5: Linear Search
Program Coding
linearpy
items -[]
size-int(input("Enter the size of items")
forn in range(size):
numbers=int(input("Enter the number")
items.append (numbers)
print(‘list of items is
items)
x= int(input("enter item to search:"))
i=search=0
while i for n in range(size):
4 numbers=int(input("Enter the number™))
5 items .append(numbers)
6
7 print("list of items is", items)
8 x = int(input("enter item to search:"))
9 i = search = 6
10> while i < Len(items):
u- if items[i] == x:
12 search = 1
13 break
4 i ivi
15+ if search a:
16 print("item found at position:", i + 1)
17+ else:
18 print(“item not found”)154 - Problem Solving and Python Programming
Problem 6: Binary Search
Program Coding
binary.py
def binary_sort(sorted. length, key):
start =0
end = length-1
while start <= end:
mid = int((start + end)/2)
print("\nEntered number %d is present at position: %d" % (key, mid))
return -1
elif key sorted_list[mid]:
start = mid +1Control Flow, Functions - 155
print("\ nElement not found!")
return -I
Ist=[]
size = int(input("Enter size of list: \t"))
forn in range(size):
numbers = int(input("Enter any number: \t"))
Istappend(numbers)
Ist.sort()
print(\n\nThe list will be sorted, the sorted list is, Ist)
x =int(input("\nEnter the number to search: "))
binary_sort(Ist, size, x)
Output
Enter size of list: 5
Enter any number:28
Enter any number:
Enter any number: 5
Enter any number: 6
Enter any number: 74
The list will be sorted, the sorted list is: [1, 5, 6, 28, 74]
Enter the number to search: 28
Entered number 28 is present at position: 3
Screenshots
1 def binary_sort(sorted List, length, key)
2 start = 0
3 end = Length-1
4+ while start <= end:
5 mid = int((start + end) /2)
6 Af key == sorted list{mid]:156 - Problem Solving and Python Programming
7 print ("\n€ntered number %d is present at position: %d" % (key, mid))
8 return -1
9° elif key < sorted_list{mid]
10 end = mid - 1
ue elif key > sorted list{mid]:
12 start = mid +1
B print("\n€lement not found!")
a return -1
15
16 Ast = (J
17 size = int(input(“Enter size of List: \t"))
18> for n in range(size)
19 numbers = int (input("Enter any number: \t"))
20 Lst .append(numbers)
21
22 Ast.sort()
23 print(*\n\nThe list will be sorted, the sorted list is:', 1st)
28
25 x = int(input("\nEnter the number to search: "))
26
27. binary_sort(Ist, size, )
Output
crt
cca
ccc
ccd
coat
cetLists, Tuples, Dictionaries - 157
/ LISTS, TUPLES,
DICTIONARIES
ed
operations, list slices, list methods, list loop, mutability, aliasing, cloning lists]
Lists:
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operationg
land methods; advanced list processing - list comprehension; Illustrative programs]
selection sort, insertion sort, mergesort, histogram.
1. PYTHON LIST
Python offers a range of compound datatypes often referred to as sequences.
List is one of the most frequently used and very versatile datatype used in Python.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
Itcan have any number of items and they may be of different types (integer, float, string
etc).
# empty list
my_list = (]
# list of integers
(1,2, 31
my_lis
# list with mixed datatypes
my_list= (1, "Hello", 3.4]
also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a'll158 - Problem Solving and Python Programming
How to access elements from a list?
‘There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. Index starts from 0.
So, a list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an Index Error. The index
must be an integer. We can't use float or other types, this will result into Type Error.
Nested list are accessed using nested indexing.
Program
my list = ["p',
# Output: p
print(my_list[@])
print(my_list[2])
# Output: e
1
2
3
4
5 # Output: a
6
7
8
9 print(my_list[4])
11 # Error! Only integer can be used for indexing
12. # my_list[4.9]
14 # Nested List
15 n_list = ["Happy", [2,0,1,5]]
17) # Nested indexing
19 # Output: a
20° print(n_list[o][1])
220 «# Output: 5
23 print(n_list[1][3])Output
Lists, Tuples, Dictionaries - 159
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the
last item, -2 to the second last item and so on,
Program
NOM Bw ek
Output
e
Pp
List Slices
my_list = [‘p',
o',"b','e']
# Output: e
print (my_list[-1])
# Output: p
print(my_list[-5])
We can access a range of items in a list by using the slicing operator (colon).
dam buNe
%
my list = [‘p'styt.t'."h’,'o',"n]
# elements 3rd to Sth
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end160 - Problem Solving and Python Programming
9 print(my_list[5:])
10
11 # elements beginning to end
12 print(my_list[:])
Output
Slicing can be best visualized by considering the index to be between the elements as
shown below. So if we want to access a range, we need two index that will slice that
portion from the list.
Forward
Indexing
Negative
Indexing
Add or insert element to a list
Mutability
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
Program
1 # mistake values
2 odd = [2, 4, 6, 8]
3 print("Before Mutable", odd)
4
5 # change the Ist item
6 odd[e@] = 1Lists, Tuples, Dictionaries - 161
7
8 # Output: [1, 4, 6, 8]
a print("After changing First Item", odd)
11 # change 2nd to 4th items
12 odd[1:4] = [3, 5, 7]
14 «# Output: [1, 3, 5, 7
15 print("After Mutable", odd)
Append () and extend() Methods
We can add one item to a list using append() method or add several items using extend()
method.
odd = [1, 3, 5]
odd. append(7)
# Output: [1, 3, 5, 7]
print("By suing append", odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print("By using extend", add)
Be A
ERB oov an eens
Output162 - Problem Solving and Python Programming
List concatenation and List repetition
We can also use + operator to combine two lists. This is also called list concatenation,
The * operator repeats a list for the given number of times. This is also called as list
repetition.
Program
1 odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print("List Concatination" ,odd + [9, 7, 5])
#Output: ["re", "re", "re"]
print("List Repetition",["re"]
san ebwn
3)
Insert() Method
Furthermore, we can insert one item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.
Program
1 odd = [1, 9]
2 odd.insert(1,3)
3
4 # Output: [1 9]
5 print("Insert™, odd)
6
7 odd[2:2] = [5, 7]
8
9 # Output: [1, 3, 5, 7, 9]
10 print("Insert Using Index", odd)Lists, Tuples, Dictionaries - 163
Output
Delete or remove elements from a list?
We can delete one or more items from a list using the keyword del. It can even delete
the list entirely.
Program
1 my list = ['p','y','t',"h',‘o','n']
2
z! # delete one item
4 del my_list[2]
5
# Output: ["p’, "r', "b’,
print (my_list)
# delete multiple items
10 del my_list[1:5]
12 # Output: [‘p’, ‘m']
13° print(my_list)
15 # delete entire list
16 del my_list
17
18 # Error: List nat defined
19 print(my_list)
Output164 - Problem Solving and Python Programming
We can use remove() method to remove the given item or pop() method to remove an
item at the given index
The pop() method removes and retums the last item if index is not provided. This helps
us implement lists as stacks (first in, last out data structure)
We can also use the clear() method to empty a list.
Program
1 my_list = ["p',’y
2 my_list .remove("p’)
3 print(my_list)
4 print (my_list .pop(1))
5 print(my_list)
6 print(my_list .pop())
7 print(my_list)
8 my_list .clear()
a
18 print(my List)
Output
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
>>> my_list = ["p","r',"o",'b","L","e"
>>> my_List[2:3] = []
>>> my_list
[py ir’, “bY,
>>> my_List[2:5]
>>> my_list
['p', or’, ‘w']
im’)Lists, Tuples, Dictionaries - 165
2. PYTHON LIST METHODS
Methods that are available with list object in Python programming are tabulated below.
They are accessed as listmethod(). Some of the methods have already been used above.
n Method Name Description
1. | append ‘Add an element to the end of the list
2. | extend Add all elements of a list to the another list
3. | insert) Insert an item at the defined index
4. | remove() Removes an item from the list
5. | pop0 Removes and returns an clement at the given index
6. | clear() Removes all items from the list
7. | index Retums the index of the first matched item
8. | count Retums the count of number of items passed as an argument
9. | sorta. Sort items in a list in ascending order
10.] reversed Reverse the order of items in the list
11.| copy Retums a shallow copy of the list
Some examples of Python list methods:
Program
my_list = [3, 8, 1, 6, 6, 8, 4]
print("List indexof $ is", my_list .index(3))
print("List count of $8 is", my_list.count(8))
my_list .sort()
print(my_list)
my_list .reverse()
print(my_list)
Wan kwNe166 - Problem Solving and Python Programming
Output
3. LIST COMPREHENSION: ELEGANT WAY TO CREATE NEW LIST
List comprehension is an elegant and concise way to create new list from an existing list
in Python.
List comprehension consists of an expression followed by for statement inside square
brackets.
Syntax:
[exp for val in collection]
[exp for val in collection if]
[exp for val in collection ifstest1> and ]
[exp for val1 in collection] and val2 in collection2]
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 '' x for x in range(16)]
64, 128, 256, 512]
1
2
3. # Output: [1, 2, 4, 8, 16,
4 print (pow2)
Output
This code is equivalent to
pod = []
for x in range(1):
pow2.append(2 ** x)Lists, Tuples, Dictionaries - 167
Example 1: List of Squares
1 squares=[i''2 for i in range(1,10)]
2 print (squares)
Output
This code is equivalent to
1 squares=[]
2> for i in range(1,1@):
3 squares .append(i!'2)
4
5 print (squares)
A list comprehension can optionally contain more for or if statements. An optional if
statement can filter out items for the new list. Here are some examples.
1 pow2 = [2 '* x for x in range(1e) if x > 5]
2 print (pow2)
3
Output
4. OTHER LIST OPERATIONS IN PYTHON
4.1 List Membership Test
We can test if an item exists in a list or not, using the keyword in.
my_list = [‘p’,'r',‘o',‘b',"L','e',‘m']
print(’p* in my_list)
print(*a’ in my_list)
print('c* not in my_list)
TB whe168 - Problem Solving and Python Programming
Output
4.2 Iterating Through a List (List Loop)
Using a for loop we can iterate though each item in a list.
Program
1- for subject in ["Physics','PSPP’, 'Chemistry']:
2 print("I like",subject)
Output
4.3 Built-in Functions with List
Built-in functions like all(), any(), enumerate(), len(), max(), min(), list(), sorted() etc. are
commonly used with list to perform different tasks.
Built-in Functions with List
rr Deseript
Na | Function jescription
1.] alld Return True if all elements of the list are true (or if the list is empty).
2.| anyo Return True if any element of the list is true. If the list is empty, return False
Return an enumerate object. It contains the index and value of all the items of
3. enumerated
list as a tuple.
4. | lend Return the length (the number of items) in the list.
3. | listo) Convert an iterable (tuple, string, set, dictionary) to a list.
6. | maxi) Return the largest item in the list.Lists, Tuples, Dictionaries - 169
7 | mind Retum the smallest item in the list
8 | sorted) Retum anew sorted list (does not sort the list itself)
9| sum) Retum the sum of all cements in the list.
5. OBJECTS AND VALUES
If we execute these assignment statements,
a="banana”
b= "banana"
we know that a and b will refer to a string with the letters "banana". But we don’t know
yet whether they point to the same string.
There are two possible states:
a—+ “banana” | | a~
“banana”
b—> “banana” | | b-—”
In one case, a and b refer to two different things that have the same value. In the
second case, they refer to the same thing. These things have names — they are called
objects. An object is something a variable can refer to.
We can test whether two names have the same value using
>>>as=b
True
We can test whether two names refer to the same object using the és operator:
>e>aisb
True
This tells us that both a and b refer to the same object, and that it is the second of the
two state diagrams that describes the relationship.170 - Problem Solving and Python Programming
Since strings are immutable, Python optimizes resources by making two names that refer
to the same string value refer to the same object.
This
not the case with lis!
>>ra=[1,2,3]
>>>b=[1,2, 3]
>>>a==b
True
>>>a is b
False
The state diagram here looks like this:
a—>+> [12,3]
b—>+11,2,3]
a and b have the same value but do not refer to the same object.
6. ALIASING
Since variables refer to objects, if we assign one variable to another, both variables refer
to the same object:
>>>a=[1,2, 3]
>>> b=a
>>>a is b
True
In this case, the state diagram looks like this:
Because the same list has two different names, a and b, we say that it is aliased
Changes made with one alias affect the otheLists, Tuples, Dictionaries - 1
>>> b[0]=5
>>> print a
15,23]
Although this behavior can be useful, it is sometimes unexpected or undesirable. In
general, it is safer to avoid aliasing when you are working with mutable objects. Of
course, for immutable objects, there's no problem. That’s why Python is free to alias
strings when it sees an opportunity to economize.
7. CLONING LISTS
If we want to modify a list and also keep a copy of the original, we need to be able to
make a copy of the list itself, not just the reference. This process is sometimes called
cloning, to avoid the ambiguity of the word copy.
‘The easiest way to clone a list is to use the slice operator:
>>> a=[1,2, 3]
>>> b =al:]
>>> print b
11,2,3]
‘Taking any slice of a creates a new list. In this case the slice happens to consist of the
whole list.
Now we are free to make changes to b without worrying about a:
>>> b0]
>>> print a
11,2, 3]
LIST PARAMETERS
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. Since lists are mutable changes made to the parameter change the argument as
well. For example, the function below takes a list as an argument and multiplies each
element in the list by 2:172 - Problem Solving and Python Programming
def double_stuff(a_list):
for index, value in enumerate(a_list):
a_list{index] = 2* value
If we put double_stuff in a file named ch09. py, we can test it out like this:
>>> from ch09 import double_stuff
>>> things = [2, 5, ‘Spam’, 9.5]
>>> double_stuff(things)
>>> things
[4, 10, ‘SpamSpam’, 19.0]
>>>
The parameter a_list and the variable things are aliases for the same object. The state
diagram looks like this:
—main_ |a_list | _
> [2, 5, ‘Spam’, 9.5]
double_stuff | things | ~
Since the list object is shared by two frames, we drew it between them.
Ifa function modifies a list parameter, the caller sees the change.
9, TUPLES AND MUTABILITY
So far, you have seen two compound types: strings, which are made up of
characters; and lists, which are made up of elements of any type. One of the differences
we noted is that the elements of a list can be modified, but the characters in a string
cannot. In other words, strings are immutable and lists are mutable.
A tuple, like a list, is a sequence of items of any type. Unlike lists, however, tuples are
immutable. Syntactically, a tuple is a comma-separated sequence of values:
>>> tup = 2,4, 6, 8, 10
Although it is not necessary, it is conventional to enclose tuples in parentheses:
>>> tup = (2, 4, 6, 8, 10)
To create a tuple with a single element, we have to include the final comma:Lists, Tuples, Dictionaries - 173
>>> tup = 6,)
>>> type(tup)
Without the comma, Python treats (5) as an integer in parenthese:
>>> tup = (5)
>>> type(tup)
Syntax issues aside, tuples support the same sequence operations as strings and lists.
The index operator selects an element from a tuple.
>>> tup =
a,b, 'c,'d'e’
>>> tuplo]
And the slice operator selects a range of elements.
>>> tup[1:3]
(b;,'c)
But if we try to use item assignment to modify one of the elements of the tuple, we get
an error:
>>> tup|0] ='X"
TypeError: ‘tuple’ object does not support item assignment
Of course, even if we can’t modify the elements of a tuple, we can replace it with a
different tuple:
>>> tup =
X') + tup[:}
>>> tup
(x, be,
e)
Alternatively, we could first convert it to a list, modify it, and convert it back into a
tuple:174 - Problem Solving and Python Programming
>p> tup = (X;,'bi,'c,,'d’,'e’)
>>> tup = list(tup)
>>> tup
[X;, bi, 'c, 'd','e']
>>> tup[0] = 'a!
>>> tup = tuple(tup)
>>> tup
(a', bi, ‘c,d’, 'e’)
10, TUPLE ASSIGNMENT
Once in a while, it is useful to swap the values of two variables. With
conventional assignment statements, we have to use a temporary variable. For example,
to swap a and b:
temp=a
a=b
b= temp
If we have to do this often, this approach becomes cumbersome. Python provides a
form of tuple assignment that solves this problem neatly:
a,b=b,a
The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments. This feature makes tuple assignment quite versatile
Naturally, the number of variables on the left and the number of values on the right
have to be the same:
>>>a,b,c,d=1,2,3
ValueError: need more than 3 values to unpack
11, TUPLES AS RETURN VALUES
Functions can return tuples as return values. For example, we could write a
function that swaps two parameters:Lists, Tuples, Dictionaries - 175
def swap(x, y)
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there is a
danger in trying to encapsulate swap, which is the following tempting mistake:
def swap(x,y): # incorrect version
x Y= yx
If we call this function like this:
swap(a, b)
then a and x are aliases for the same value. Changing x inside swap makes x refer to a
different value, but it has no effect on a in_main__. Similarly, changing y has no effect
onb.
This function runs without producing an error message, but it doesn’t do what we
intended. This is an example of a semantic error.
12. PYTHON DICTIONARY
Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
12.1 create a dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma,
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.176 - Problem Solving and Python Programming
+ empty dictionary
my_dict= {)
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: 'ball’}
# dictionary with mixed keys
my_dict= {‘name’: John’, 1: [2, 4, 3]}
# using dict()
my_dict= dict({1!apple’, ball’)
# from sequence having each item as a pair
my_dict= dict({(1,'apple’), (2,'ball’)})
‘As youcan see above, we can also create a dictionary using the built-in function dict)
12.2 access elements from a dictionary
While indexing is used with other container types to access values, dictionary
uses keys. Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if
the key is not found.
[ my_dict = {*name*:"Jack", ‘age’: 26}
print (my_dict[‘name"])
print(my_dict.get('age'))
swe
OutputLists, Tuples, Di
12.3 change or add elements in a dictionary
Dictionary are mutable. We can add new items or change the value of existing items
using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to
the dictionary
Program
1 my_dict = {*name':"Jack', ‘age’: 26}
2
3 # update value
4 my_dict[*age’] = 27
5 print (my_dict)
6
7 # add item
& my_dict[‘address*] = "Downtown"
9 print(my_dict)
Output
12.4 delete or remove elements from a dictionary
We can remove a particular item in a dictionary by using the method pop(). This
method removes as item with the provided key and returns the value
The method, popitem( can be used to remove and return an arbitrary item (key,
value) form the dictionary. All the items can be removed at once using, the clear()
method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.178 - Problem Solving and Python Programming
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# rem a particular item
print (squares .pop(4))
print (squares)
# remove an arbitrary item
print (squares .popitem())
print (squares)
12. # delete a particular item
13. del squares[1]
4 print (squares)
16 # rem all items
17 squares .clear()
is print (squares)
19
20 # delete the dictionary itself
21 del squares
Output
13. Python Dictionary Methods
Methods that are available with dictionary are tabulated below. Some of them
have already been used in the above examples.Lists, Tuples, Dictionaries - 179
Python Dictionary Methods
SLNo [Method Description
1. | clear Remove all items form the dictionary.
2. | copy0) Return a shallow copy of the dictionary.
Return a new dictionary with keys from seq and value equal to 0
3. | fromkeys(segl, 0
5 [fomkeysetl | gefautts to None)
4. | gettkeyLa)) Return the value of key. Ifkey doesnot exit, return d (defaults to None),
5. [itemso) Retum a new view of the dictionary’s items (key, value)
6.__|keys0) Return a new view of the dictionary’s keys,
7 bey Remove the item with key and return its value or d if key is not found. If
+ | peptey(al) d is not provided and key is not found, raises Key Error.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
| if key isin the dictionary, retum its value. If not, insert key with a value
OJ setdefaulteylad) | 6+ and retum d (defaults to None),
10, | update(omnery | UPAate the dictionary with the key/value pairs from other, overwriting
existing keys.
11. | values() Return a new view of the dietionary’s values
Here are a few example use of these methods.
Program
1 marks = {}.fromkeys([‘flath", English", "Science'], 9)
int (marks)
item in marks .items():
print (item)
list (sorted(marks .keys()))180 - Problem Solving and Python Programming
14, Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create new
dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed
by for statement inside curly braces
Here is an example to make a dictionary with each item being a pair of a
number and its square.
1 #List comprehension
squares = {x: x'x for x in range(6)}
nt (squares)
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make dictionary with only odd items.
Program
1 #List comprehension with more than one condition
odd_squares = {x: x'x for x in range(1l) if x%2
2
3
4 print(odd_squares)
OutputLists, Tuples, Dictionaries - 181
15. Other Dictionary Operations
15.1 Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in, Notice that
membership test is for keys only, not for values.
Program
Fly squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: S1}
2 print(1 in squares)
3 print(2 not in squares)
4 # membership tests for key
5
only not value
print(49 in squares)
15.2 Iterating Through a Dictionary
Using a for loop we can iterate though each key in a dictionary.
Program
L squares =
2~ for i in squares:
3 print(squares[i])
9, 5: 25, 7: 49, 9: S81}
Output
15.3 Built-in Functions with Dictionary
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks182 - Problem Solving and Python Programming
Built-in Functions with Dictionary
[SL.NO | Function Description
Return True if all keys of the dictionary are true (or if the
all) ,
dictionary is empty).
2 , Return True if any key of the dictionary is true. If the dictionary is
~ anv empty, return False.
end) Return the length (the number of items) in the dictionary.
4. [ompo Compares items of two dictionaries
8. | sorted() Return a new sorted list of keys in the dictionary.
Here are some examples that uses built-in functions to work with dictionary.
Program
1 squares
{i: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(len(squares))
print(sorted(squares))
ILLUSTRATIVE PROBLEMS
Problem 1: Selection Sort
Program Coding
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1)
positionOfMax-0for location in range(1,fillslot +1):
if alist{location}>alist[positionOfMax]
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist{positionOfMax]
alist[positionOfMax] = temp
ist=[]
size=int(input("Enter the Size of lis
for nin range(size):
numbers=int(input("Enter the Number:”))
alist.append(numbers)
print("Befor Sorting:",alist)
selectionSort(alist)
print("After Sorting:")
print(alist)
Output
Enter the Size of list: 5
Enter the Number:
Enter the Number:
Enter the Number:
Enter the Number:
Enter the Number:
12
15
7
8
5
Befor Sorting: [12, 15, 7, 8, 5]
After Sorting:
(5, 7, 8, 12, 15]
Lists, Tuples, Dictionaries - 183184 - Problem Solving and Python Programming
Screenshots
1+ def selectionSort(alist):
2+ for fillslot in range(len(alist)-1,0,-1):
3 positionOfMax-0
4~ for location in range(1,fillslot+1):
5+ if alist [location]> alist [posit ion0fMax]:
6 positionOfliax = location
7
8 temp = alist[fillslot]
9 alist [fillslot] = alist [position0fliax]
10 alist [positiondfmax] - temp
di
12 -[]
13 nt(input("Enter the Size of list:"))
14~ for n in range(size):
15 numbers-=int(input("Enter the Number :"))
16 alist .append(numbers)
print("Befor Sorting:",alist)
418 selectionSort(alist)
19 print(“After Sorting:")
20° print(alist)Lists, Tuples, Dictionaries - 185
Problem 2: Insertion Sort
Program Coding
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist{[position}-alist[position-1]
position = position-1
alist{position]-currentvalue
alist=[]
size-int(input("Enter the Size of list:"))
for nin range(size):
numbers=int(input("Enter the Number:"))
append(numbers)
print("Befor Sorting:" alist)
insertionSort(alist)
print("After Sorting:")
print(alist)
Output
Enter the Size of list: 5
Enter the Number: 25
Enter the Number: 14186 - Problem Solving and Python Programming
Enter the Number: 7
Enter the Number: 1
Enter the Number: 2
Befor Sorting: [25, 14, 7,1, 2]
After Sorting:
[1, 2, 7, 14, 25)
Screenshots
1~ def insertionSort(alist):
ei for index in range(1,len(alist)):
3
4 curpentvalue = alist [index]
5 position = index
6
7 while position»® and alist [position-1]> current value:
8 alist [position]-alist [positian-1]
9 position = position-1
10
ul alist [position ]-current value
12
13 alist -[]
14 size-int(input("Enter the Size of list
15~ for n in range(size):
16 numbers=int (input("Enter the Number
17 alist .append(numbers)
18 print("Befor Sorting:",alist)
19 insertionSort(alist)
20 print("After Sortin
21 print(alist)
Output
riers
ccetaotd
SortedProblem 3: Mergesort
Program Coding
def mergeSort(alist):
print("Splitting ",alist)
iflen(alist)>1:
mid = len(alist)//2
lefthalf = alist{:mid]
righthalf = alist{mid:]
mergeSort(lefthal )
mergeSort(righthalf)
ino
jo
k-0
while i 1:
mid = Len(alist)//2
lefthalf = alist[:mid]
righthalf = alist [mid:]
mergeSort (Lefthalf)
mergeSort (righthalf)
i-o
OOIKRVAEWN
Lists, Tuples, Dictionaries - 189
12> while i < len(lefthalf) and j < len(righthalf):190 - Problem Solving and Python Programming
Be if lefthalf[i] < righthalf[i]:
14 alist [k]-lefthal#[i]
15 isi+l
16> else:
17 alist [k]-righthal#[j]
18 jeje
19 k=k+1
20° while i < len(Lefthalf):
21 alist [k]-lefthalf[i]
22 isitl
23 +1
dae while j < len(righthalf)
25 alist [k]-righthalf[j]
26
27
28 nt("Merging ",alist)
30 alist =[]
31) osize=int(input("Enter the Size of list:"))
32~- for n in range(size):
33 numbers=int(input("Enter the Number :"))
34 alist .append( numbers)
35 print("Befor Sorting:",alist)
36 mergesort(alist)
37) print(“After Sorting:
38 print(alist)
OutputLists, Tuples, Dictionaries - 191
Problem 4: Histogram
Program Coding
def histogram( items ):
for n in items:
output ="
times =n
while( times > 0):
output +="
times = times - 1
print(output)192 - Problem Solving and Python Programming
alist=[]
size=int(input("Enter the Size of list:"))
forn in range(size):
numbers=int(input("Enter the Number:"))
alist.append(numbers)
print("The Histogram Values:",alist)
histogram (alist)
Output
Enter the Size of list: 5
Enter the Number:
Enter the Number:
Enter the Number:
Enter the Number:
Enter the Number:
4
5
7
1
2
The Histogram Values: [4, 5,7, 1, 2]
Screenshots
1+ def histogram( items ):
2- for
words. kyw
nin items:
output = "*
times n
while( times >» © ):
output += "*"
times = times
print (output)
1Lists, Tuples, Dictionaries - 193
16
dl alist =[]
12 size=int(input("Enter the Size of list:"))
13~ for n in range(siz
4 number's =int (input (
Enter the Number
15 alist .append( numbers)
16 print("The Histogram Values:",alist)
17 histogram(alist)
Output194Files, Modules, Packages - 195
FILES, MODULES, PACKAGES
oe
[Files and exception: text files, reading and writing files, format operator; command line
larguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
lprograms: word count, copy file.
1. PYTHON FILE
File is a named location on disk to store related information. It is used to
permanently store data ina 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.
Write File
>
=
Open File >I ASF Close File
Read File
Hence, in Python, a file operation takes place in the following order.
1. Opena file
2. Read or write (perform operation)
3. Close the file
How to open 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.196 - Problem Solving and Python Programming
>>> 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 File Modes
SL
Mode Description
No
1. Open a file for reading. (default)
Open a file for writing. Creates a new file if it does not exist or truncates
2 w P 8
the file if it exists
5 , Open a file for exclusive creation. Ifthe fle already exists, the operation
* fails,
fi Open for appending at the end of the file without truncating it. Creates a
. new file if it does not exist
5. Openin text mode. (default)
6. Openin binary mode.
7. + Open a file for updating (reading and writing)
f = open("test. txt")
# equivalent to 'r or ‘rt
f= open("test.txt’,'w') # write in text mode
f= open("img.bmp
Unlike other languages, the character
't+b’) # read and write in binary mode
does not imply the number 97 until it is
encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is ‘cp1252°
but ‘utf-8' in Linux.Files, Modules, Packages - 197
So, we must not also rely on the default encoding or else our code will behave
differently in different platforms.
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')
How to close a file Using Python?
When we are done with operations to the file, we need to close the file properly.
Closing a file will free up the resources that were tied with the file and is done
using Python close() method.
Python has a garbage collector to dean up unreferenced objects but, we must
not rely on it to close the file.
£ = open("test.txt",en coding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing
some operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block
try:
f = open("test.txt",encoding = ‘utf-8')
+ perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception
is raised, causing 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.198 - Problem Solving and Python Programming
with open("test.txt",encoding = 'utf-8)) as f:
# perform file operation
How to write to File Using Python?
In order to write into a file in Python, we need to open it in write 'w', append ‘a’
or exclusive creation ‘x’ mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it
already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write)
method. This method returns the number of characters written to the file.
with open("test.txt", w'encoding = 'utf-8!) as f
f.write("my first file\n")
fwrite("This file\n\n")
Ewrite("contains three lines\n")
This program will create a new file named ‘test.txt’ if it does not exist. If it does
exist, itis overwritten.
We must include the newline characters ourselves to distinguish different lines.
How to read files in Python?
To read a file in Python, we must open the file in reading mode.
There are various methods available for this purpose. We can use the read(size)
method to read in size number of data. If size parameter is not specified, it reads and
returns up to the end of the file.
Example,
Create a file with name “test.txt”. The content of the file is “This is my first file’. The
following program illustrates the read operation that can be done on a file in various
methods.
>>> f= open("test.txt",'r',encoding = ‘utf-8')
>>> fread(4) # read the first 4 data
‘This’Files, Modules, Packages - 199
>>> firead(4) # read the next 4 data
“is?
>>> fread() # read in the rest till end of file
‘my first file\nThis file\ncontains three lines\n’
>>> fread() # further reading returns empty sting
We can see that, the read() method returns newline as '\n’. Once the end of file
is reached, we get empty string on further reading.
We can change our current file cursor (position) using the seek() method
Similarly, the tell() method returns our current position (in number of bytes).
>>> f.tell # get the current file position
56
>>> fseek(0) # bring file cursor to initial position
0
>>> print(f.read() # read the entire file
This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. '
>>> for line in f:
print(line, end =")
This is my first file
This file
contains three lines
The lines in file itself has a newline character ‘\n'.
Moreover, the print() end parameter to avoid two newlines when printing.200 - Problem Solving and Python Programming
Alternately, we can use readline() method to read individual lines of a file. This
method reads a file till the newline, including the newline character.
>>> freadline()
"This is my first file\n’
>>> freadline()
‘This file\n’
>>> f.readline()
‘contains three lines\n’
>>> freadlineQ)
Lastly, the readlines() method returns a list of remaining lines of the entire file.
All these reading method return empty values when end of file (EOF) is reached.
>>> freadlines()
[This is my first file\n’, 'This file\n’, ‘contains three lines\n']
2. PYTHON FILE METHODS
There are various methods available with the file object. Some of them have been used
in above examples.
Here is the complete list of methods in text mode with a brief description.
Python File Methods
SLNo Method Description
1 close() Close an open file, It has no effect if the file is already closed.
Separate the underlying binary buffer from the TextlOBase and
2 detach(
ietach() retum it.
3. fileno() Return an integer number (file descriptor) of the file.
4. flush() Flush the write buffer of the file stream.
5. isatty() Return True if the file stream is interactive,Files, Modules, Packages - 201
Read atmost n characters form the file. Reads till end of file if itis
6 read(1i) :
negative or None.
7. teadable() | Returns Trueif the file stream can be read from.
Read and return one line from the file. Reads in at most 1 bytes if
8. | readline(n—1) °
specified.
Read and retum a list of lines from the file. Reads in at most n
9. | readlines(
bytes/characters if specified.
to, | See offet,fromS | Change the file position to oft bytes, in reference to fiom (start,
" EEK_SET) current, end).
11] — seekable() —_| Returns Trueif the file stream supports random access.
2 tell Returns the current file location.
ag, | meatelsize-No | Resize the file stream to size bytes, Ifsize isnot specified, resize to
° ne) current location.
14.| writable) __| Returns Truef the file stream can be written to.
. Write string s to the file and retum the number of characters
5, write(s)
written.
16.| writelines(lines) | Write alist of lines to the file.
3. COMMAND LINE ARGUMENTS
The sys module in Python is one of many available modules of library code.
sys.argv is the list of commandline arguments passed to the Python program
argy represents all the items that come along via the commandline input, it's basically a
an array holding the command line arguments of our program. Don't forget that the
counting starts at zero (0) not one (1).202 - Problem Solving and Python Programming
To use it, you will first have to import it (import sys) The first argument,
sys.argy[0], is always the name of the program as it was invoked, and sys.argy[1] is the
first argument you pass to the program. It's common that you slice the list to access the
actual command line argument:
Example,
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
Below is an example on how to read the argument from the command line
import sys
for x in sys.argy:
print "Argument: ", x
In this len(sys.argy) , checks how many arguments that have been entered.
Another example to read the argument from the command line
import sys
if len (sys.argy) != 2:
print "Usage: python ex.py "
sys.exit (1)
Where len(sys.argy) != 2 just checks whether you entered at least two elements
To Run the Program
>python ex.py
Argument: ex.py
>python ex.py hello
Argument: ex.py
Argument: helloFiles, Modules, Packages - 203
>python ex.py hello world
Argument: ex.py
Argument: hello
Argument: world
4, ERRORS AND EXCEPTIONS
An error isa term used to describe any issue that arises unexpectedly that cause
a computer to not function properly. Computers can encounter either software errors or
hardware errors. When writing a program, we usually encounter errors.
Software errors are the most common types of errors on a computer and are
typically fixed with software updates or patches that are designed to fix errors in the
code.
Hardware errors are any defects with hardware inside the computer or
connected to the computer. Although some hardware issues can be fixed with such
things as firmware updates, typically any hardware errors caused by defects are
resolved by replacing the defective hardware
Error caused by not following the proper structure (syntax) of the language is
called syntax error or parsing error.
>>> ifa<3
File "", line 1
ifa<3
SyntaxError: invalid syntax
We can notice here that a colon is missing in the if statement.
Errors can also occur at runtime and these are called exceptions. They occur, for
example, when a file we try to open does not exist (File Not Found Error), dividing a
number by zero (Zero Division Error), module we try to import is not found (Import
Error) etc.
Whenever these type of runtime error occur, Python creates an exception object.
If not handled properly, it prints a traceback to that error along with some details about
why that error occurred,204 - Problem Solving and Python Programming
>>> 1/0
Traceback (most recent call last):
File "", line 301, in runcode
File "", line 1, in
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent calll last):
File "", line 301, in runcode
File "
FileNotFoundError: [Ermo 2] No such file or directory: ‘imaginary. txt’
5. PYTHON BUILT-IN EXCEPTIONS
Illegal operations can raise exceptions. There are plenty of builtin exceptions in
Python that are raised when corresponding errors occur. We can view all the built-in
exceptions using the local() builtin functions as follows.
>>> locals()['_builtins
This will return us a dictionary of built-in exceptions, functions and attributes.
Some of the common built-in exceptions in Python programming along with the
error that cause then are tabulated below.
Python Built-in Exceptions
SLNo | Exception Cause of Error
1. | AssertionError Raised when assert statement fails.
2. | AttributeError Raised when attribute assignment or reference fails.
3. | EOFError Raised when the input() functions hits end-of-file
condition.
4, | FloatingPointError Raised when a floating point operation fails.
5. | GeneratorExit Raise when a generator's close() method is called.
6. | ImportError Raised when the imported module is not found.
7. | IndexError Raised when index of a sequence is out of range.
8. | KeyError Raised when a key is not found in a dictionary.Files, Modules, Packages - 205
9. | Keyboardinterrupt | Raised when the user hits interrupt key (Clic or
delete).
10. | MemoryError Raised when an operation runs out of memory.
11. | NameError Raised when a variable is not found in local or global
scope.
12, | NotImplementedError | Raised by abstract methods.
13, | OSError Raised when system operation causes system related
error.
14. | OverflowError Raised when result of an arithmetic operation is too
large to be represented,
ReferenceError Raised when a weak reference proxy is used to
access a garbage collected referent.
16. | RuntimeError Raised when an error does not fall under any other
category.
17. | Stoplteration Raised by next() function to indicate that there is no
further item to be returned by iterator.
18. | SyntaxError Raised by parser when syntax error is encountered.
19, | IndentationError Raised when there is incorrect indentation.
20. | TabExror Raised when indentation consists of inconsistent tabs
and spaces.
21. | SystemError Raised when interpreter detects intemal error.
22, | SystemExit Raised by sys.exit() function.
23. | TypeError Raised when a function or operation is applied to an
object of incorrect type.
24. | UnboundLocalError | Raised when a reference is made to a local variable in
a function or method, but no value has been bound
to that variable
25. | UnicodeError Raised when a Unicode-related encoding or
decoding error occurs.
26. | UnicodeEncodeError | Raised when a Unicode-related error occurs during
encoding,
27. | UnicodeDecodeError | Raised when a Unicode-related error occurs during
decoding,206 - Problem Solving and Python Programming
28. | UnicodeTranslateError | Raised when a Unicode-related error occurs during,
translating.
29. | ValueError Raised when a function gets argument of correct
type but improper value.
30. | ZeroDivisionError Raised when second operand of division or modulo
operation is zero.
We can also define our own exception in Python (if required). Visit this page to
learn more about user-defined exceptions.
We can handle these builtin and user-defined exceptions in Python using try,
except and finally statements.
6. Python Exception Handling - Try, Except and Finally
Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong,
When these exceptions occur, it causes the current process to stop and passes it
to the calling process until itis handled. If not handled, our program will crash.
For example, if function A calls function B which in tum calls function C and an
exception occurs in function C. If it is not handled in C, the exception passes to B and
then to A.
If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.
4.1 Catching Exceptions in Python
In Python, exceptions can be handled using a try statement.
A aiitical operation which can raise exception is placed inside the try clause and the
code that handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.Files, Modules, Packages - 207
Program
1 # import module s to get the type of exception
import sys
2
3
4 randomlist = ['a', @, 2]
5
6~ for entry in randomList:
7 tr
8 pint("The entry is", entry)
9 p= dfint(entry)
16 break
aly except:
2 print("Oops!",sys.exe_info()[@],"occured.")
B print("Wext entry.)
u print()
a5 print("“The reciprocal of",entry,"is",
Output
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
causes
module and ask the user to try again. We can see that the values ‘a’ and "
ValueError and '0' causes ZeroDivisionError.208 - Problem Solving and Python Programming
4.2 Catching Specific Exceptions in Python
In the above example, we did not mention any exception in the except clause.
This is not a good programming practice as it will catch all exceptions and
handle every case in the same way. We can specify which exceptions an except clause
will catch.
A try clause can have any number of except clause to handle them differently
but only one will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause.
Here is an example pseudo code.
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeE ror, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pa
4.3 Raising Exceptions
In Python programming, exceptions are raised when corresponding errors occur
at run time, but we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that
exception was raised.>>> raise KeyboardInterrupt
‘Traceback (most recent call last):
Keyboardinterrupt
>>> raise MemoryError("This is an argument”)
‘Traceback (most recent calll last):
MemoryError: This is an argument
>>> try:
a= int(input("Enter a positive integer: "))
ifa<=0:
raise ValueError("That is not a positive number!")
. except ValueE rror as ve:
print(ve)
Enter a positive integer: -2
That is not a positive number!
4.4 try...finally
Files, Modules, Packages - 209
The try statement in Python can have an optional finally clause. This clause is
executed no matter what, and is generally used to release
external resources.
For example, we may be connected to a remote data center through the network
or working with a file or working with a Graphical User Interface (GUD)
In all these circumstances, we must clean up the resource once used, whether it
was successful or not. These actions (closing a file, GUI or disconnecting from network)
are performed in the finally clause to guarantee execution.
Here is an example of file operations to illustrate this,
try:
£= open("test.txt",encoding = 'utt-8')
# perform file operations210 - Problem Solving and Python Programming
finally:
felose()
This type of construct makes sure the file is closed even if an exception occurs.
Python has many built-in exceptions which forces your program to output an error
when something in it goes wrong.
However, sometimes you may need to create custom exceptions that serves your
purpose.
In Python, users can define such exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception class
Most of the built-in exceptions are also derived form this class.
>>> class CustomError(Exception):
pass
>>> raise CustomError
Traceback (most recent call last):
—main__.CustomError
>>> raise CustomError("An error occurred”)
Traceback (most recent call last):
__main__.CustomError: An error occurred
Here, we have created a user-defined exception called Custom Error which is
derived from the Exception class. This new exception can be raised, like other
exceptions, using the raise statement with an optional error message.
When we are developing a large Python program, it is a good practice to place
all the user-defined exceptions that our program raises in a separate file. Many
standard modules do this. They define their exceptions separately as exceptions.py or
errors.py (generally but not always).Files, Modules, Packages - 211
User-defined exception class can implement everything a normal class can do,
but we generally make them simple and concise. Most implementations declare a
custom base class and derive others exception classes from this base class. This concept
is made clearer in the following example.
Example: User-Defined Exception in Python
In this example, we will illustrate how user-defined exceptions can be used in a
program to raise and catch errors.
This program will ask the user to enter a number until they guess a stored
number correctly. To help them figure it out, hint is provided whether their guess is
greater than or less than the stored number.
# define Python user-defined exceptions
class Error(Exception):
“Base class for other exception.
pass
class ValueTooSmall Error(Error)
Raised when the input value is too small
pass
cla
s ValueTooLargeError(Error):
Rai
sed when the input value is too large’
pass
# our main program
# user guesses a number until he/she gets it right
# you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a number: "))212 - Problem Solving and Python Programming
if inum< number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")
Here is a sample run of this program.
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
Here, we have defined a base class called Error.
The other two exceptions (Value Too Small Error and Value Too Large Error)
that are actually raised by our program are derived from this class. This is the standard
way to define user-defined exceptions in Python programming, but you are not limited
to this way only.Files, Modules, Packages - 213
5. PACKAGES AND MODULES
5.1 Modules
If you quit from the Python interpreter and enter it again, the definitions you
have made (functions and variables) are lost. Therefore, if you want to write a
somewhat longer program, you are better off using a text editor to prepare the input for
the interpreter and running it with that file as input instead. This is known as creating a
script. As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you've written in several
programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is called a module;
definitions from a module can be imported into other modules or into the main module
(the collection of variables that you have access to in a script executed at the top level
and in calculator mode).
A module is a file containing Python definitions and statements, The file name is
the module name with the suffix .py appended. Within a module, the module’s name
(as a string) is available as the value of the global variable _name__. For instance, use
your favorite text editor to create a file called fibo.py in the current directory with the
following contents
4# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a,b=0,1
while b <1
print b,
a,b=b,atb
def fib2(n): # return Fibonacci series up ton
result = []
ab=0,1
while b >> import fibo
This does not enter the names of the functions defined in fibo directly in the
current symbol table; it only enters the module name fibo there. Using the module
name you can access the functions:
>>> fibo.fib(1000)
11235 813213455 89 144 233 377 610 987
>>> fibo.fib2(100)
(1,1, 2, 3,5, 8, 13, 21, 34, 55, 89]
>>> fibo._name_
‘fibo!
If you intend to use a function often you can assign it to a local name:
>>> fib = fibo.fib
>>> fib(600)
11235813 213455 89 144 233 377
5.2 More on Modules
A module can contain executable statements as well as function definitions
These statements are intended to initialize the module. They are executed only the first
time the module name is encountered in an import statement. [1] (They are also run if
the file is executed as a script.)
Each module has its own private symbol table, which is used as the global
symbol table by all functions defined in the module. Thus, the author of a module can
use global variables in the module without worrying about accidental clashes with a
user's global variables. On the other hand, if you know what you are doing you can
touch a module's global variables with the same notation used to refer to its functions,
modnameitemname.Files, Modules, Packages - 215
Modules can import other modules. It is customary but not required to place all
import statements at the beginning of a module (or script, for that matter). The
imported module names are placed in the importing module's global symbol table.
There is a variant of the import statement that imports names from a module
directly into the importing module's symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
1123581321 3455 89 144 233 377
This does not introduce the module name from which the imports are taken in
the local symbol table (so in the example, fibo is not defined).
‘There is even a variant to import all names that a module defines:
>>> from fibo import *
>>> fib(500)
11235 813213455 89 144 233 377
This imports all names except those beginning with an underscore (_).
Note that in general the practice of importing * from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to use it
to save typing in interactive sessions.
Note
For efficiency reasons, each module is only imported once per interpreter
session, Therefore, if you change your modules, you must restart the interpreter ~ or, if
it’s just one module you want to test interactively, use reload(), e.g. reload(module
name),
5.3 Executing modules as scripts
When you run a Python module with
python fibo.py 216 - Problem Solving and Python Programming
the code in the module will be executed, just as if you imported it but with the
__name__ set to "_main_". That means that by adding this code at the end of your
module:
if __name_ ="__main.
import sys
fib(int(sys.argv[1))
you can make the file usable as a script as well as an importable module, because the
code that parses the command line only runs if the module is executed as the “main”
file:
$ python fibo.py 50
112358132134
If the module is imported, the code is not run:
>>> import fibo
>>
This is often used either to provide a convenient user interface to a module, or for
testing purposes (running the module as a script executes a test suite).
5.4 The Module Search Path
When a module named spam is imported, the interpreter first searches for a
built-in module with that name. If not found, it then searches for a file named spam.py
in a list of directories given by the variable sys.path. sys.path is initialized from these
locations:
* the directory containing the input script (or the current directory).
* PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
+ the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory
containing the script being run is placed at the beginning of the search path, ahead ofFiles, Modules, Packages - 217
the standard library path. This means that scripts in that directory will be loaded
instead of modules of the same name in the library directory. This is an error unless the
replacement is intended. See section Standard Modules for more information.
5.5 “Compiled” Python files
‘As an important speed-up of the start-up time for short programs that use a lot
of standard modules, if a file called spam.pyc exists in the directory where spam.py is
found, this is assumed to contain an already-“byte-compiled” version of the module
spam. The modification time of the version of spam.py used to create spam.pyc is
recorded in spam.pyc, and the -pyc file is ignored if these don’t match.
Normally, you don’t need to do anything to create the spam.pyc file. Whenever
spam.py is successfully compiled, an attempt is made to write the compiled version to
spam.pyc. It is not an error if this attempt fails; if for any reason the file is not written
completely, the resulting spam.pyc file will be recognized as invalid and thus ignored
later. The contents of the spam.pyc file are platform independent, so a Python module
directory can be shared by machines of different architectures.
Some tips for experts:
+ When the Python interpreter is invoked with the -O flag, optimized code is
generated and stored in .pyo files. The optimizer currently doesn’t help much; it
only removes assert statements. When -O is used, all bytecode is optimized; .pye
files are ignored and -py files are compiled to optimized bytecode.
+ Passing two -O flags to the Python interpreter (-OO) will cause the bytecode
compiler to perform optimizations that could in some rare cases result in
doc__ strings are removed from the
malfunctioning programs. Currently only
bytecode, resulting in more compact .pyo files. Since some programs may rely on
having these available, you should only use this option if you know what you're
doing.
+ A program doesn’t run any faster when it is read from a .pyc or .pyo file than
when it is read from a py file; the only thing that's faster about .pyc or .pyo files is
the speed with which they are loaded.
+ When a scriptis run by giving its name on the command line, the bytecode for the
script is never written to a .pyc or .pyo file. Thus, the startup time of a script may
be reduced by moving most of its code to a module and having a small bootstrap218 - Problem Solving and Python Programming
script that imports that module. It is also possible to name a pyc or .pyo file directly
on the command line,
+ Itis possible to have a file called spam.pyc (or spam.pyo when -O is used) without
a file spam-py for the same module. This can be used to distribute a library of
Python code in a form that is moderately hard to reverse engineer.
+ The module compileall can create .pyc files (or -pyo files when -O is used) for all
modules in a directory
5.6 Standard Modules
Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (“Library Reference” hereafter). Some
modules are built into the interpreter; these provide access to operations that are not
part of the core of the language but are nevertheless built in, either for efficiency or to
provide access to operating system primitives such as system calls. The set of such
modules is a configuration option which also depends on the underlying platform. For
example, the winreg module is only provided on Windows systems. One particular
module deserves some attention: sys, which is built into every Python interpreter. The
variables s
prompt
.psl and sys.ps2 define the strings used as primary and secondary
>>> import sys
>
>>> sys.ps2
>>> sys.psl ='C>’
C> print ‘Yuck!’
Yuck!
o
These two variables are only defined if the interpreter is in interactive mode.
The variable sys.path is a list of strings that determines the interpreter’s search path for
modules. It is initialized to a default path taken from the environment variable
PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify
it using standard list operations:Files, Modules, Packages - 219
>>> import sys
>>> sys path append (/ufs/guido/lib/py thon’)
5.7 The dir() Function
The built-in function dir() is used to find out which names a module defines. It returns a
sorted list of strings:
>>> import fibo, sys
>>> dir(fibo)
[_name__’, fib’, 'fib2']
>>> dir(sys)
[_displayhook_','__doc_','_excepthook__', "_name_', '_package_,
stderr_','_stdin_
'_stdout_!
"_clear_type_cache',
‘_current_frames’, '_getframe’, '_mercurial’, 'api_version’, ‘argv’,
‘builtin_module_names,, 'byteorder, 'call_tracing’, ‘callstats',
‘copyright, ‘displayhook', 'dont_write_bytecode’, 'exc_clear’, 'exc_info’,
"exc_traceback,, 'exc_type’, 'exc_value’, ‘excepthook’, 'exec_prefix',
‘executable’, ‘exit, ‘flags’, ‘float_info’, 'float_repr_style’,
‘getcheckinterval, 'getdefaultencoding’, 'getdlopenflags',
‘getfilesy stemencoding’, 'getobjects’, 'getprofile’, ‘getrecursionlimit’,
‘getrefcount, ‘getsizeof, 'gettotalrefcount, ‘gettrace’, ‘hexversion’,
‘long_info’, ‘maxint, 'maxsize’, 'maxunicode’, 'meta_path’, 'modules',
‘path’, 'path_hooks’, 'path_importer_cache’, ‘platform’, 'prefix,, ‘ps1’,
‘py3kwaming’, 'setcheckinterval’, 'setdlopenflags’, 'setprofile’,
‘setrecursionlimit’, 'settrace’, ‘stderr’, ‘stdin’, ‘stdout’, ‘subversion’,
‘version’, 'version_info’, 'warnoptions']
Without arguments, dir() lists the names you have defined currently:
>e>a=[1,2,3,4,5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
[_builtins_', '_name_
\_package_','a’, ‘fib’, 'fibo', ‘sys']
Note that it lists all types of names: variables, modules, functions, ete.220 - Problem Solving and Python Programming
dir() does not list the names of built-in functions and variables. If you want a list of
those, they are defined in the standard module __builtin +
>>> import __builtin__
>>> dir(__builtin_)
[ArithmeticError’, 'AssertionError, 'AttributeError’, 'BaseException’,
'BufferError, ‘BytesWarning,, ‘DeprecationWarning’, 'EOFError’,
"Ellipsis’, 'EnvironmentError’, 'Exception’, ‘False’, 'FloatingPointError’,
"FutureWaming’, ‘GeneratorExit’, ‘1OError’, ‘ImportError, 'ImportWaming’,
‘IndentationError,, ‘IndexError, 'KeyError’, 'Keyboardinterrupt’,
‘LookupError,, 'MemoryError’, 'NameError’, ‘None’, 'NotImplemented’,
‘NotimplementedError’, ‘OSError, ‘OverflowError',
"PendingDeprecationWarning’, 'ReferenceError’, 'RuntimeError’,
"RuntimeWarning’, 'StandardError,, ‘Stoplteration’, ‘SyntaxError’,
"SyntaxWarning’, 'SystemError,, ‘SystemExit,, ‘TabError’, ‘True’,
"TypeError’, ‘Unbound LocalError,, 'UnicodeDecodeError’,
"UnicodeEncodeError’, 'UnicodeError,, 'UnicodeTranslateError’,
"UnicodeWaring’, 'UserWarning’, 'ValueError’, ‘Warning’,
‘ZeroDivisionError’, _'
debug__','_doc_','_import_’,
_name_','_package_’, ‘abs’, ‘all’, ‘any’, ‘apply’, ‘basestring’,
‘bin, ‘bool, ‘buffer’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’,
‘classmethod’, ‘emp’, ‘coerce’, ‘compile’, ‘complex’, ‘copyright’,
‘credits, ‘delattr’ ‘dict, ‘dir’, 'divmod’, ‘enumerate’, ‘eval’,
‘execfile, ‘exit, file’, ‘filter, ‘float’, format, ‘frozenset’,
‘getattr, ‘globals’, 'hasattr,, hash, ‘help’, ‘hex’, id’, ‘input’,
‘int, 'intern’, ‘isinstance’, ‘issubclass,, ‘iter’, ‘len’, ‘license’,
‘list, ‘locals’, 'long’, ‘map’, ‘max’, '‘memoryview’, ‘min’, ‘next’,
‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, 'print, ‘property’, ‘quit,
‘range’, ‘raw_input,, ‘reduce’, ‘reload’, ‘repr’, ‘reversed’, ‘round’,
‘set, ‘setattr, ‘slice’, ‘sorted’, 'staticmethod’, ‘str’, ‘sum’, ‘super’,
‘tuple’, ‘type’, 'unichr’, ‘unicode’, ‘vars’, 'xrange’, 'zip']
5.8 Packages
Packages are a way of structuring Python’s module namespace by using “dotted
module names”. For example, the module name A.B designates a submodule named B
in a package named A. Just like the use of modules saves the authors of differentFiles, Modules, Packages - 221
modules from having to worry about each other's global variable names, the use of
dotted module names saves the authors of multi-module packages like NumPy or the
Python Imaging Library from having to worry about each other’s module names.
Suppose you want to design a collection of modules (a “package”) for the
uniform handling of sound files and sound data. There are many different sound file
formats (usually recognized by their extension, for example: .wav, .aiff, au), so you
may need to create and maintain a growing collection of modules for the conversion
between the various file formats. There are also many different operations you might
want to perform on sound data (such as mixing, adding echo, applying an equalizer
function, creating an artificial stereo effect), so in addition you will be writing a never-
ending stream of modules to perform these operations. Here's a possible structure for
your package (expressed in terms of a hierarchical filesystem)
sound/ Top-level package
__init_.py Initialize the sound package
formats/ Subpackage for file format conversions
“PY
wavread.py
__init,
wavwrite.py
aiffread.py
aiffwrite py
auread.py
auwrite.py
effects/ Subpackage for sound effects
__init__py
echo.py
surround.py
reverse.py
filters/ Subpackage for filters
py
equalizer.py
init222 - Problem Solving and Python Programming
vocoder.py
karaoke.py
When importing the package, Python searches through the directories on
sys.path looking for the package subdirectory.
The _init_.py files are required to make Python treat the directories as
containing packages; this is done to prevent directories with a common name, such as
string, from unintentionally hiding valid modules that occur later on the module search
path. In the simplest case, _i
’t__py can just be an empty file, but it can also execute
initialization code for the package or set the __all__ variable, described later.
Users of the package can import individual modules from the package, for
example:
import sound.effects.echo
This loads the submodule sound.effects.echo. It must be referenced with its full name.
sound effects.echo.echofilter(input, output, delay=0.7, atten=4)
An alternative way of importing the submodule is:
from sound.effects import echo
This also loads the submodule echo, and makes it available without its package prefix,
so it can be used as follows:
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directl y
from sound.effects.echo import echofilter
Again, this loads the submodule echo, but this makes its function echofilter() directly
available:
echofilter(input, output, delay-0.7, atten~4)Files, Modules, Packages - 223
Note that when using from package import item, the item can be either a submodule (or
subpackage) of the package, or some other name defined in the package, like a function,
class or variable. The import statement first tests whether the item is defined in the
package; if not, it
sumes it is a module and attempts to load it. If it fails to find it, an
Import Error exception is raised.
Contrarily, when using syntax like import item. subitem. subsubitem, each item
except for the last must be a package; the last item can be a module or a package but
can’t be a class or function or variable defined in the previous item.
5.9 Importing * From a Package
Now what happens when the user writes from sound.effects import *? Ideally,
one would hope that this somehow goes out to the filesystem, finds which submodules
are present in the package, and imports them all. This could take a long time and
importing sub-modules might have unwanted side-effects that should only happen
when the sub-module is explicitly imported
The only solution is for the package author to provide an explicit index of the
package. The import statement uses the following convention: if a package's __init_.py
code defines a list named __all_, it is taken to be the list of module names that should
be imported when from package import * is encountered. It is up to the package author
to keep this list up-to-date when a new version of the package is released. Package
authors may also decide not to support it, if they don’t see a use for importing * from
their package. For example, the file sound/effects/_init_.py could contain the
following code:
__all__=["echo", "surround", "reverse")
This would mean that from sound.effects import * would import the three
named submodules of the sound package.
If __all__ is not defined, the statement from sound.effects import * does not
import all submodules from the package sound.effects into the current namespace; it
only ensures that the package sound.effects has been imported (possibly running any
initialization code in __init_.py) and then imports whatever names are defined in the
package. This includes any names defined (and submodules explicitly loaded) by224 - Problem Solving and Python Programming
__init__py. It also includes any submodules of the package that were explicitly loaded
by previous import statements. Consider this code:
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
In this example, the echo and surround modules are imported in the current namespace
because they are defined in the sound.effects package when the from...import statement
is executed. (This also works when __all__ is defined.)
Although certain modules are designed to export only names that follow certain
patterns when you use import *, itis still considered bad practice in production code.
Remember, there is nothing wrong with using from Package import
specific_submodule! In fact, this is the recommended notation unless the importing
module needs to use submodules with the same name from different packages.
5.10 Intra-package References
The submodules often need to refer to each other. For example, the surround
module might use the echo module. In fact, such references are so common that the
import statement first looks in the containing package before looking in the standard
module search path. Thus, the surround module can simply use import echo or from
echo import echofilter. If the imported module is not found in the current package (the
package of which the current module is a submodule), the import statement looks for a
top-level module with the given name.
When packages are structured into subpackages (as with the sound package in
the example), you can use absolute imports to refer to submodules of siblings packages.
For example, if the module sound. filters. vocoder needs to use the echo module in the
sound.effects package, it can use from sound.effects import echo,
Starting with Python 2.5, in addition to the implicit relative imports described
above, you can write explicit relative imports with the from module import name form
of import statement. These explicit relative imports use leading dots to indicate the
current and parent packages involved in the relative import. From the surround
module for example, you might use:Files, Modules, Packages - 225
from . import echo
from .. import formats
from ..filters import equalizer
Note that both explicit and implicit relative imports are based on the name of the
current module. Since the name of the main module is always "__main__", modules
intended for use as the main module of a Python application should always use
absolute imports.
5.11 Packages in Multiple Directories
Packages support one more special attribute, __path__. This is initialized to be a
list containing the name of the directory holding the package's __init_.py before the
code in that file is executed. This variable can be modified; doing so affects future
searches for modules and subpackages contained in the package.
While this feature is not often needed, it can be used to extend the set of
modules found in a package.
ILLUSTRATIVE PROGRAMS.
Problem 1: Word Count
Program Coding
fname = input("Enter file name: ")
num_words = 0
with open(iname, 'r') as f:
for line in f:
words =line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Output
Case 1:
Contents of file:226 - Problem Solving and Python Programming
Hello world
Output:
Enter file name: datal.txt
Number of words:
2
Case 2:
Contents of file:
This programming language is
Python
Output:
Enter file name: data2.txt
Number of words:
5
Screenshots
fname ~ input("Enter file nam
mmum_words = 0
with open(fname, ‘r’) as f:
for line inf
words = line.split()
num_words +=len(words)
print(”number of words:”)
print(num_words)Files, Modules, Packages - 227
Output
case I:
Contents of file:
Hello world
Output
Enter file name : datal txt
Number of words:
2
case 2:
Contents of file:
This programming language is
Python
Output
Enter file name : data2.txt
‘Number of words:
5
Problem 2: Copy File
Program Coding
from shutil import copy file
from sys import exit
source = input("Enter source file with full path: ")
target = input("Enter target file with full path: ")
# adding exception handling
try:
copyfile(source, target)
except IOError as e:228 - Problem Solving and Python Programming
print("Unable to copy file. %s" % e)
exit(1)
except:
print("Unexpected errors", sys.exc_info())
exit(1)
print("\nFile copy done!\n")
while True:
print("Do you like to print the file ? (y/n)
check = input()
if check
break
elif chee!
file = open(target, "r")
print("\nHere follows the file content: \n")
print(file.read())
file.close()
print)
break
else:
continue
Output