Python All Units New2
Python All Units New2
CHAPTER 1
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in
a list, insert a card in a list of sorted cards, and guess an integer number in a range, Towers of
Hanoi.
1
Problem Solving and Python Programming 2020
2
Problem Solving and Python Programming 2020
i) Time: A good algorithm should take less time to execute the program.
ii) Memory: A good algorithm should take less memory space to execute the program.
iii) Accuracy: A good algorithm should provide more accurate results.
iv) Sequence: A good algorithm should be written in sequence (step-by-step).
v) Understandability: A good algorithm should be easily understandable.
vi) Solvability: A good algorithm should solve the problem.
1.1.3 Two important factors of an algorithm
3
Problem Solving and Python Programming 2020
1. Start
2. Print “Enter two numbers:”
3. Read A, B
4. C=A+B
5. Print C
6. Stop
4
Problem Solving and Python Programming 2020
1. Start
2. Print “Enter two numbers:”
3. Input a, b
4. c = a
5. a = b
6. b = c
7. Print a, b
8. Stop
Example 3: Construct an algorithm to check whether the given number is odd or even.
1. Start
2. Print “Enter two numbers:”
3. Read n
4. r = n%2
5. If r = 0 then
6. Print “Number is even”
7. If r! =0 then
8. Print “Number is odd”
9. Stop
Example 4: Write an algorithm to find the area of the circle.
1. Start
2. Print “Enter radius:”
3. Input r
4. a = 3.14*r*r
5. Print a
6. Stop
1.2 BUILDING BLOCKS OF AN ALGORITHM
i) Instructions/Statements
ii) State
iii) Control Flow
iv) Functions
1.2.1 Instructions/Statements
Instructions/Statements are the steps which solves a particular problem. Most algorithms
have the basic parts of statements.
→ Description of the problem.
→ Setup
→ Parameters
→ Execution
→ Conclusion
Example: To find the sum of two numbers.
Description of the problem:
To find the sum of two numbers.
Setup:
Two numbers required for addition and one variable for storing the result.
Parameters:
1. Read first number.
2. Read the second number.
Execution:
Calculate the sum of two numbers (a,b)
result = a + b
Conclusion:
The desired output is the sum of two numbers which is stored in the variable ‘result’.
1.2.2 State
3. PROCESS state
4. OUTPUT state
5. STOP state
STOP OUTPUT
7
Problem Solving and Python Programming 2020
Statement 1
Statement2
Statement3
4. Print c
5. Stop
Flowchart:
Start
Read F
c=(5/9)*(f-32)
Print c
STOP
8
Problem Solving and Python Programming 2020
Yes No
Condition
Statement 1 Statement 2
1. Start
2. Read a, b
3. If a>b then Print “a is big”
4. Else Print “b is big”
5. Stop
Yes No
If
A>B
A is BIG B is BIG
One or more steps are performed repeatedly. This logic is used for producing loops in the
program. The looping process can either be one time or multiple times based on the condition.
9
Problem Solving and Python Programming 2020
No
Condition Statement 2
Yes
Statement 1
1. Start
2. Initialize n=0
3. Increment n=n+1
4. Print n
5. If n<=10 then goto step 3
6. Else goto step 7
7. Stop
Flowchart:
Start
n=0
n= n+1
Print n
Yes
If
n<=10
No
Stop
10
Problem Solving and Python Programming 2020
1.2.4 Functions
1. Start
2. Read l1, l2, l3…ln into array.
3. Initialize max=l1
4. Read next number l1, do the following
i. If max< l1 then
I) max = l1
ii. Repeat step” i” until n
5. Print max
6. Stop
1.2.5 Advantages of algorithm
i) Easy to understand.
ii) Easy to debug.
iii) It is easy for a programmer to convert algorithm into actual program.
1.2.6 Disadvantages of algorithm
i) It is time consuming. (An algorithm is developed first, which is then converted into
flow chart and then program).
ii) It is difficult to show branching and looping.
1.3 NOTATION
1.3.1 Pseudo code
Pseudo code is made up of two words: Pseudo and code. Pseudo means ‘imitation’ and
‘code’ refers to instructions written in programming language. Pseudo code is not a real
programming language, but it looks like a programming language. Pseudo code is also called as
“Program Design Language [PDL]”. It is an outline of a program, written in a form that can be
11
Problem Solving and Python Programming 2020
easily converted into real programming statements. Pseudo code instructions are written in
normal English.
Rules for writing pseudo code:
→ It is not visual.
→ We do not get a picture of the design.
→ There is no standardized style or format.
→ For a beginner, it is more difficult to follow the logic or write pseudo code.
Example 1: Write Pseudo code to calculate sum and average for n numbers.
BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i < = n, then
COMPUTE sum = sum +i
CALCULATE i=i+1
END FOR
COMPUTE avg = sum/n
PRINT sum, avg
END
Example 2: Write Pseudo code to add two numbers.
BEGIN
SET C=0
READ A, B
ADD C=A+B
PRINT C
END
Example 3: Write Pseudo code to calculate area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
13
Problem Solving and Python Programming 2020
PRINT Area
END
Example 4: Write Pseudo code to read number n and print the integers counting up to n.
BEGIN
READ n
INITIALIZE i to 1
FOR i <= n, then
DISPLAY i
INCREMENT i
END FOR
END
Example 5: Write Pseudo code to find the greatest among two numbers.
BEGIN
Read A, B
IF A >B
PRINT “A is greatest”
ELSE
PRINT “B is greatest”
ENDIF
END
1.3.2 Flowchart
14
Problem Solving and Python Programming 2020
Flowchart symbols:
Wait
9 Delay
10 OR Logical OR
Logical AND
11 AND
15
Problem Solving and Python Programming 2020
A Document
12 Document
vi) Only one flow line should enter a decision symbol but 2 or 3 flow line can leave the decision
symbol.
START STOP
viii) If the flowchart becomes complex, connector symbols are used to reduce the number of
flow lines.
ix) The text within the symbols should be brief.
x) The validity of flowchart should be tested by passing simple test data.
16
Problem Solving and Python Programming 2020
Start
Read
Process
Output
Stop
Advantages:
i) Better communication
It is easy for the programmer to explain the logic of program.
ii) Effective analysis
It is easy to analyze the problem effectively.
iii) Proper documentation
With the help of flowchart good documentation is done for various purposes.
iv) Efficient coding
Flowchart acts as a guide during the system analysis and program development phase.
v) Efficient debugging
It helps in debugging process.
vi) Efficient program maintenance
The maintenance of a program becomes easy with the help of the flowchart.
Disadvantages (Limitations):
i) Complex logic
Sometimes the logic of the program is quite complicated. In such a case flowcharts
become complex.
17
Problem Solving and Python Programming 2020
Start
sum = num1+num2
Print sum
Stop
Start
product =num1*num2
Print product
Stop
18
Problem Solving and Python Programming 2020
19
Problem Solving and Python Programming 2020
program. These languages specify the steps that the program should take to reach to an intended
state. Procedure is a group of statements. It makes the program structured and helps to reuse the
code.
Example: CLIST, Hypertalk, MATLAB, PL/I
v) Scripting programming language
Scripting languages are Programming languages that control applications.
Example: AppleScript, AWK, MAYA, PHP, VBSCRIPT.
vi) Markup programming language
Markup language is an artificial language that define how the text to be displayed.
Example: CURL, SGML, HTML, XML, XHTML.
vii) Logic-based programming language
Logic-based programming language is a type of programming language that is based on
logic.
Example: ALF, Fril, Janus, Leda, Prolog.
viii) Concurrent programming language
It is a computer programming language that executes the operations concurrently.
Example: ABCL, Afnix, E, Joule, Limbo.
OPCODE OPERAND
21
Problem Solving and Python Programming 2020
Design an algorithm
Prove correctness
22
Problem Solving and Python Programming 2020
Parallel algorithms:
→ An algorithm which has the capability of executing the operations concurrently is
called parallel algorithms.
→ RAM model doesn’t support this.
iii) Choosing between exact and approximate problem solving
→The next decision is to choose between solving the problem exactly or solving it
approximately.
→Based on this, the algorithms are classified as exact and approximation algorithms.
Exact algorithms:
→ The algorithms that can solve the problem exactly are called exact algorithms.
Approximate algorithms:
→The algorithms that can solve the problem not exactly are called approximate
algorithms.
→There are three issues to choose an approximation algorithm.
→First, there are certain problems like extracting square roots, solving non-linear
equations which cannot be solved exactly.
→Secondly, if the problem is complicated it slows the operations. E.g. Traveling
salesman problem.
→Third, this algorithm can be a part of a more sophisticated algorithm that solves a
problem exactly.
iv) Deciding on appropriate data structures
→Data structures play a vital role in designing and analyzing the algorithms.
→Some of the algorithm design techniques also depend on the structuring data specifying
a problem’s instance.
Algorithm + Data structure = Programs
v) Algorithm design techniques
23
Problem Solving and Python Programming 2020
→Once an algorithm has been specified, you have to prove its correctness.
→You have to prove that the algorithm yields a required result for every legitimate input
in a finite amount of time.
→A common technique for proving correctness is to use mathematical induction.
viii) Analyzing an algorithm
24
Problem Solving and Python Programming 2020
Iteration and Recursion are the simple strategies for developing algorithms.
1.5.1 Iteration
Iteration is the process of repeating the same set of statements again and again until the
condition becomes false. Iteration is done in two ways.
i) In iteration loop, the condition is checked at the beginning of the loop. If the condition
is true, then the loop will be executed. If the condition is false, the loop will not be executed.
No
If
condition
Yes
ii) Condition is checked at the bottom of the loop. If the condition is true, loop will be
executed. Otherwise the loop will not be executed.
Yes
If
condition
No
25
Problem Solving and Python Programming 2020
Example: Write an algorithm, pseudo code and draw the flowchart to print the numbers from 1
to 10.
Algorithm:
1. Start
2. Initialize n=0
3. Increment n by 1
4. Print n
5. Check condition n<10
i. If yes goto step 3
ii. Otherwise goto step 6
6. Stop
Flowchart:
Start
n=0
n= n+1
Print n
Yes
If
n<10
No
Stop
Pseudo code:
BEGIN
OBTAIN n
INITIALIZE n=0
26
Problem Solving and Python Programming 2020
INCREMENT n=n+1
DISPLAY n
IF n<10 REPEAT the loop
ENDIF
END
1.5.2 Recursion
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Syntax:
function():
function():
In the above syntax, function() is a function which call itself until the condition is reached.
1.5.3 Difference between recursion and iteration
27
Problem Solving and Python Programming 2020
5. Stop
fact(n) function:
1. Start function
2. If n=0, return 1
3. If n>0 return function fact(n)
4. Return
Flowchart :
fact(n)
Start
Read n
if
n=0
fact = fact(n)
Stop
28
Problem Solving and Python Programming 2020
Problem description:
The problem is to find the minimum element in the given list of elements. Finding
minimum in a list of elements can be achieved in different ways. One way is to sort the list of
elements in ascending order and get the first element as minimum. Another method is to compare
each element with other. As an initial step, first element of the list is considered as minimum
element. And in each iteration, each element in the list is compared with the minimum. If the
element in the list is less than the minimum then swap both elements else compare with the next
element in the list. These steps are continued until the end of the list and finally print the
minimum.
Algorithm:
1. Start.
2. Read the list of elements.
3. Set first element in the list as minimum.
4. Move to the next element in the list.
5. If current element<minimum then
Set minimum =current element.
6. Repeat Step 4 and Step 5 until the end of the list is reached.
7. Print the minimum value in the list
8. Stop
Pseudo code:
BEGIN
READ the list of elements.
INITIALIZE min with the first element of the list
FOR each element in the list of elements
IF element is less than min
COPY element to min
29
Problem Solving and Python Programming 2020
ENDIF
ENDFOR
PRINT min as the minimum value
END
Flowchart:
Start
min = element[0]
i=1
No
if i<n
If
element[
i] < min
No
e
min=element[i]
i= i+1
Print min
elements, i
Stop
Playing cards are one of the techniques of sorting and the steps are shown as
follows: Start with an empty left hand and cards face down on the table. Then remove one card
30
Problem Solving and Python Programming 2020
at a time from the table and Insert it into the correct position in the left hand. To find a correct
position for a card, we compare it with each of the cards already in the hand from left to right.
Once the position is found, the cards from that position are moved to the next higher indexed
position and in that order. New card is inserted at the current position.
Algorithm:
1. Start
2. Read the list of sorted cards.
3. Read the new card.
4. Insert a new card to the end of the list.
5. For i=1 to len(a)
6. current_card=a[i]
7. pos=i
8. While pos>0 and a[pos-1]>current_card
9. a[pos]=a[pos-1]
10. pos=pos-1
11. a[pos]=currentcard
12. Print sorted list of cards.
13. Stop
Pseudo code:
BEGIN
READ the list of sorted cards.
READ the new card.
ADD new card to the end of the sorted list.
FOR i=1 to len(a)
current_card=a[i]
pos=i
WHILE pos>0 and a[pos-1]>current_card
a[pos]=a[pos-1]
a[pos]=current_card
ENDWHILE
31
Problem Solving and Python Programming 2020
position = 1
No
position
<
length
Yes
location = Position
No
location>0 &&
position=position+1 cards[location] <
cards[location-1]
yes
Swap card[location]<cards[location-1]
location=location-1
Stop
32
Problem Solving and Python Programming 2020
Algorithm:
1. Start
2. Read n.
3. Read a guess number.
4. If guess > n
5. Print “Your guess is too high”
6. If guess < n
7. Print “ Your guess is too low”
8. Else
9. If guess = n
10. Print “Good job” else print “no”
11. Stop
Pseudo code:
BEGIN
READ n
OBTAIN guess
IF guess > n
DISPLAY “Your guess is too high”
IF guess < n
DISPLAY “Your guess is too low”
ELSE
IF guess=n
DISPLAY “Good Job” ELSE DISPLAY “No’
ENDIF
ENDIF
ENDIF
END
33
Problem Solving and Python Programming 2020
Flowchart:
start
Read n
Read guess
if No
guess >n
Yes
if No
Yes No
if
Print “Too Low”
guess>=n
Yes
Print “Good No
Job”
Stop
34
Problem Solving and Python Programming 2020
A Tower’s of Hanoi is a children’s playing game, played with three poles and a number
of different sized disks which is stacked on the poles. The disks are stacked on the left most pole
in ascending order initially. ie) The largest on the bottom and the smallest on the top.
Rules to be followed:
i) Only one disk can be moved among the towers at any given time.
ii) Only the “top” disk can be removed.
iii) No large disk can sit over a small disk.
The objective is to transfer the disks from the left most pole to the right most pole by
using the centre pole as the temporary pole.
The steps are
i) Move the top n-1 disks from the left pole to the centre pole, n is the number of disks.
ii) Move the nth largest disk to the right pole.
iii) Move the n-1 disks on the centre pole to the right pole.
The total number of moves will be 2n – 1, where n is the number of disks.
Algorithm:
1. Start
2. Read disk, source, dest, aux
3. Call the function Hanoi(disk, source, dest, aux)
4. Stop
Algorithm for function Hanoi(disk, source, dest, aux):
1. Start
2. If disk=1
Move disk from source to dest
3. Else
3.1 Hanoi(disk-1, source, aux, dest)
3.2 Move disk from source to dest
3.3 Hanoi(disk-1, aux, dest, source)
4. Return
35
Problem Solving and Python Programming 2020
A B C
1 2
A B C A B C
4
3
A B C A B C
5 6
A B C A B C
A B C
36
Problem Solving and Python Programming 2020
Flowchart:
Hanoi()
Start
Read disk
If
n=1
Define function
Hanoi()
Move disk from souce to
dest
Stop
Move disk from source to
dest
Return
Pseudo code:
BEGIN
READ disk, source, dest, aux
FUNCTION Hanoi (disk, source, dest, aux)
END
37
Problem Solving and Python Programming 2020
38
Problem Solving and Python Programming 2020
39
Problem Solving and Python Programming 2020
and other shapes connected by arrows where each shape represents a step in the process. The
arrows show the order of the flow of execution.
6. What are the advantages of flowchart?
i) Better communication
ii) Efficient analysis of program
iii) Efficient coding
iv) Efficient debugging
7. What are the disadvantages of flowchart?
i) Complex logic
ii) Difficult to alter and modify
iii) Difficult to reproduce
8. Define Pseudo code.
Pseudo code is made up of two words: Pseudo and code. Pseudo means imitation and
code refers to instructions written in programming language. Pseudo code is not a real
programming language, but it looks like a programming language. It is an outline of a program,
written in a form that can be easily converted into real programming statements.
9. What are the rules for writing Pseudo code?
i) Write one statement per line.
ii) Capitalize initial keywords.
iii) End Multiline structure.
iv) Keep Statements language independent.
10. Differentiate Recursion and Iteration.
Sl.No Recursion Iteration
1 Function calls itself until the Repetition of loop until condition
base condition is reached. fails.
2 It keeps code short and It keeps the code longer.
simple.
3 It is slower. It is faster.
4 It takes more memory. It takes less memory.
5 Tracing is difficult if any Tracing is easier if any problem
problem occurs. occurs.
40
Problem Solving and Python Programming 2020
11. Write the pseudo code to calculate the sum and product of two numbers and display it.
BEGIN
INITIALIZE sum, product, number1, number2
PRINT “Input two numbers”
READ number1, number2
sum = number1 + number2
PRINT sum
COMPUTE product = number1 * number2
PRINT product
END
12. What is a function?
A function is a block of organizes, reusable code which is used to perform a task or action.
It provides better modularity. They are also called as methods, routines, procedures etc.
13. List the categories of programming languages.
Programming languages can be divided into nine major categories.
i) Interpreted Programming language
ii) Functional Programming language
iii) Compiled Programming language
iv) Procedural Programming language
v) Scripting Programming language
vi) Markup Programming language.
vii) Logic-based Programming language
viii) Concurrent Programming language.
ix) Object-Oriented Programming language.
14. Write an algorithm to accept two number’s, compute the result and print the result.
(JANUARY 2018)
1. Start
2. Read n1, n2
3. result = n1 + n2
4. Print result
41
Problem Solving and Python Programming 2020
5. Stop
15. Write an algorithm and give the flowchart to find the net salary of an employee.
Algorithm:
1. Start
2. Read the basic salary
3. If the basic is greater than or equal to 4000 ELSE Goto Step 4
4. DA= 0.32 * basic (Dearness Allowance)
5. HRA = 0.15 * basic (House Rent Allowance)
6. CCA = 325 (City Compensatory Allowance)
7. Net Salary= basic + DA HRA + CCA
8. Print Net Salary
9. Stop
16. Define Programming Language.
Programming languages are used to communicate instructions to the computer.
Programming languages are written based on syntactic and semantic rules.
17. What is control flow?
Control flow represents the order of statements execution or direction of flow of program.
There are three types of control flow
→ Sequential control flow
→ Selection control flow
→ Repetition control flow
18. Write an algorithm to find the largest of two numbers.
1. Start
2. Read a, b
3. If a is greater than b then Print “a is large”
4. Else Print “b is large”
5. Stop.
42
Problem Solving and Python Programming 2020
20. Write an algorithm to find the minimum number in a given list of numbers.
(JANUARY 2019)
1. Start
2. Read each elements one by one.
3. Assign the first element as the minimum.
4. Move to the next element.
5. If the current element<minimum then
Set minimum=current element
6. Repeat the Step 4 and Step 5 until the end of the list is reached.
7. Print minimum.
8. Stop.
21. How will you analyze the efficiency of an algorithm? (JANUARY 2020)
(i) Time (ii) Space
22. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of problem
solving? (JANUARY 2020)
It will give finite number of clearly defined steps to derive a solution for a given problem.
43
Problem Solving and Python Programming 2020
44
Problem Solving and Python Programming 2020
13. i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6) (JANUARY 2020)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosssthenes is a simple algorithm for finding all prime numbers up to a specified integer. It
wae created by the ancient Greek mathematician Eratosthenes. The algorithm to find all prime
numbers less than or equal to a given integer n:
1)Create a list of integers from two to n:2,3,4,….n
2)start with a counter i set to 2. (i.e)the first prime number
3)starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4)find the first number of the list following i.This is the next prime number
5)set I to thenumber found in the previous step
6)repeat steps 3 and 4 untill I is greater than n.
7)all the numbers,which are still in the list,are prime numbers (10) (JANUARY 2020)
45
Problem Solving and Python Programming 2020
Additional Problems
1. Start
2. Print “Enter three numbers:”
3. Read a, b, c
4. If a > b then
i. If a > c then
print “a is largest”
ii. Else
print “c is largest”
iii. Else if b > c then
print “b is largest”
iv. Else
print “c is largest”
5. Stop
Example 2: Construct an algorithm for incrementing value of a variable that starts with initial
value 1 and stops when value becomes 5.
1. Start
2. c = 1
3. Print c
4. c = c+1
5. If c <= 5 then Goto 3
6. Stop
Example 3: Construct an algorithm to find the given year is leap year or not.
1. Start
2. Print “Enter the year:”
3. Read year
4. If year%4==0
i. Print “Leap year”
5. Else
46
Problem Solving and Python Programming 2020
1. Start
2. Input n
3. Initialize sum=0, i=1
4. If i<=n goto 6
5. Else
i. sum= sum + i
6. Increment i=i+2
7. Goto 4
8. Print sum
9. Stop
47
Problem Solving and Python Programming 2020
1. Start
2. Read a,b,c
3. s=(a+b+c)/2
4. area=sqrt(s*(s-a)*(s-b)*(s-c))
5. Print area
6. Stop
Example 8: Algorithm to compute and print the average of 10 numbers
1. Start
2. Initialize total=0, average=0
3. For 1 to 10
4. Read num
5. total = total + num
6. End For
7. Calculate average=total/10
8. Print average
9. Stop.
Example 9: Algorithm to swap two variables.
1. Start
2. Read a,b
3. Assign temp=a
4. Assign a=b
5. Assign b=temp
6. Print a,b
9. Stop.
Example 10: Write Pseudo code to determine a student whether successful or fail.
BEGIN
READ grade
IF grade>=50
48
Problem Solving and Python Programming 2020
PRINT "passed"
ELSE
PRINT "failed“
ENDIF
END
Example 11: Write Pseudo code to swap the variables.
BEGIN
SET A=0, B=0, C=0
READ A, B, C
C=A
A=B
B=C
PRINT A, B
END
Example 12: Write Pseudo code to check whether the given number is odd or even.
BEGIN
READ number
IF number%2=0 THEN
DISPLAY “Number is Even”
ELSE
DISPLAY “Number is Odd”
ENDIF
END
Example 13: Write Pseudo code to print the numbers from 1 to 100.
BEGIN
READ i
INITIALISE i=1
WHILE i <=100
DISPLAY i
49
Problem Solving and Python Programming 2020
INCREMENT i=i+1
ENDWHILE
END
Example 14: Pseudo code for computing the area of a rectangle.
BEGIN
READ height
READ width
COMPUTE area=height * width
PRINT area
END
Example 15: Pseudo code for computing the average of five numbers.
BEGIN
PRINT “Enter 5 numbers”
READ n1, n2, n3, n4, n5
PRINT “The average is”
SET avg=(n1+n2+n3+n4+n5)/5
PRINT avg
END
Example 16: Write Pseudo code to check whether the given number is positive or negative.
BEGIN
READ number
IF number > 0 THEN
DISPLAY “Number is Positive”
ELSE
DISPLAY “Number is Negative”
ENDIF
END
Example 17: Write Pseudo code to check whether the given year is leap year or not.
BEGIN
50
Problem Solving and Python Programming 2020
READ year
IF year %4 = 0 && year %100!=0 && year % 400 =0 THEN
DISPLAY “Leap Year”
ELSE
DISPLAY “Not a Leap Year”
ENDIF
END
Start
Initialize x=0
Increment x = x+ 1
Print x
Yes
If x<
20
No
Stop
51
Problem Solving and Python Programming 2020
2
Example 19: Flowchart representation to find all the roots of a quadratic equation ax +bx+c=0
Start
D= b-4ac
True False
Is
D>=0?
r2=(-b-sqrt(D))/2a rp =sqrt(D)/2a
x1 =rp+ j ip
x2=rp- j ip
Display r1 , r2
Stop
52
Problem Solving and Python Programming 2020
Example 20: Flowchart representation to find the Fibonacci series till term≤1000.
Start
fterm=0, sterm= 1
False
Is
sterm<=1000?
True
Display sterm
temp=sterm
sterm=sterm+fterm
fterm=temp Stop
53
Problem Solving and Python Programming 2020
Example 21: Flowchart representation to find whether the given number is odd or even.
Start
Read n
No If Yes
n%2==0
Stop
54
Problem Solving and Python Programming 2020
CHAPTER 2
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and
arguments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points
55
Problem Solving and Python Programming 2020
56
Problem Solving and Python Programming 2020
57
Problem Solving and Python Programming 2020
Source code
Output
Python
data
Interpreter
Input data
58
Problem Solving and Python Programming 2020
59
Problem Solving and Python Programming 2020
60
Problem Solving and Python Programming 2020
Data types
1. Complex 1. Strings
2. Integer
3. Floating 2. Tuples Dictionary
point 3. Lists
4. Boolean
Fig 2.3: List of data types in Python
2.2.1 Integer (type int)
An integer data type represents the whole numbers. It represents positive and negative
numbers. Integer data type have unlimited size in Python.
Example: -3, 2 etc
Types of integer data type:
i) Regular integer
ii) Binary literals (base 2)
iii) Octal literals (base 8)
iv) Hexa decimal literals (base 16)
61
Problem Solving and Python Programming 2020
i) Regular integer
They are normal integers.
Example:
>>>a=9293
>>>b= -136
ii) Binary literals (base 2)
A binary literal is of the form zero followed by an uppercase B or lowercase b. The
literals are 0 and 1.
Example:
>>>bin=0b1111
>>>print(bin)
Output:
15
iii) Octal literals (base 8)
An octal literal is a number prefixed with zero followed by either uppercase O or lower
case o. The literals are 0 to 7.
Example:
>>>oct=0O24
>>>print(oct)
Output:
20
iv)Hexa decimal literals (base 16)
A hexa decimal literal is prefixed by 0(zero) followed by an upper case X or a lower case
x. The literals are 0 to9, [a-f/A-F].
Example:
>>>hex=0x9A
>>>print(hex)
Output:
154
62
Problem Solving and Python Programming 2020
63
Problem Solving and Python Programming 2020
>>>X+Y
+ Concatenation-Adds values of 2 strings
python program
>>>x[0:3]
[] Slice-Gives the character from the given range.
pyt
>>>x[1:2]
[:] Range slice-Give the characters from the given range.
y
>>>print str[0:3]
Hel
>>>print str[5:]
Python
>>>print str*2
HelloPython HelloPython
>>>print str+”welcome”
HelloPython welcome
2.2.5 Lists
List data type contains elements of various data types. Values in a list are called elements
or items of list. The list is enclosed by square brackets [ ], where items are separated by commas.
List values can be accessed using slice operator ([] or [:]) .The index 0 represents beginning of
the list and -1 represents ending of the list.
→ list[0] represents beginning of list.
→ list[-1] represents ending of list.
Syntax:
listname= [value1,value2,…value n]
Example:
>>>mylist = [10, 10.5, ‘programming’]
Example Program:
>>>mylist= ()
>>>mylist=[‘python’,10,10.5,’program’]
>>>print mylist
[‘python’,10,10.5,’program’]
>>>print mylist[1:3]
[10, 10.5]
>>>print mylist[2:]
[10.5,’program’]
>>>print mylist*2
[‘python’,10,10.5,’program’,’python’,10,10.5,’program’]
65
Problem Solving and Python Programming 2020
>>>print mylist[-1]
[‘program’]
2.3 VARIABLES
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
2.3.1 Rules for naming variables
→Variable name can be any length.
→They can contain both letters and numbers. But they cannot begin with numbers.
→Both upper case and lower case letters are used.
→Variable names are case sensitive.
Example: midname, midName, MidName are different variables.
→Variable name cannot be any one of the keywords.
2.3.2 Assigning values to variables
The equal (=) sign is used to assign the values to variables.
→Left of = operator is the name of the variable.
→Right of = operator is the value of variable.
Example:
>>>X=5
>>>name=”Python”
>>>print X
5
>>>print name
Python
In the above program X and name are variables. The value of X is 5 and the value of name is
Python.
66
Problem Solving and Python Programming 2020
2.4 EXPRESSIONS
Expression is a combination of values, variables, operators and operands. A value itself is
considered as an expression.
Example:
17 #expression
x #expression
x+17 #expression
Expression consists of combination of operators and operands.
Example:
5+ (8*k) #expression
The above expression consists of 2 sub expressions. That is 5 and (8*k).Here sub expression
(8*k) is evaluated first.
Evaluation of expressions:
When expression is typed at the prompt, the interpreter evaluates it, and finds the value of
expression.
Program:
>>>12+8 #expression
20
>>>n=100 #expression
>>>print(n) #expression
100
>>>100 #expression
100
2.5 STATEMENTS (or) I/O STATEMENTS
Statement is a section of code (or) instruction that represents a command (or) action.
2.5.1 Types of statements
i) Assignment statements
ii) Simultaneous assignment statements
iii) Input statements
iv) Print statements
67
Problem Solving and Python Programming 2020
i)Assignment statements
Assignment statements assigns right of = symbol to left of = symbol.
Example:
>>>Name=’CSE’
>>>age=100
>>>Name
CSE
>>>age
100
ii) Simultaneous assignment statements
Simultaneous assignment statement is used to assign more number of values to more
variables simultaneously.
Example:
>>>x,y=10,20
>>>x
10
>>>y
20
>>>sum, diff=x+y, y-x
>>>sum
30
>>>diff
10
69
Problem Solving and Python Programming 2020
Here left side is a tuple of variable. The right side is a tuple of expression.
2.6.1 Working of tuple assignment
i) The first variable in the tuple of left side is assigned to first expression in tuple of right side.
ii) Similarly, the second variable in the tuple of left side is assigned to second expression in
tuple of right side. Number of variables on left side and the number of expressions on the right
side must be same.
Example: Program on tuple assignment
>>>#empty tuple
>>>mytuple=( )
>>>mytuple
()
>>>#tuples having same datatypes
>>>mytuple=(1,2,3,4,5)
>>>mytuple
(1, 2, 3, 4, 5)
>>>#tuples having different datatypes
>>>mytuple=(1,”Python”,2.5)
>>>mytuple
(1,”Python”, 2.5)
>>>#tuple assignment
>>>X, Y, Z= mytuple
>>>X
1
>>>Y
Python
>>>Z
2.5
70
Problem Solving and Python Programming 2020
+ - * ** / // %
Operator precedence:
When an expression contains more than one operator, precedence is used to determine
the order of evaluation. The order of evaluation depends on rules of precedence.
2.7.1 Rules of precedence
i) Parenthesis has the highest precedence.
Example: 5*(9-3)
Here expression in parenthesis is evaluated first.
ii) Exponentiation has next highest precedence.
Example: 1+2**3=9
iii) Multiplication and division have next higher precedence than addition and subtraction.
Example: 3*2-1=5
iv) Operators with same precedence are evaluated from left to right (Except exponentiation).
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).
71
Problem Solving and Python Programming 2020
x[index:index] Slicing
left to right
** Exponentiation right-to-left
+x Unary plus
-x Unary minus left to right
~x Bitwise NOT
* Multiplication
/ Division
left to right
// Floor division
% Remainder
+ Addition left to right
- Subtraction
Bitwise Left Shift and Right
<<, >> left to right
Shift
& Bitwise AND left to right
^ Bitwise XOR left to right
| Bitwise OR left to right
in, not in
Membership tests
is, is not
Identity tests Chain from left to right
<, <=, >, >=, <>, !=,
Comparisons
==
not Boolean NOT left to right
and Boolean AND left to right
or Boolean OR left to right
→The acronym PEMDAS is useful way to remember the rules. That is,
P (parenthesis first)
72
Problem Solving and Python Programming 2020
E (Exponent)
MD (multiplication and division)
AS (addition and subtraction)
→Arithmetic evaluation is carried out using two phases from left to right. During the first phase
highest priority operators are evaluated. The second phase lowest priority operators are
evaluated.
Example:
6+4/2 is 8, not 5.
Example:
>>>X, Y, Z=2, 3, 4
>>>value=X-Y/3+Z*3-1
>>>print(“Result=”,value)
Result=12
2.8 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Comment contains information for persons reading the program. Comment lines are
ignored during program execution. Comment lines have no effect on the program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment
2.8.1 Types of comments
i) Single line comments
ii) Multi line comments
i) Single line comments
Single line comments describes information in one line(short),and they start with the
symbol #.Everything from the # to the end of the line is ignored, it has no effect on the execution
of the program.
73
Problem Solving and Python Programming 2020
Example:
>>>#This is a print statement
>>>print(“Hello python”)
Hello python
ii) Multi line comments
Multi line comments describes information in detail (multiple line).Here,more than
one line of comments can be added to the program in between the triple quotes(” ” ”).
Example:
”””This is print statement
This line print “Hello python”
Written by ABC, April 2017”””
2.9 MODULES AND FUNCTIONS
2.9.1 Modules
Module is a file containing python definitions and statements. We use modules to break
down large programs into small manageable and organized files. Modules provide reusability of
code. Modules are imported from other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found,”module not found” will be displayed.
Modules
74
Problem Solving and Python Programming 2020
75
Problem Solving and Python Programming 2020
c=a+b
return c
ii) Save it as sum.py
iii) Import the module using import command
>>>import sum
>>>print sum.add(10,20)
2.9.2 Functions
A function is a group of statements that perform a specific task. If a program is large, it is
difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Each subprogram specifies one or more actions to be
performed for the larger program. Such subprograms are called as functions. Functions may or
may not take arguments and may or may not produce results.
Function is defined as a block of organized, reusable code that is used to perform single,
related action. Function provides better modularity and high degree of reusing.
Advantages of using functions:
i) Better modularity
ii) High degree of reusing
iii) Better readability
iv) Easy to debug and testing
v) Improved maintainability
Functions
76
Problem Solving and Python Programming 2020
Built-in Functions:
Built-in functions are predefined functions. User can use the functions but cannot
modify them. Python has the following built-in functions.
i) input():read the input from user.
>>>name=input (“Enter the name”)
ii) print():print values to screen.
>>>print (“Hello python”)
iii) type():gives the type of value.
>>>type (12)
<type ‘int’>
iv)min():find minimum value from several values.
>>>min (5,7,8,9)
5
v) max():find maximum value from several values.
>>>max (10,100,50,70)
100
vi) pow():find power of given value.
>>>pow (3,2)
9
User defined functions:
The functions defined by the users according to their requirements are called user-defined
functions. The users can modify the function according to their requirements.
Example:
multiply(), sum_of_numbers(), display()
Elements of user defined functions:
(i)Function definition
(ii)Function-Use (or) function call
77
Problem Solving and Python Programming 2020
Example Program:
1. def sum(a,b):
2. c=a+b
3. return c
4. print(“The sum is:”, sum(10,5))
Python interpreter starts at line 1 of above program. In line 1, there is a function
definition. So it skips the function definition, and go to line 4.In line 4, function call is present.
So it goes back to function definition and execute it. After return statement, it again comes to
line 4 and execute it.
2.12 ARGUMENTS AND PARAMETERS
2.12.1 Arguments
Argument is the value, supply to function call. This value is assigned to corresponding
parameter in the function definition. Arguments are specified within a pair of paranthesis,
separated by commas.
2.12.2 Types of arguments
i) Required arguments
ii) Keyword arguments
iii) Default arguments
iv) Variable-Length arguments
i) Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here number of arguments in function call should match exactly with function definition.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is:10
79
Problem Solving and Python Programming 2020
80
Problem Solving and Python Programming 2020
81
Problem Solving and Python Programming 2020
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
Enter the second number: 10
Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
Using temp function:
n1=input (“Enter the value of a:”)
n2=input (“Enter the value of b:”)
print (“Before Swap:”)
print (“Value of a:”,n1)
print (“Value of b:”,n2)
temp =n1
n1=n2
n2=temp
print(“After Swap:”)
print(“Value of a:”,n1)
print(“Value of b:”,n2)
Output:
Before Swap:
Value of a: 10
Value of b: 15
After Swap:
Value of a: 15
Value of b: 10
82
Problem Solving and Python Programming 2020
83
Problem Solving and Python Programming 2020
84
Problem Solving and Python Programming 2020
Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.
85
Problem Solving and Python Programming 2020
values the operator is applied to are called operands. For eg, in the expression 4 + 5, 4 and 5 are
operands and + is an operator.
5. What is the difference between * operator and ** operator?
* is a multiplication operator which multiplies two operands.
Example: 3*2 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Example: 3**2 returns 9.
6. Compare arguments and parameters.
Arguments Parameters
1.It is the value, which is given to 1.It is the name, which is given in
function call. function definition.
2.Syntax: 2.Syntax:
functionname(arguments) def functionname(parameter):
86
Problem Solving and Python Programming 2020
87
Problem Solving and Python Programming 2020
88
Problem Solving and Python Programming 2020
~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR
22. What are the features of the Python language?
→Easy to learn
→Interpreted
→Interactive
→Object Oriented
→High Level language
23. Name four types of scalar objects in python has. (JANUARY 2018)
The commonly used scalar types in Python are:
Int- Any integer.
Float-Floating point number (64 bit precision).
Bool-True, False.
Str-A sequence of characters.
24.What is tuple? How literals of type tuple are written? Give example (JANUARY 2018)
Tuple is an immutable sequence of values, they are separated by commas. The value can
be any type and they are indexed by integer. The literals of type tuple are written as,
(), (9,), (8, 9, 0)
25. What are keywords? Give example. (JANUARY 2019)
The python interpreter uses keywords to recognize the structure of the program and they
cannot be used as variable names.Python2 has 31 keywords. Example: class, print
26. State the reason to divide programs into functions. (JANUARY 2019)
Creating a new function gives an opportunity to name a group of statements, which
makes program easier to read and debug. Functions can make a program to smaller by
eliminating the repeated code.
89
Problem Solving and Python Programming 2020
27. Compare interpreter and compiler. What type of translator is used for Python?
(JANUARY 2020)
Interpreter - Translates program one statement at a time Compiler - Translates program one
statement at a time. Python uses interpreter as a translator
28. Write a python program to print sum of cubes of the values of n variables.
(JANUARY 2020)
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+i**3
print(sum)
90
Problem Solving and Python Programming 2020
91
Problem Solving and Python Programming 2020
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
(JANUARY 2020)
18.i)Write a python program print the maximum among ‘n’randomly generate ‘d’ numbers by
storing them in a list(10) (JANUARY 2020)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6) (JANUARY 2020)
92
Problem Solving and Python Programming 2020
1. Explain how to write and execute a program in python illustrate the steps for writing a python
program to check whether the number is palindrome or not.
2. Formulate with an example program to pass the list arguments to a function.
3. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii) sum
of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple vii)
Compare two tuples viii) printing two tuples of different data types.
4. Formulate with an example program to find out all the values in the list that is greater than the
specified number.
5. Write a program to find out the square root of two numbers.
93
Problem Solving and Python Programming 2020
Additional Programs
1. Python program to calculate the average of numbers in a given list.
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter the element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter the element: 23
Enter the element: 45
Enter the element: 56
Average of elements in the list 41.33
2. Python program to exchange the values of two numbers without using a temporary
variable.
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
94
Problem Solving and Python Programming 2020
95
Problem Solving and Python Programming 2020
96
Problem Solving and Python Programming 2020
97
Problem Solving and Python Programming 2020
Output:
Enter the lower limit for the range:1
Enter the upper limit for the range:16
1
3
5
7
9
11
13
15
9. Python program to find the sum of digits in a number.
n=int(input("Enter the number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter the number:1892
The total sum of digits is: 20
10. Python program to count the number of digits in a number
n=int(input("Enter the number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
98
Problem Solving and Python Programming 2020
Output:
Enter the number:123
The number of digits in the number are: 3
11. Python program to check if a number is a palindrome.
n=int(input("Enter the number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not a palindrome")
Output:
Enter the number:121
The number is palindrome
12. Python program to take the temperature in Celsius and convert it to Fahrenheit.
Celsius=int(input("Enter the Temperature in Celsius:"))
f=(Celsius*1.8)+32
print("Temperature in Fahrenheit is:",f)
Output:
Enter the Temperature in Celsius:32
Temperature in Fahrenheit is: 89.6
13. Python program to print squares of numbers.
for i in range(1,5,1):
print(i*i)
Output:
1 4 9 16
99
Problem Solving and Python Programming 2020
100
Problem Solving and Python Programming 2020
CHAPTER 3
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary
search.
101
Problem Solving and Python Programming 2020
102
Problem Solving and Python Programming 2020
3.1 CONDITIONALS
3.1.1 Boolean values and operators
Boolean values:
Boolean data types have two values. They are 0 and 1.
→0 represents False
→1 represents True
True and False are keywords. Boolean values are used in comparisons and conditional
expressions. The most common way to produce boolean value is relational operators.
103
Problem Solving and Python Programming 2020
+ Addition
- Subtraction
* Multiplication
/ Division
Example Program:
x=5
y=5
print(“x+y=”,x+y)
print(“x-y=”,x-y)
print(“x*y=”,x*y)
104
Problem Solving and Python Programming 2020
print(“x/y=”,x/y)
print(“x%y=”,x%y)
print(“x//y=”,x//y)
Output:
x+y=30
x-y=20
x*y=125
x/y=5.0
x%y=0
x//y=5
ii) Comparison (Relational) operators
Comparison operators are used to compare values. It either returns True or False according
to the condition.
== Equality
!= Not equal to
> Greater than
< Less than.
>= Greater than or equal to
<= Less than or equal to
Example Program:
x=10
y=20
print(“x>y=”,x>y)
print(“x<y=”,x<y)
print(“x==y=”,x==y)
print(“x!=y=”,x!=y)
105
Problem Solving and Python Programming 2020
print(“x>=y=”,x>=y)
print(“x<=y=”,x<=y)
Output:
x>y=False
x<y=True
x==y=False
x!=y=True
x>=y=False
x<=y=true
iii) Assignment operators
Assignment operators are used in Python to assign values to variables.
Operator Description
106
Problem Solving and Python Programming 2020
Example Program:
x=True
y=False
print(“x and y=”,x and y)
print(“x or y=”,x or y)
print(“not x=”,not x)
Output:
x and y=False
x or y=True
not x=False
v)Bitwise operators
Bitwise operators are used to perform bit-level operations which makes processing faster.
107
Problem Solving and Python Programming 2020
Example Program:
x=2
y=3
print(“x&y=”,x&y)
Output:
x&y=2
vi) Membership operators
→It evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
and dictionary or not.
→To check particular element is available in the list or not.
→The membership operators are in and not in.
Operator Description
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
vii) Identity operators
They are used to check if two values (or variables) are located on the same part of the
memory.
Operator Description
is True if the operands are identical(refer to the same object)
108
Problem Solving and Python Programming 2020
is not True if the operands are not identical(do not refer to the same
object)
Example:
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y)
print(a is b)
Output:
False
True
3.1.3 Conditional Statements
i)Conditional if
If conditional is a decision making statement. It is always used with condition. It executes
code only if condition is satisfied.
syntax:
if condition:
statements
Flowchart:
False
condition
True
statements
109
Problem Solving and Python Programming 2020
True False
if
condition
110
Problem Solving and Python Programming 2020
111
Problem Solving and Python Programming 2020
default statements
Flowchart:
False
Condition
True
True
False
Statement 1 Condition
True False
Statement 2 Condition
3
True
112
Problem Solving and Python Programming 2020
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
Output:
enter a value:1
enter b value:0
enter c value:0
same and real roots
3.2 ITERATION/CONTROL STATEMENTS/LOOPING STATEMENTS
Iteration means repetition of loop until base condition is false. Repeated execution of set of
statements is called as iteration.
→state
→while
→for
→break
→continue
→pass
3.2.1 State
It is possible to have more than one assignment for the same variable. Reassignment
replaces existing value with new value.
Example Program1:
>>>x=10
>>>y=17
>>>print x
10
>>>x=18
113
Problem Solving and Python Programming 2020
>>>print x
18
Example Program2:
>>>x=10
>>>y=176
>>>x=8
>>>print x
8
3.2.2 While loop
While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
Flowchart:
False
Condition
True
Body of while
statements
114
Problem Solving and Python Programming 2020
115
Problem Solving and Python Programming 2020
Factorial is 125
for in sequence:
The for loop in Python is used to iterate over a sequence (list, tuple, string).. Loop
continues until we reach the last element in the sequence.
Syntax:
for loopvariable in sequence:
Body of for statements
Flowchart:
False
Condition
Body of for
statements
R
for i in "Ramu": A
1. For loop in string
print(i) M
U
for i in [2,3,5,6,9]: 2
2. For loop in list
print(i) 3
116
Problem Solving and Python Programming 2020
5
6
9
2
for i in (2,3,1):
3. For loop in tuple 3
print(i)
1
3.2.4 Break
Break statements can alter the flow of a loop. It terminates the current loop and executes
the remaining statement outside the loop.
Syntax:
i) while loop
while(condition):
if(condition):
break
ii) for loop
for loop variable in sequence:
if(condition):
break
Flowchart:
condition
False
True
Break?
Body of loop
117
Problem Solving and Python Programming 2020
Example Program:
for i in "welcome":
if(i=="c"):
break
print(i)
Output:
w
e
l
3.2.5 Continue
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
i) while loop
while(condition):
if(condition):
continue
ii) for loop
for loopvariable in sequence:
if(condition):
continue
Flowchart:
condition
Continue
Body of loop
118
Problem Solving and Python Programming 2020
Example Program:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
3.2.6 Pass
It is a null statement, nothing happens when it is executed.
Syntax:
pass
Example Program:
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output:
w
e
l
c
o
119
Problem Solving and Python Programming 2020
m
e
1 It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
2 syntax: syntax:
break continue
3 for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
4 w w
e e
l l
o
m
e
Void function:
A function that does not return any value is called void function.
Example 1:
print(“Hello”)
Example 2:
def add():
a=10
b=20
c=a+b
print(c)
add()
3.3.1 Return values
Return statement may or may not send back any value to main program. The return
statement is also used to exit a function and go back to place where it was called, return
keywords are used to return the values from the function.
Syntax:
return(expression)
121
Problem Solving and Python Programming 2020
Types of parameters/arguments:
i) Required/positional parameters
ii) Keyword parameters
iii) Default parameters
iv) Variable length parameters
student( “Aarika”):
a=50
def add():
b=20
c=a+b Global variable
print(c) 70
def sub():
b=30
Local variable
c=a-b
print(c) 20
123
Problem Solving and Python Programming 2020
print(a) 50
124
Problem Solving and Python Programming 2020
else:
return n*fact(n-1)
n=int(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
Output:
enter no. to find fact:5
Fact is 120
3.4 STRINGS
String is defined as sequence of characters represented in quotation marks (either
single quotes ( ‘ ) or double quotes ( “ ). An individual character in a string is accessed using a
index. The index should always be an integer (positive or negative). A index starts from 0 to
n-1. Strings are immutable i.e. the contents of the string cannot be changed after it is created.
String operators/operations:
i) Indexing
ii) Slicing
iii) Concatenation
iv) Repetition
v) Membership
vi)Comparision
i) Indexing
Positive indexing helps in accessing the string from the beginning. Negative subscript helps
in accessing the string from the end.
>>>a=”HELLO HAI”
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>I
ii) Slicing
125
Problem Solving and Python Programming 2020
The slice[start : stop] operator extracts sub string from the strings. A segment of a string
is called a slice.
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO
iii) Concatenation
The + operator joins the text on both sides of the operator.
a=”save”
b=”water”
>>>print(a+b)
savewater
iv) Repetition
The * operator repeats the string on the left hand side times the value on right hand side.
a=”python”
>>>print(3*a)
pythonpythonpython
v) Membership
Using membership operators to check a particular character is in string or not. Returns
true if present
>>> s="good morning"
>>>"m" in s
True
>>> "a" not in s
True
vi)Comparison
The strings can be compared using relational operators.
>>>msg1=”Good”
>>>msg2=”Good”
>>>msg1==msg2
True
126
Problem Solving and Python Programming 2020
3.4.2 Immutability
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
127
Problem Solving and Python Programming 2020
128
Problem Solving and Python Programming 2020
in our code.
→There is large number of standard modules also available in python.
→Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example Program:
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
Output:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
/:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
import array
Syntax to create array:
arrayname = modulename.functionname(‘datatype’,[elements])
Example:
a=array.array(‘i’,[1,2,3,4])
Here,
a- array name
array- module name
i- integer datatype
131
Problem Solving and Python Programming 2020
132
Problem Solving and Python Programming 2020
133
Problem Solving and Python Programming 2020
sum=0
for i in a:
sum=sum+i
print("The total is",sum)
Output:
The total is 35
3.5.5 Linear search
mylist=[11,23,38,40,52,63,78,98,29,45]
print(mylist)
x = int(input("Enter number to search: "))
found=False
for i in range(len(mylist)):
if(mylist[i] == x):
found=True
print ("Element found at position:",i+1)
break
if(found==False):
print "Element not found"
Output:
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 78
(‘Element found at position:’ 7)
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 2
Element not found
3.5.6 .Binary search
def bsearch(list,x):
first = 0
last= len(list)-1
134
Problem Solving and Python Programming 2020
while (first<=last):
midpoint= (first+ last)//2
if x==list[midpoint]:
return midpoint
elif(x<list[midpoint]):
last=midpoint-1
else:
first= midpoint+1
return -1
list=[10,20,30,40,50]
print("Original list is:",list)
x=input("Enter the element to be searched:")
pos=bsearch(list,x)
if(pos!=-1):
print “Element found at the position:”,pos
else:
print “Element not found”
Output:
Original list is:[10,20,30,40,50]
Enter the element to be searched:30
Element found on position:2
Original list is:[10,20,30,40,50]
Enter the element to be searched:60
Element not found
135
Problem Solving and Python Programming 2020
The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
If statement:
The syntax of if statement is:
Syntax:
if
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens.
137
Problem Solving and Python Programming 2020
138
Problem Solving and Python Programming 2020
Example:
def factorial(n):
if n == 1:
139
Problem Solving and Python Programming 2020
return 1
else:
return n * factorial(n-1)
14. Explain global and local scope.
The scope of a variable refers to the places that we can see or access a variable. If we
define a variable on the top of the script or module, the variable is called global variable. The
variables that are defined inside a class or function is called local variable.
Example:
def my_local():
a=10
print(“This is local variable”)
Example:
a=10
def my_global():
print(“This is global variable”)
15. Compare string and string slices.
A string is a sequence of character.
Example:
fruit = ‘banana’
String slices:
A segment of a string is called string slice, selecting a slice is similar to selecting a
character.
Example:
>>> s =' Pythonprogram'
>>> print s[0:5]
pytho
>>> print s[6:12]
progra
140
Problem Solving and Python Programming 2020
Example:
a = “foo”
b=a
a=a+a
print a
print b
Output:
foofoo
foo
It is observed that ‘b’ hasn’t changed even though ‘a’ has changed.
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string
18. What are string methods?
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper()
>>> word = 'lion'
>>> new_word = word.upper()
>>> print new_word
LION
141
Problem Solving and Python Programming 2020
25. Write a program to accept two number,multiply them and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
val1=int(input())
val2=int(input())
prod=val1*val2
print(“product is:”,prod,”\n”)
26. Write a python program to accept two numbers, find the greatest and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
num1=input()
num2=input()
number1=int(num1)
number2=int(num2)
if number1>number2:
Largest=number1
else:
Largest=number2
print(“largest number is:”,largest)
27. Present the flow of execution for a while statement. (JANUARY 2019)
While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
28. Define recursion with example. (JANUARY 2019)
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
143
Problem Solving and Python Programming 2020
29. Do loop statements have else clause? When will it be executed? (JANUARY 2020)
Yes. Loop’s else part runs if no break occurs and the condition is false
30. Write a program to display a set of strings using range () function. (JANUARY 2020)
144
Problem Solving and Python Programming 2020
145
Problem Solving and Python Programming 2020
see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
i)Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with
the given lengths. (4)
ii)Write a function that prompts the user to input three stick lengths, converts them to
integers, and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii)Write a python program to generate all permutations of a given string using built-in
functions. (8) (JANUARY 2020)
19.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10) (JANUARY 2020)
146
Problem Solving and Python Programming 2020
1. Write a python program to design simple calculator performing arithmetic functions like
addition, subtraction, multiplication and division with the input given by user.
2. Create a program for linear search using Arrays
3. Illustrate a program to find GCD of m and n.
4. How to find the square root of a number using newton’s method
5. Write a python program to sum an array of numbers
6. Write a python program for student mark system.
7. Write a python program greatest of three numbers.
147
Problem Solving and Python Programming 2020
Additional Programs
1. Positive or negative number
n=eval(input("enter a number:"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output:
enter a number:88
positive number
2. Leap year or not
y=eval(input("enter a yaer:"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output:
enter a year:2004
leap year
3. Greatest of three numbers
a=eval(input(“enter the value of a:”))
b=eval(input(“enter the value of b:”))
c=eval(input(“enter the value of c:”))
if(a>b):
if(a>c):
print(“The greatest number is”,a)
else:
print(“The greatest number is”,c)
else:
if(b>c):
148
Problem Solving and Python Programming 2020
149
Problem Solving and Python Programming 2020
print(sum)
output
Enter the value of n :
10
55
6. Print no’s divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Output:
enter a:30
5
15
25
150
Problem Solving and Python Programming 2020
CHAPTER 4
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, mergesort, histogram.
151
Problem Solving and Python Programming 2020
152
Problem Solving and Python Programming 2020
4.1 LIST
List contain elements of various data types, the list is enclosed by square brackets where
elements are separated by commas. The values in a list are called elements or items. A list within
another list is called nested list.
→ List values can be accessed using slice operator ([] or [:])
→ list[0] represents beginning of list
→ list[-1] represents ending of list
Syntax:
listname=[value1,value2,…value n]
Example :
>>>mylist = [10,10.5, ‘programming’]
Example program for creating lists:
list1 = [‘Rama’, ‘Delhi’, 2018]
list2 = [10, 20, 30, 40, 50]
list3 = []
list4 = [‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
print list1
print list2, list3
print list4
Output:
[‘Rama’, ‘Delhi’, 2018]
[10, 20, 30, 40, 50] [ ]
[‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
Creating list:
i) The simplest way to create a list is enclose the elements in square brackets([])
nlist =[10,20,30,40]
slist =[“Hai”, “Python”]
ii) A list that contains no element is called an empty list. It can be created with empty brackets [].
elist = []
153
Problem Solving and Python Programming 2020
154
Problem Solving and Python Programming 2020
iv) Membership
i) Concatenation
The list can be concatenated by using ‘+’ operator.
Example:
>>>a = [1,2,3]
>>>b =[4,5,6]
>>>c =a+b
>>>c
[1,2,3,4,5,6]
ii) Repetition
The list can be repeated by using * operator.
Example:
>>>a =[1,2,3]
>>>a*2
[1,2,3, 1,2,3]
>>>[1]*5
[1,1,1,1,1]
iii) Indexing
The list elements can be accessed by using index operator ([]).
Example:
>>>a =[1,2,3]
>>>a[0]
1
>>>a[1]
2
>>>a[2]
3
>>>a[-1]
3
155
Problem Solving and Python Programming 2020
iv) Membership
There are 2 membership operators in python programming.
i) in - Returns true if value is in list, returns false if value is not in list.
ii) not in - Returns true if value is not in list, returns false if value is in list.
Example:
>>>a= [1,2,3]
>>>1 in a
True
>>>4 in a
False
>>>3 not in a
False
4.1.2 List slices
A segment of list is called as list slice. The list elements can be accessed using the slice
operator ([]). Slice operator [n:m] returns a part of list from nth element to mth element ,
including first and excluding last.
If the first index is omitted, the slice starts at the beginning of the string. If the second
index is omitted, the slice goes to the end of the string. If the first index is greater than or equal
to the second, the slice is an empty string. If both indices are omitted, the slice is a given string
itself.
Syntax:
listname [start: finish -1]
Example:
>>>mylist=[‘Python’,10,10.5,’program’]
>>>mylist[0]
‘Python’
>>>mylist[1]
10
>>>mylist[2]
10.5
156
Problem Solving and Python Programming 2020
>>>mylist[3]
‘program’
>>>mylist[0:3]
[‘Python’,10,10.5]
>>>mylist[1:3]
[10, 10.5]
>>>mylist[:3]
[‘Python’,10,10.5]
>>>mylist[:]
[‘Python’,10,10.5,’program’]
>>>mylist[1:]
[10,10.5,’program’]
mylist
python 10 10.5 program
0 1 2 3
mylist[0] -> element in 0th position.
mylist[-1] -> element in ending of list
mylist[0:3] -> Starting from 0th position to 2nd position
mylist[1:] -> ending position is not given , so 1st position to ending of list
mylist[:] -> beginning to ending of list.
4.1.3 List methods
Python provides a set of list methods. They are
i) append()
ii) extend()
iii) sort()
iv) reverse()
v) pop()
vi) clear()
vii) index()
viii) count()
157
Problem Solving and Python Programming 2020
ix) insert()
x) remove()
xi) copy()
i) append()
Adds element to the end of specified list and does not return any value.
>>>a =[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]
ii) extend()
This method add all elements of list to another list.
>>>a= [1,2,3]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()
This method sorts elements in list.
>>>a= [3,1,2]
>>>a.sort()
>>>a
[1,2,3]
iv) reverse()
This method reverse the elements in a list.
>>>a =[1,2,3]
>>>a.reverse()
>>>a
[3,2,1]
158
Problem Solving and Python Programming 2020
v) pop()
This method removes and returns an element at the given index. If the index is not given,
it removes and returns the last element on the list.
Example:
list=[“eng”,”chem”,”python”,”maths”]
>>>list.pop(2)
python
>>>list
[“eng”,”chem”,”maths”]
>>>list.pop()
[“eng”,”chem,’python”]
vi) clear()
This method clear elements in a list.
>>>a= [1,2,3]
>>>a.clear()
>>>print(a)
[]
vii) index()
This method returns index of given element. If the element is not in the list it returns
error.
>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()
It counts how many times the elements occur in the list.
>>>a= [1,2,3,2,2,1,3]
>>>a.count(3)
2
Syntax:
listname.count(value)
159
Problem Solving and Python Programming 2020
ix) insert()
It inserts an element on a desired position of a list.
Syntax:
listname.insert(index,element)
>>>a=[1,2,3]
>>>a.insert(1,4)
>>>a
[1,4,2,3]
x) remove()
It removes the specified element from the list.
>>>a=[1,2,3]
>>>a.remove(2)
>>>print(a)
[1,3]
xi) copy()
It copies one list to another list.
>>>a =[1,2,3]
>>>b=a.copy()
>>>b
[1,2,3]
Syntax:
listname.copy()
List functions:
i) len()
ii) max()
iii) min()
iv) cmp()
v) sum()
vi) sorted()
i) len() : Returns the number of elements in a list.
160
Problem Solving and Python Programming 2020
>>>a= [1,2,3,4]
>>>len(a)
4
ii) max(): Returns maximum value from the list .
>>>a= [1,2,3,4]
>>>max(a)
4
iii) min(): Returns minimum value from list.
>>>a= [1,2,3,4]
>>>min(a)
1
iv) cmp(): Compares the elements of lists.
>>>list1 = [123, 'xyz']
>>>list2 = [456, 'abc']
>>>print cmp(list1, list2)
-1
>>>print cmp(list2, list1)
1
>>>list3 = list2 + [786];
>>>print cmp(list2, list3)
-1
v) sum(): It returns the sum of all elements in a list.
>>>a= [5,10,15,5,4]
>>>sum(a)
39
vi) sorted(): Returns the sorted list of elements in ascending order.
>>>a= [4,3,2,1]
>>>sorted(a)
[1,2,3,4]
161
Problem Solving and Python Programming 2020
162
Problem Solving and Python Programming 2020
data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
>>>data[1][1]
0
>>>data[2][2]
0
>>>data[1][1]
8
>>>data[2][2]
7
>>>data[1][1]
8
>>>data[2][2]
7
>>>data
[0,0,0],[0,8,0],[0,0,0],[0,0,0],[0,0,0]
4.1.6 List aliasing
List aliasing is defined as circumstance where two (or) more variables refer to the same object.
Example:
>>>a=[1,2,3]
>>>b=a
>>>b is a
True
>>>b is not a
False
In this example, a is assigned to b then both variables refers to same objects.
a
[1,2,3]
b
163
Problem Solving and Python Programming 2020
Here, the same list has two different names (‘a’ and ‘b’).so it is aliased.
If the aliased object is mutable, modifications done in one object affect the other object also.
Aliasing with mutable object:
Lists are mutable (changeable)
Example:
>>>a=[1,2,3]
` >>>b=a
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=10
>>>a
[10,2,3]
>>>b
[10,2,3]
4.1.7 Cloning list
Assignment statements in Python do not copy objects. They simply create bindings between
two objects. For mutable sequences (like lists), a copy of an existing object may be required so
that one object can be changed without affecting another. In lists, cloning operation can be used
to create a copy of an existing list so that changes made in one copy of list will not affect
another. The copy contains the same elements as the original. This can be done using
i) list() function
ii) copy() function
iii) copy.deepcopy() function
i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)
164
Problem Solving and Python Programming 2020
Example:
>>>a= [1,2,3]
>>>b= list(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=4
>>>a
[4,2,3]
>>>b
[1,2,3]
ii) copy() function
copy.copy() is little slower than list() since it has to determine data type of old list first.
Syntax:
newlistname= copy.copy(oldlistname)
Example:
>>>import copy
>>>a= [1,2,3]
>>>b= copy.copy(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
iii) copy.deepcopy() function
copy.deepcopy() is the slowest and memory-consuming method.
Syntax :
newlistname = copy.deepcopy(Oldlistname)
Example Program1:
import copy
165
Problem Solving and Python Programming 2020
166
Problem Solving and Python Programming 2020
Here list passed as parameter to function (circulate), this list is circulated based on value the
value.
4.1.10 Deleting list elements
To remove a list element, del operator can be used if an element to be deleted is known.
In the following code, the element ‘Chennai’ is deleted by mentioning its index in the del
operator.
Example Program:
stulist = [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
Now the list is : [‘Rama’, 2018, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
4.2 TUPLES
Tuple is a collection sequence of values of different types. Unlike lists, tuple values are
indexed by integers. The important difference is that tuples are immutable. Tuples are created
using parenthesis (). The important points to be noted are
i) The values in tuples can be any type and they are indexed by integers
ii) A type is a comma-seperated list of values.
Example:
>>>t=’a’,’b’,’c’,’d’,’e’
Creation of tuples:
i) Create a tuple with a single element.
>>>t1= ‘a’
>>>type(t1)
<class ‘tuple’>
>>>t2=(‘a’)
>>>type(t2)
167
Problem Solving and Python Programming 2020
<class ‘str’>
ii) A tuple can be created using the built-in function tuple. It can create an empty tuple
with no argument.
>>>t= tuple()
>>>t
()
iii) A tuple built-in- functions can be used to create a tuple with sequence of arguments.
>>>t= tuple(‘computer’)
>>>t
(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Operators on tuple:
i) Bracket operator
ii) Slice operator
iii) Relational operator
i) Bracket operator
Bracket operator indexes an element.
>>>t= (‘c’,’o’,’m’,’p’)
>>>t[0]
‘c’
>>>t[3]
‘p’
ii) Slice operator
Slice operator selects a range of elements.
>>>t[0:3]
(‘c’,’o’,’m’)
iii) Relational operator
→The relational operators work with tuples and other sequences.
→Python starts by comparing the first element from each sequence.
→If they are equal, it goes on to the next elements and so on, until it finds elements that
differ.
168
Problem Solving and Python Programming 2020
169
Problem Solving and Python Programming 2020
→The right side can be any kind of sequence (string, list or tuple).
Example:
To split an email address into a username and a domain consider the following
>>>addr=’[email protected]’
>>>uname,domain= addr.split(‘@’)
Here split is a keyword, the return value from split is a list with two elements and the first
element is assigned to username, the second to domain
>>>uname
‘effie’
>>>domain
‘python.org’
4.2.2 Tuples as return values
A function can return only one value, but if the value is a tuple, it can return multiple
values. The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and the remainder. Here the type of returning a values are
i)It can store the result as a tuple.
>>>t= divmod(13,4)
>>>t
(3,1)
ii) To store the elements separately, use tuple assignment.
>>>Q,R= divmod(13,4)
>>>Q
3
>>>R
1
iii) A function can return a tuple. The built-in function def minmax(t) is used to find the
largest and smallest elements of a sequence and can return a tuple of two values.
def minmax(t):
return min(t),max(t)
170
Problem Solving and Python Programming 2020
→max and min are built-in functions that find the largest and smallest elements of the
sequence.
→minmax computes both the largest and smallest elements and returns a tuple of two
values.
Example Program:
>>>def minmax(t):
return min(t), max(t)
>>>minmax([6,3,7,12])
(3,12)
>>>minmax(‘abcd’)
(‘a’,’d’)
4.2.3 Accessing values
To access the tuple elements slicing (bracket operator [ ]) operator along with index or
indices is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
t2 = (1, 2, 3, 4, 5, 6, 7 );
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print “tup1[0]: “, tup1[0]
print “tup1[1]: “, tup1[1]
print “tup2[1:5]: “, tup2[1:5]
print “tup2[1:]: “, tup2[1:]
print t[0]
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a
171
Problem Solving and Python Programming 2020
172
Problem Solving and Python Programming 2020
Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is
replaced by ‘A’.
4.2.6 Built-in functions with tuple
The built-in functions with tuples are given below.
i) all(): Return True if all elements of the tuple are true (or if the tuple is empty).
ii) any():Return True if any element of the tuple is true. If the tuple is empty, return False.
iii) enumerate():Return an enumerate object. It contains the index and value of all the items of
tuple as pairs.
iv) len():Return the length (the number of items) in the tuple.
v) max():Return the largest item in the tuple.
vi) min():Return the smallest item in the tuple
vii) sorted():Take elements in the tuple and return a new sorted list (does not sort the tuple
itself).
viii) sum():Return the sum of all elements in the tuple.
4.2.7 Comparing tuples
With relational operators it is possible to work with tuples and other sequences. To
compare two elements, Python starts by comparing the first element from each sequence. If the
elements are equal, it goes on to the next elements, and so on, until it finds an element that is
different, subsequent elements are not considered (even if they are really big)
>>> (0, 1, 2) < (0, 3, 4)
True
4.3 Dictionaries
Dictionary is a collection that shows values along with key,the sequence of such key and
value pair is separated by commas, these pairs are sometimes called entries or items,all the
entries are enclosed by {}.A colon seperates key and its values.
→ Dictionaries in Python are implemented using hash table. It is an array whose indexes
are obtained using a hash function on the keys.
173
Problem Solving and Python Programming 2020
174
Problem Solving and Python Programming 2020
i) dict()
ii) dict(s)
iii) len()
iv) max()
v) min()
vi) all()
vii) sorted()
viii) any()
ix) pop()
x) copy()
xi) key()
xii) values()
xiii) update()
xiv) clear()
i) dict() : It creates a new, empty dictionary.
>>>cse=dict()
>>>cse
{}
ii) dict(s): It creates a new dictionary with key-value.
>>>cse=dict(s)
iii) len(): It counts the number of key value pairs.
>>>cse={‘name’:’ABC’,’age’:20}
>>>len(cse)
2
iv) max(): It returns the maximum key in dictionary.
>>>max(xse)
2
v) min(): It returns the minimum key in dictionary.
>>>min(cse)
1
175
Problem Solving and Python Programming 2020
176
Problem Solving and Python Programming 2020
177
Problem Solving and Python Programming 2020
value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value. There is no direct
method to handle reverse lookup. The following function takes a value and returns the first key
that map to that value.
Example Program:
def getvalue(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print getvalue(squares,4)
Output:
2
4.3.6 Inverting a dictionary
A dictionary can be inverted with list values. For example, if you were given a dictionary
that maps from child to parent, you might want to invert it; that is, create a dictionary that maps
from parent to children. Since there might be several children with the same parent each value in
the inverted dictionary should be a list of children.
Example Program:
def invertdict(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = { ‘child1’: ‘A1’,
‘child2’: ‘A1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}
178
Problem Solving and Python Programming 2020
print invertdict(d)
Output:
{‘parent2’: [‘child3’, ‘child4’], ‘A1’: [‘child1’, ‘child2’]}
4.4 ADVANCED LIST PROCESSING
.The list comprehension is the advanced list processing is given below.
4.4.1 List comprehensions
List comprehension is an elegant and concise way to create new list from existing list in
python. List comprehension process is described by series of keywords.
Syntax:
[expression for item in list if conditional]
newlist is the resultant list. expression (i) is based on the variable used for each element in the
old list. If needed filter can be applied using if statement.
A list comprehension consists of the following parts:
i) An input sequence.
ii) Variable representing members of the input sequence.
iii) An optional predicate expression.
iv) An Output expression producing elements of the output list from members of the
input sequence that satisfy the predicate.
Example Program1:
>>>a=[11,22,33,44]
>>>b=[x*2 for x in a]
>>>b
[22,44,66,88]
179
Problem Solving and Python Programming 2020
Example Program2:
>>>names=[‘alice’,’bob’,’charly’]
>>>b=[ x.upper() for x in names]
[‘ALICE’,’BOB,’CHARLY]
>>>c=[x.capitalize() for x in names]
>>>c
[‘Alice’,’Bob’,’Charly’]
Example Program3:
>>>vowels=(‘a’,’e’,’i’,’o,’u’)
>>>t=’hello’
>>>[c for c in t if c in vowels]
[‘e’,’o’]
Example Program4:
>>>a=[1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
Example Program5:
>>>a= [10,5,0,-5,-10]
>>>[x for x in a if x>0]
[10,5]
>>>[x for x in a if x<0]
[-5,-10]
180
Problem Solving and Python Programming 2020
a[position]=a[position-1]
position=position-1
a[position]=currentvalue
list=[50,60,40,30,20,70]
print( “Original list is:”,list)
insertionsort(list)
print(”List after insert:”,a)
Output:
Original list is: =[50,60,40,30,20,70]
List after insert:[20,30.40,50,60,70]
181
Problem Solving and Python Programming 2020
left=a[:mid]
right=a[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1
list=[50,60,40,20,70,100]
print ("Original list is:" ,list)
mergesort(list)
print ("Sorted list is:",list)
Output:
Original list is: [50, 60, 40, 20, 70, 100]
182
Problem Solving and Python Programming 2020
183
Problem Solving and Python Programming 2020
184
Problem Solving and Python Programming 2020
185
Problem Solving and Python Programming 2020
186
Problem Solving and Python Programming 2020
187
Problem Solving and Python Programming 2020
188
Problem Solving and Python Programming 2020
29. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (JANUARY 2019)
def reverse_lookup(d,v):
for k in d:
if d[k]==v:
return k
raise Value Error
30. How will you update list items? Give one example. (JANUARY 2020)
List will be updated using index value.
Example:
>>>a=[1,2,3]
>>>a[0]=10
>>> print(a)
[10,2,3]
31. Can function return tuples? If yes give example. (JANUARY 2020)
Yes function return tuples.
Example:
def add(a,b)
return(a+b)
add(3,2)
189
Problem Solving and Python Programming 2020
190
Problem Solving and Python Programming 2020
191
Problem Solving and Python Programming 2020
Additional Programs
1. Python program to find the largest number in a list.
a=[]
n=int(input("Enter the number :"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Output:
Enter the number :3
Enter element:33
Enter element:569
Enter element:73
Largest element is: 569
2. Python program to put even and odd elements in a list into two different lists.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
192
Problem Solving and Python Programming 2020
Output:
Enter number of elements:5
Enter element:69
Enter element:45
Enter element:46
Enter element:28
Enter element:457
The even list [46, 28]
The odd list [69, 45, 457]
3. Python program to remove the duplicate items from a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Output:
Enter the number of elements in list:5
Enter element1:100
Enter element2:100
Enter element3:220
Enter element4:220
Enter element5:220
193
Problem Solving and Python Programming 2020
Non-duplicate items:
[100, 220]
4. Python program to add a key-value pair to the dictionary.
key=int(input("Enter the key (int) to be added:"))
d={}
d.update({key:value})
print(d)
Output:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
5. Python program to concatenate two dictionaries in to one.
d1={'A':1,'B':2}
d2={'D':3}
d1.update(d2)
print(d1)
Output:
Case 1:
Concatenated dictionary is:
{'A': 1, 'D': 3, 'B': 2}
6. Python program to check if a given key exists in a dictionary or not.
d={'A':1,'B':2,'C':3}
194
Problem Solving and Python Programming 2020
if key in d.keys():
print(d[key])
else:
Output:
Enter key to check: A
Key is present and value of the key is:
1
7. Python program to sum all the items in a dictionary.
d={'A':100,'B':540,'C':239}
print(sum(d.values()))
Output:
Total sum of values in the dictionary:
879
8. Python program to multiply all the items in a dictionary.
d={'A':100,'B':100,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Output:
2390000
9. Python program to remove the given key from a dictionary.
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
195
Problem Solving and Python Programming 2020
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Output:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
10. Python program to count the frequency of words appearing in a string using a
dictionary.
test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
Enter string: hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}
196
Problem Solving and Python Programming 2020
CHAPTER 5
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count, copy file.
197
Problem Solving and Python Programming 2020
198
Problem Solving and Python Programming 2020
access mode→ The access mode denotes the mode in which the file has to be opened (read,
199
Problem Solving and Python Programming 2020
Opens a file for appending in binary format. The file pointer is at the end
ab
of the file if the file exists. If the file does not exist, it creates a new file
200
Problem Solving and Python Programming 2020
for writing.
Opens a file for both appending and reading. The file pointer is at the end
a+ of the file if the file exists. If the file does not exist, it creates a new file
for reading and writing.
Opens a file for both appending and reading in binary format. The file
ab+ pointer is at the end of the file if the file exists. If the file does not exist, it
creates a new file for reading and writing.
Attribute Description
Returns true if the file is closed, otherwise
file.closed
false.
Returns the file access mode with which file
file.mode
was opened.
file.name Returns name of the file.
ii) Reading and writing files
Python provides read () and write () methods to read and write files through file object
respectively.
Reading files:
The read() method read the file contents, from opened file. To read the content of file, the
file must be opened in read mode (r).There are 4 methods for reading files.
i ) Reading a file using read(size) method
ii) Reading a file using for loop
iii) Reading a file using readline() method
iv) Reading a file using readlines() method
The file test.txt contains
problem solving and python programming.
Introduction to python
i) Reading a file using read(size) method
201
Problem Solving and Python Programming 2020
The read(size) method is used to read in size number of data.If the size parameter is not
specified, it reads and returns up to the end of file.
Syntax:
fileobject . read([size])
Example:
f=open(“test.txt”, “r+”)
S=f.read(15);
print(“Read string is:”,S)
f.close()
Output:
Read string is: problem solving
ii) Reading a file using for loop
A file can be read using for loop. This method is efficient and fast.
Syntax:
for loopvariable in fileobject:
print(loopvariable)
Example Program:
f=open(“test.txt”, “r+”)
for i in f:
print(i)
f.close()
Output:
Problem solving and python programming
Introduction to python
iii) Reading a file using readline() method
The readline() method is used to read individual line of a file. It reads a file till the
newline(\n) character is reached (or) end of file is reached.
Syntax:
fileobject . readline()
Example Program:
202
Problem Solving and Python Programming 2020
f=open(“test.txt”, “r+”)
f.readline()
f.close()
Output:
Problem solving and python programming
iv) Reading a file using readlines() method
The readlines() method is used to read all the lines of file at a time.
Syntax:
fileobject.readlines()
Example Program:
f=open(“test.txt”, “r+”)
f.readlines()
f.close()
Output:
Problem solving and python programming
Introduction to python
Writing files:
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
a-appending mode
x-exclusive creation
The ‘w’ mode will overwrite into the file if already exists. So all previous data’s are erased.
Syntax:
fileobject . write(string)
Example Program:
f=open(“test.txt”, “r+”)
f.write(“Welcome to python”)
f.close()
iii) Closing the file
203
Problem Solving and Python Programming 2020
The function close() of a file object flushes if there is any unwritten information and
closes the file object when there is no more writing can be done. Python closes a file
automatically when the reference object of a file is reassigned with another file. The syntax of
close () function is given below.
Syntax:
fileobject.close()
Example Program:
f1=open(“test.txt”,”w”)
print(“Name of file is:”,f1.name)
print(“closed or not:”,f1.closed)
print(“opening mode is:”,f1.mode)
f1.close()
Output:
Name of file is:test.txt
closed or not:False
opening mode is:w
5.1.3 Format Operator
write() function takes the argument as a string . To put other values in a file, it must be
converted to strings. It is done by 2 methods:
i) str() method is used to convert other values into string.
Example Program:
>>>x=52
>>>f.write(str(x))
52
ii) Format operator is an % operator that converts other values into string.
with integers, % is considered as modulus operator
with strings,% is considered as format operator
Example Program:
>>>x=15
204
Problem Solving and Python Programming 2020
>>>”%d”%x
15
%d is formatted as decimal integer.
Format sequence in string:
Format sequence can appear anywhere in the string
Example Program:
>>>computers=10
>>>’I have bought %d computers’, %computers
Output:
I have bought 10 computers
More than one format sequence:
If there is more than one format sequence, second argument must be tuple.
Example Program:
>>>”In %d years, I have bought %g%s”.%(2,3.0,’computers’)
In 2 years, I have bought 3.0 computers
In the above program:
→%d is formatted to integer
→%g is formatted to floating point number
→%s is formatted to string.
→Number of elements in tuple and number of format sequences must be same.
5.2 COMMAND LINE ARGUMENTS
Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our script other languages.
Command line argument in python can be processed by using two modules.
i) sys module
ii) argparse module
i) sys module
Sys module is used to access the command line arguments through sys.argv. The sys
module is used for two purposes.
i) sys.argv is a list in Python, which contains the command line arguments passed to the script.
205
Problem Solving and Python Programming 2020
206
Problem Solving and Python Programming 2020
Errors
207
Problem Solving and Python Programming 2020
208
Problem Solving and Python Programming 2020
209
Problem Solving and Python Programming 2020
print (10/0)
ZeroDivisionError: integer division or modulo by zero
Exceptions come in different types, and the type is printed as part of the message: the
type in the example is ZeroDivisionError which occurs due to division by 0. The string printed as
the exception type is the name of the built-in exception that occurred. Exception refers to
unexpected condition in a program. The unusual conditions could be faults, causing an error
which in turn causes the program to fail. The error handling mechanism is referred to as
exception handling. Many programming languages like C++, PHP, Java, Python, and many
others have built-in support for exception handling.
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 stops the current process and
passes the control to corresponding exception handler. If not handled, our program will crash.
Some of the standard exceptions available in Python are listed below.
Exception Name Description
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
OverflowError Raised when a calculation exceeds maximum limit for
a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place
for all numeric types.
AssertionError Raised in case of failure of the Assert statement
EOFError Raised when there is no input from either the
raw_input() or input() function and the end of file is
reached.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence
KeyError Raised when the specified key is not found in the
dictionary.
210
Problem Solving and Python Programming 2020
211
Problem Solving and Python Programming 2020
Syntax:
try:
statements
----------------
-----------------
Except exception1:
Except exception2:
ii) If no exception occurs, the except block is skipped and execution of the try statement
is finished.
iii) If an exception1 occurs rest of try block is skipped, except block1 gets executed.
iv) If an exception2 occurs rest of try block is skipped, except block2 gets executed.
A simple example to handle divide by zero error is as follows.
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”
Output:
divide by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to
see if the exception type matches. If none of the except clauses match, the exception will be
considered unhandled, and your program will crash.
212
Problem Solving and Python Programming 2020
Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
Output (successful):
Please enter the dividend: 12
Please enter the divisor: 2
12 / 2 = 6.000000
Output (unsuccessful-divide by zero error):
Please enter the dividend: 100
Please enter the divisor: 0
The dividend may not be zero!
213
Problem Solving and Python Programming 2020
214
Problem Solving and Python Programming 2020
Example:
try:
raise NameError
except NameError:
print(‘Error’)
Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as re-raise. If no expressions are present, raise re-raises the
last exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise
Output:
Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(‘Hi’)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
5.4.2 The else and finally statements
Two clauses that can be added optionally to try-except block are else and finally. else
will be executed only if the try clause doesn’t raise an exception.
try:
age = int(input(“Please enter your age: “))
except ValueError:
215
Problem Solving and Python Programming 2020
5. 5 MODULES
Module is a file containing Python definitions and statements. Modules are imported from
other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found, “module not found” will be displayed.
216
Problem Solving and Python Programming 2020
Modules
217
Problem Solving and Python Programming 2020
>>>math . factorial(4)
24
iii) datetime
This module is used to calculate date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
5.5.2 User Defined modules
To create module,write one or more functions in file, then save it with .py extentions.
i) Create a file
def add(a,b):
c=a+b
return c
ii) Save it as sum.py
iii) Import module
>>>import sum
>>>print sum.add(10,20)
5.6 PACKAGES
When we have a large number of Python modules, they can be organized into
packages such that similar modules are placed in one package and different modules are placed
in different packages. A package is a tree like hierarchical file directory structure that consists of
modules, sub-packages, sub-sub packages, and so on. In another words, it is a collection of
modules. When a package is imported, Python explores in list of directories on sys.path for the
package subdirectory.
Example:
Assume we are creating a package named Animals with some sub packages as shown in
following.
218
Problem Solving and Python Programming 2020
Animals
(Package)
_init_.py _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
219
Problem Solving and Python Programming 2020
Syntax:
import Animals.Birds.display
Now if this display.py module contains a function named displayByName(), we must use
the following statement with full name to reference it.
Syntax:
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
Syntax:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
Syntax:
display.displayByName()
5.7 ILLUSTRATIVE PROGRAMS
5.7.1 Word count
This Program counts the number of words present in a given file.
try:
InFile=open(“test.txt”,’r’)
except IOError:
print “Error:File Not Found”
else:
data=inFile.read()
words=data.split()
print(words)
print “Total number of words are:”,len(words)
Output:
test.txt
I am enjoying python program
[‘I’, ‘am’, ‘enjoying’,’python’,’program’]
Total number of words are:5
220
Problem Solving and Python Programming 2020
221
Problem Solving and Python Programming 2020
1. Define file.
File is the named location on the system which stores data, information or commands for later
access. It stores the information permanently.
2. Define Text File.
Text files are the types of files that store information in the form of readable and printable
characters. They are the persistent storage.
3. What are the basic file operations in python?
→Opening a file
→Writing to a file.
→Reading from a file
→Closing a file.
4. What are the different types of files?
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5. Write the syntax for opening and closing a file.
Opening a file: fileobject.open(“filename”,mode)
Closing a file: fileobject.close()
6. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
f.write("hello world")
f.close()
7. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
8. What are the two arguments taken by the open() function?
222
Problem Solving and Python Programming 2020
The open function takes two arguments: name of the file and the mode of operation.
Example:
f = open("test.txt","w")
9. What is a file object?
A file object allows us to use, access and manipulate all the user accessible files. It
maintains the state about the file it has opened.
i) sys module
ii) argparse module
14. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
For example, dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo
15. Define an error. What are its types?
Errors are mistakes in the program, which are created by fault of the programmer. They
are often referred to as bugs.
Types of errors:
iv) Syntax errors
v) Runtime errors
vi) Logical error
16. Define Debugging.
Debugging is the process of finding and eliminating errors.
17. Define Runtime errors.
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
→Division by Zero
→Access not defined identifier
→Access not defined file
18. What are the error messages that are displayed for the following exceptions?
→Accessing a non-existent list item
→Accessing a key that isn’t in the dictionary
→Trying to open a non-existent file
→IndexError: list index out of range
→KeyError: what
→IOError: [Errno 2] No such file or directory: 'filename'
224
Problem Solving and Python Programming 2020
19. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
20. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
the except branch and then continues.
21. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes
two arguments: the exception type and specific information about the error.
22. What are modules?
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
23. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are
simply directories.
Syntax: from <mypackage> import <modulename>
24. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called __init__.py.
25. Write a python program to count number of lines, words and characters in a text file.
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")
225
Problem Solving and Python Programming 2020
for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
26. Write a python script to display the current date and time. ( JANUARY 2018)
>>>import datetime
>>>datetime.time()
9:15:20
>>>datetime.date()
19/5/2018
27. Write a note on modular design. (JANUARY 2018)
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
• Sys.argv
• argparse
• getopt
31. Write methods to rename and delete files. (JANUARY 2020)
Delete - remove()
Rename – rename()
227
Problem Solving and Python Programming 2020
228
Problem Solving and Python Programming 2020
1. Write a function that copies a file reading and writing up to 50 characters at a time.
2. Write a Python program to handle multiple exceptions.
3. Write a python program to count number of lines, words and characters in a text file.
4. Write a program to illustrate multiple modules.
5. Write a Python program to append the contents of one file to another file.
6. Write a Python program to count the occurrences of a word in a text file.
7. Write a Python program to count the number of blank spaces in a text file.
229
Problem Solving and Python Programming 2020
Additional Programs
230
Problem Solving and Python Programming 2020
231
Problem Solving and Python Programming 2020
Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
Contents of file test.txt:
Appending!!
Contents of file test1.txt (before appending):
Original
Contents of file test1.txt (after appending):
Original Appending!!
5. Python program to count the number of blank spaces in a text file.
fname = input("Enter file name: ")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Contents of file:
he l l o world hello
Output:
Output:
Enter file name: read.txt
Occurrences of blank spaces:5
6. Python program to read a file and capitalize the first letter of every word in the file.
fname = input("Enter file name: ")
with open(fname, 'r') as f:
232
Problem Solving and Python Programming 2020
for line in f:
l=line.title()
print(l)
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
7. Python program to read the contents of a file in reverse order.
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
hello
hello word
233
Problem Solving and Python Programming 2020
234
Problem Solving and Python Programming 2020
ANNA UNIVERSITY
MODEL
QUESTION PAPERS
235
Problem Solving and Python Programming 2020
236
Problem Solving and Python Programming 2020
237
Problem Solving and Python Programming 2020
238
Problem Solving and Python Programming 2020
239
Problem Solving and Python Programming 2020
OR
b. Define recursion. Write a Program for finding factorial of given number. (13)
14. a. Define list. Explain the various techniques to slice the list. (13)
OR
b.i) Define dictionary and its operation in detail.(7)
ii) Explain about the different types of arguments in detail. (6)
15. a .i)Explain in detail about how to read contents from file with example.(6)
ii) Explain in detail about package concepts in python with example. (7)
OR
b. i) Define exception handling? Explain user defined exception handling in detail.(6)
ii) Write a program to count the occurrence of all letters in file. (7)
PART –C (1 x15=15)
16. a. Summarize the difference between algorithm, flowchart and pseudo code.(15)
OR
b. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii)
sum of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple
vii) Compare two tuples viii) printing two tuples of different data types.(15)
240
Problem Solving and Python Programming 2020
1. What is an algorithm?
2. Write a pseudo-code to accept two numbers, add the numbers and print the result.
3. Outline the modes Python interpreter works.
4. State the difference between (I) and (II) operators in Python.
5. Write a Python program to accept two numbers, find the greatest and print the result.
6. What is recursion?
7. What is a list in Python? Give example.
8. Write the syntax for concatenating two lists in Python.
9. What is an exception? Give example.
10. Write the syntax for opening a file in Python for reading only.
242
Problem Solving and Python Programming 2020
1. What is an algorithm?
2. Write an algorithm to accept two numbers, compute the sum and print the result.
3. Name the four types of scalar objects Python has.
4. What is a tuple? How literals of type tuple are written? Give example.
5. Write a Python program to accept two numbers, multiply them and print the result.
6. Write a Python program to accept two numbers, find the greatest and print the result.
7. What is a list? How lists differ from tuples?
8. How to slice a list in Python?
9. Write a Python script to display the current date and time.
10. Write a note on modular design.
11. a) i) Draw a flow chart to accept three distinct numbers, find the greatest and print the result.
(8)
ii) Draw a flow chart to find the sum of the series 1 + 2+ 3+4+5+….+100. (8)
(OR)
b) Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem
with relevant diagrams. (16)
243
Problem Solving and Python Programming 2020
(OR)
b) i) Write the Python program to perform linear search on a list. (8)
ii) Write a Python program to store ‘n’ numbers in a list and sort the list using
selection sort. (8)
15. a) Tabulate the different modes for opening a file and explain the same. (16)
(OR)
b)i) Appraise the use of try block and except block in Python with syntax. (6)
ii) Explain with an example exceptions with arguments in Python. (10)
244
Problem Solving and Python Programming 2020
245
Problem Solving and Python Programming 2020
12. a. i)Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python (8)
(OR)
b.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in functions. (12)
ii)Write a python function to swap the values of two variables (4)
13. a) List the three types of conditional statements and explain them (16)
(OR)
b. i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
14. a.i)Discuss the different options to traverse a list (8)
ii)Demonstrate the working of +,* and slice operators in python (8)
(OR)
b.i)Compare and contrast tuples and list in python (4)
ii)Write a script in python to sort n number using selection sort (12)
15. a.i)Explain the commands used to read and write into a file with examples (8)
ii)Discuss about the use of format operator in file processing (8)
(OR)
b) Describe how exceptions are handled in python with necessary examples (16)
246
Problem Solving and Python Programming 2020
247
Problem Solving and Python Programming 2020
b). i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer.
It was created by the ancient Greek mathematician Eratosthenes. The algorithm to find
all prime numbers less than or equal to a given integer n:
1)Create a list of integers from two to n:2,3,4,….n
2)Start with a counter i set to 2. (i.e)the first prime number
3)Starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4)Find the first number of the list following i. This is the next prime number
5)Set I to the number found in the previous step
6)Repeat steps 3 and 4 until I is greater than n.
7)All the numbers, which are still in the list are prime numbers (10)
12. a.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4)
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
OR
b)i)Write a python program print the maximum among ‘n’ randomly generate ‘d’ numbers
by storing them in a list(10)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6)
13.a.i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not
be able to get the short sticks to meet in the middle. For any three length, there is a simple test to
see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
248
Problem Solving and Python Programming 2020
i)Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with
the given lengths. (4)
ii)Write a function that prompts the user to input three stick lengths, converts them to
integers, and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii)Write a python program to generate all permutations of a given string using built-in
functions. (8)
OR
b.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10)
14.a.i)Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v)Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6)
OR
b.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using merge sort.(8)
15.a.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8)
b.i)How to merge multiple files into a new file using python.(6)
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (10)
249
Problem Solving and Python Programming 2020
REFERENCES
TEXT BOOKS:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist’’, 2nd edition,
Updated for Python 3, Shroff/O’Reilly Publishers, 2016 (http://greenteapress.com/wp/think-
python/)
2. Guido van Rossum and Fred L. Drake Jr, “An Introduction to Python – Revised and
updated for Python 3.2, Network Theory Ltd., 2011.
REFERENCES:
1. Charles Dierbach, “Introduction to Computer Science using Python: A Computational
Problem-Solving Focus, Wiley India Edition, 2013.
2. John V Guttag, “Introduction to Computation and Programming Using Python’’, Revised
and expanded Edition, MIT Press , 2013
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning,
2012.
4. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An Introduction
to Computer Science using Python 3”, Second edition, Pragmatic Programmers,LLC,2013.
5. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in
Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,, 2015.
250