GE8151 - Problem Solving & Python Programming (Ripped From Amazon Kindle Ebooks by Sai Seena)
GE8151 - Problem Solving & Python Programming (Ripped From Amazon Kindle Ebooks by Sai Seena)
GE8151 - Problem Solving & Python Programming (Ripped From Amazon Kindle Ebooks by Sai Seena)
Python Programming
J. Jayalakshmi
M.E. (CSE)
Professor in CSI College of Engineering,
Ketti, Ooty, The Nilgiris
® TM
(i)
Problem Solving and Python
Programming
Semester - I (Common to All Branches)
Published
®
by :
Amit Residency, Office No.1, 412, Shaniwar Peth, Pune - 411030, M.S. INDIA
TM
Printer :
Yogiraj Printers & Binders
S.No. 10/1a, Ghule Industrial Estate, Nanded Village Road,
Tal. : Haveli, Dist. Pune
Price : ` 195 /-
ISBN 978-93-332-1661-6
9 789333 216616 AU 17
The book uses plain, lucid language to explain fundamentals of this subject. The
book provides logical method of explaining various complicated concepts and
stepwise methods to explain the important topics. Each chapter is well supported with
necessary illustrations, practical examples and solved problems. All chapters in this
book are arranged in a proper sequence that permits each topic to build upon earlier
studies. All care has been taken to make students comfortable in understanding the
basic concepts of this subject.
The book not only covers the entire scope of the subject but explains the
philosophy of the subject. This makes the understanding of this subject more clear
and makes it more interesting. The book will be very useful not only to the students
but also to the subject teachers. The students have to omit nothing and possibly have
to cover nothing more.
We wish to express our profound thanks to all those who helped in making this
book a reality. Much needed moral support and encouragement is provided on
numerous occasions by our whole family. We wish to thank the Publisher and the
entire team of Technical Publications who have taken immense pain to get this book
in time with quality printing.
Any suggestion for the improvement of the book will be acknowledged and well
appreciated.
Authors
A.A.Puntambekar
J.JayaLakshmi
Dedicated to God.
(iii)
Syllabus
Problem Solving and Python Programming (GE8151)
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation (pseudo
code, flow chart, programming language), algorithmic problem solving, simple strategies for developing
algorithms (iteration, recursion). Illustrative problems : find minimum in a list, insert a card in a list of
sorted cards, guess an integer number in a range, Towers of Hanoi. (Chapter - 1)
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.
(Chapter - 2)
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. (Chapter - 3)
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. (Chapter - 4)
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. (Chapter - 5)
(iv)
Table of Contents
Unit - I
Unit - II
Unit - III
Unit - IV
Unit - V
Unit - I
Syllabus :
Algorithms, building blocks of algorithms (statements, state, control flow, functions),
notation (pseudo code, flow chart, programming language), algorithmic problem solving,
simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range,
Towers of Hanoi.
Contents
TM
Technical Publications - An up thrust for knowledge
(1 - 1)
Problem Solving and Python Programming 1-2 Algorithmic Problem Solving
1.1 Algorithms
Definition of Algorithm : An algorithm is a finite set of instructions for performing a particular task. The instructions
are nothing but the statements in simple English language.
Example :
Let us take a very simple example of an algorithm which adds the two numbers and store the result in
a third variable.
Step 1 : Start.
Step 4 : Perform the addition of both the numbers and store the result in variable 'c'.
Step 6 : Stop.
Solution :
Expected output :
Area of the Circle
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-3 Algorithmic Problem Solving
Algorithm :
Step 1 : Start
Step 5 : Stop
Solution :
Step 1 : Start
Step 7: Stop
Review Question
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-4 Algorithmic Problem Solving
Then body of an algorithm is written, in which various programming constructs like if, for, while or
some assignment statements may be written.
Algorithmic body consists of basic building blocks such as Simple Statements, Control Flow
Statements and Functions
There are other types of operators such as Boolean operators such as true or false. Logical
operators such as and, or, not. And relational operators such as <, <=, >, >=, =,
The array indices are stored with in square brackets '[' ']'. The index of array usually start at zero.
The multidimensional arrays can also be used in algorithm.
The inputting and outputting can be done using read and write.
For example :
write(“This message will be displayed on console”) ;
read(val) ;
The comment statemement is non executable statement. It provides additional information about
the programming statement. In Python the comment is specified using #
Control flow :
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
1. sequence 2. Selection 3. iteration
Sequence :
All the instructions are executed one after another is called sequence execution. This describes a
sequence of actions that a program carries out one after another, unconditionally.
Execute a list of statements in order.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-5 Algorithmic Problem Solving
Example :
Step 1 : Start
Step 4 : Display c
Step 5 : Stop
Selection :
Selection is the program construct that allows a program to choose between different actions. Choose
at most one action from several alternative conditions.
A selection statement causes the program control to be transferred to a specific part of the program
based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise it will execute the
other part of the program.
Fig. 1.2.1
Step1 : Start
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-6 Algorithmic Problem Solving
Step 5 : else
Step 7 : Stop
Iteration :
In some programs, certain set of statements are executed again and again based upon conditional test.
i.e. executed more than one time. This type of execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1 : Start
Step 6 : go to step 4
Step 7 : Stop
Repetition(loop) may be defined as a smaller program that can be executed several times in a main
program. Repeat a block of statements while a condition is true.
Algorithm for Washing Dishes
Step1 : Stack dishes by sink.
Step 2 : Fill sink with hot soapy water.
Step 6: i=i+1
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-7 Algorithmic Problem Solving
Step 8: Stop
(3) Function
The Function is a programming constructs used for giving a name to a piece of coding. This piece of
code is referred as function body.
When the name of the function is called, the body is executed. Each execution of the body is called
activation of that body.
The function can be called from expression. For example-
total=amount+Calculate(interest);
Syntax of function
<function-name>(<parameter-list>)
Elements of Function
Various elements of Function are -
1. Name for declaration of function
2. Body consisting of local declarations and statements
3. Formal parameters which are the placeholders of actuals
4. Optional result type.
For example : Consider following C code
Review Question
1. Pseudocode
Pseudocode is an artificial and informal language that helps programmers develop algorithms.
Pseudocode is a "text-based" detail (algorithmic) design tool.
The rules of Pseudocode are reasonably straightforward. All statements showing "dependency"
are to be indented. These include while, do, for, if, switch.
For example
Example (1)
If student's age>18
Print "Adult"
else
Print "Not an Adult"
Example (2)
Set sum:=0
Set counter:= 1
While counter <= 10
Input the num
sum:=sum+num
increment counter by 1
print the sum of 10 numbers
2. Flow Chart
Flowcharts are the graphical representation of the algorithms.
The algorithms and flowcharts are the final steps in organizing the solutions.
Using the algorithms and flowcharts the programmers can find out the bugs in the programming
logic and then can go for coding.
Flowcharts can show errors in the logic and set of data can be easily tested using flowcharts.
Flow lines are used to indicate the flow of data. The arrow heads are
important for flowlines. The flowlines are also used to connect the
different blocks in the flowchart.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-9 Algorithmic Problem Solving
The diamond indicates the decision. It has one entrance and two exits.
One exit indicates the true and other indicates the false.
The process module has only one entrance and one exit.
This polygon indicates the loop A indicates the starting of the counter
S indicates the step by which the counter is incremented or
decremented B indicates the ending value of the counter Using the
counter the number of times the looping instruction gets executed.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 10 Algorithmic Problem Solving
Solution :
Example 1.3.2 Convert the algorithm for computing factorial of given number
Solution :
The algorithm for computing factorial of given number is
Read N
Set i and F to 1
While i<=N
F=F * i
Increase the value of i by 1
Display F
End
Example 1.3.3 Draw a flow chart to accept three distinct numbers, find the greatest and print the result.
AU : Jan.-18 Marks 8
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 11 Algorithmic Problem Solving
Solution :
Fig. 1.3.3
Example 1.3.4 Draw flow chart to find the sum of series 1 + 2 + 3 + 4 + 5 ...... + 100.
AU : Jan.-18 Marks 8
Solution :
Fig. 1.3.4
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 12 Algorithmic Problem Solving
3. Programming Languages
Definition : Programming languages are formal languages that have been designed to express
computations.
There are various programming paradigm
1. Imperative or procedural programming
2. Object oriented programming
3. Functional programming
4. Logic programming
Examples of various programming languages based on the above mentioned paradigm is as shown
by following table
Imperative Object Functional Logic
programming oriented programming programming
C Java
PASCAL Python
FORTRAN
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 13 Algorithmic Problem Solving
3. Functional Programming
Computations of functional languages are performed largely through applying functions to
values, i.e., (+ 10 20). This expression is interpreted as 10 + 20. The result 30 will be returned.
For building more complex functions the previously developed functions are used. Thus program
development proceeds by developing simple function development to complex function
development.
Examples of function programming are LISP, Haskell, ML
4. Logic Programming
In this paradigm we express computation in terms of mathematical logic only. It is also called as
rule based programming approach.
Rules are specified in no special order.
The logic paradigm focuses on predicate logic, in which the basic concept is a relation.
Example of Logic programming is Prolog.
Review Questions
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 14 Algorithmic Problem Solving
4. Select the best way to solve the problem from list of alternative solutions : For selecting the best
way to solve the problem, the merits and demerits of each problem must be analysed. The criteria to
evaluate each problem must be predefined.
5. List the instructions using the selected solution : Based on the knowledgebase (created/used in
step 2) the step by step instructions are listed out. Each and every instruction must be understood by
the person or the machine involved in the problem solving process.
6. Evaluate the solution : When the solution is evaluated then - i) Check whether the solution is
correct or not ii) Check whether it satisfies the requirements of the customer or not.
Review Question
1. Iteration
In iteration the control statements such as for loop, do-while loop or while is used. The loop
continues its execution until the terminating condition is reached.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 15 Algorithmic Problem Solving
1. prod = 1;
2. x = n;
3. while (x > 0)
4. {
5. prod = prod*x;
6. x – –;
7. }
8. return(prod);
Such an algorithm is called as an iterative algorithm because it calls explicit repetition of some
process (in our example the process multiplication and decrementing x by 1) until certain condition is
met (for example x > 0).
2. Recursion
Definition : Recursion is a method of solving problems that involves breaking a problem down into smaller and
smaller subproblems until you get to a small enough problem that it can be solved trivially.
Properties of Recursion
There are three important laws of recursion :
1. A recursive algorithm must have a base case.
2. A recursive algorithm must change its state and move toward
the base case.
3. A recursive algorithm must call itself, recursively
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 16 Algorithmic Problem Solving
2. The iterative functions are implemented Instead of making use of for, while, do-
with the help of for, while, do-while while the repetition in code execution is
programming constructs. obtained by calling the same function
again and again over some condition.
3. The iterative methods are more efficient The recursive methods are less efficient.
because of better execution speed.
4. Memory utilization by iteration is less. Memory utilization is more in recursive
functions.
5. It is simple to implement. Recursive methods are complex to
implement.
6. The lines of code is more when we use Recursive methods bring compactness in
iteration. the program.
Review Question
Algorithm FindMin
{
Problem Description : Finding the minimum element in a list
Input : A list of elements in an array A[start…end]
Output : minimum element
min<- start
for i from start+1 to end do
if A[i]<A[min] then
min<-i
end if
end for
}
Write(“The minimum element is present at position “+min)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 17 Algorithmic Problem Solving
1 3 4 5 6
Step 1 : Traverse the cards from first card to last card. Find the cards having value grater than keycard
Shift those cards one position ahead.
Algorithm InsertCard
{
Problem Description : Inserting a card at appropriate position in the list of already sorted list
Input: A list of elements in an cards A[start…end]
Output: Sorted List A
#Traverse the cards from 1 to length(A)
for i in range 1 to len(A)
#The card to be placed is called keyCard
#Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j=i-1
while j >=0 and keyCard < A[j] :
A[j+1] = A[j]
j = j-1
A[j+1] = keyCard
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 18 Algorithmic Problem Solving
Fig. 1.6.3
3. Guess an integer number in a range Flowchart
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 19 Algorithmic Problem Solving
4. Towers of Hanoi
Problem Statement : The problem of “ Towers of Hanoi” states that move the five disks from
peg A to peg C using peg B as a auxillary.
There are three pegs named as A, B and C. The five disks of different diameters are placed on peg
A. The arrangement of the disks is such that every smaller disk is placed on the larger disk.
The conditions are :
i) Only the top disk on any peg may be moved to any other peg.
ii) A larger disk should never rest on the smaller one.
The above problem is the classic example of recursion. The solution to this problem is very simple.
The initial setup is as shown in Fig. 1.6.4
Fig. 1.6.4
First of all let us number out the disks for our comfort
Fig. 1.6.5
The solution can be stated as
1. Move top n–1 disks from A to B using C as auxillary.
2. Move the remaining disks from A to C.
3. Move the n–1 disks from B to C using A as auxillary.
We can convert it as follows
move disk 1 from A to B.
move disk 2 from A to C.
move disk 1 from B to C. Fig. 1.6.6
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 20 Algorithmic Problem Solving
Fig. 1.6.9
Thus actually we have moved n–1 disks from peg A to C. In the same way we can move the
remaining disk from A to C.
This is a problem in which recursion is used. Flow Chart :
Algorithm TowerofHanoi
{
Write(“\n\n Enter the total number of disks”);
Read(n);
towers(n,’A’,’C’,’B’);
}
Subroutine towers(n,fr,to,aux)
{
#if only one disk has to be moved
if n==1
{
Write(from,to);
return;
}
#move top n-1 disks from A to B using C
towers(n-1,from,aux,to);
Write(from,to);
# move remaining disk from B to C using A
towers(n-1,aux,to,fr);
}
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 21 Algorithmic Problem Solving
Review Question
1. Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem with relevant
diagrams. AU : Jan-18, Marks 16
Ans. : An algorithm is a finite set of instructions for performing a particular task. The instructions are
nothing but the statements in simple English language.
Q.2 Enlist the basic building blocks of algorithms.
Ans. : The basic building blocks of algorithms are – Assignment Statements, control statements and
functions.
Q.3 What is pseudo code ?
Ans. : Pseudocode is an artificial and informal language that helps programmers develop algorithms.
Pseudocode is a "text-based" detail (algorithmic) design tool.
Q.4 Define the Flow chart
Ans. : Flow chart is a graphical representation of the algorithm. Using specific notations the
algorithm is represented using the flow chart.
Q.5 What is programming language ? Give examples.
Ans. : Programming languages are formal languages that have been designed to
Example – C, C++, Java, Python are some programming languages that are used commonly.
Q.6 Enlist different steps used in algorithmic problem solving.
Ans. : Recursion is a method of solving problems that involves breaking a problem down into smaller
and smaller subproblems until you get to a small enough problem that it can be solved trivially.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1 - 22 Algorithmic Problem Solving
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-1 Data, Expressions and Statements
Unit - II
Syllabus :
Python interpreter and interactive mode; values and types : int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs : exchange the values of two variables,
circulate the values of n variables, distance between two points.
Contents
Section Name Page. No.
2.6.1 Variables 2 - 12
2.6.3 Keywords 2 - 14
TM
Technical Publications (2- An
- 1)up thrust for knowledge
Problem Solving and Python Programming 2-2 Data, Expressions and Statements
2.8 Comments 2 - 16
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-3 Data, Expressions and Statements
Python 3.0 was released in 2008. Although this version is supposed to be backward incompatibles,
later on many of its important features have been backported to be compatible with version 2.7
1. Python is free and open source programming language. The software can be downloaded and
used freely.
4. It is portable. That means python programs can be executed on various platforms without
altering them.
5. The Python programs do not require compilation, rather they are interpreted. Internally, Python
converts the source code into an intermediate form called bytecodes and then translates this into
the native language of your computer and then runs it.
9. Python has a powerful set of built-in data types and easy-to-use control constructs.
Step 1 : For installing Python open the web page http://www.python.org/downloads. Following screen
appears before you
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-4 Data, Expressions and Statements
Click on Download Python 3.6.2 button. The file named python-3.6.2.exe will start downloading
on your machine.
Step 3 : Now the set up pop up window for Python installation will appear Click on Install Now
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-5 Data, Expressions and Statements
Step 4 : Now a User Account Control pop-up window will appear, posing the question “Do you want
to allow the following program to make changes to this computer?” Here click Yes button.
Step 5 : Another pop up window will appear with set up Progress message and progress bar.
Step 6 : During installation, it will show the various components it is installing and move the progress
bar towards completion. Soon, a new Python 3.6.2 (32-bit) Setup pop-up window will appear with a
Setup was successfully message.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-6 Data, Expressions and Statements
2.1.3 How to Write program in Python ?
First, download the latest version of Python from the official website. I have downloaded python 3.6
version.
The folder will be created for python. Copy the path for python and set up the environment variable.
C:\> python
The python shell will be displayed and >>> prompt will be displayed. One can type different
programming constructs and get the instant result of the command entered.
For example
In above command we have used print command to display the desired message at the prompt.
Review Question
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-7 Data, Expressions and Statements
The last line is a prompt that indicates that the interpreter is ready for you to enter code. If you type
a line of code and hit Enter, the interpreter displays the result. For example
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-8 Data, Expressions and Statements
Proper indentation is required while writing the code on the interpreter shell. For example
In above code the print statement is indented. After that just hit enter to introduce blank line. After
this the output will be displayed.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2-9 Data, Expressions and Statements
Step 3 : Give some suitable file name with extension .py (I have created test.py).
Step 4 : A file will get opened and the type some programming code. Sample file is as follows –
Step 5 : Now run your code by clicking on Run on Menu bar. Following screenshot illustrates it
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 10 Data, Expressions and Statements
Review Question
3. List : The list is a compound data type which contains list of elements separated by comma and
enclosed within the square brackets [ ]. To some extend it is similar to array in C. For example
>>> myList=[10,20,30]
>>> print(myList[0])
10
>>> print(myList[1:2])
[20]
>>> print(myList[0:2])
[10, 20]
>>>
4. Tuple : Tuple is also a compound data type which contains the list of elements separated by
comma but enclosed within the circular ( … ) bracket. For example
>>> mytuple =(10,20,30,40)
>>> print(mytuple[0])
10
>>> print(mytuple[1:3])
(20, 30)
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 12 Data, Expressions and Statements
5. Dictionary: This is a type of data type in which the elements are present in the form of key-value
pair format. It is a kind of hash data type. The dictionaries are enclosed within the curly brackets
{…}. For example –
>>> mydict={'name':'AAA','roll':10,'marks':94}
>>> print(mydict.keys())
dict_keys(['name', 'roll', 'marks'])
>>> print(mydict.values())
dict_values(['AAA', 10, 94])
>>>
Type Command in Python
The data type of different values can be obtained using the type command. This functions returns the
data type of that particular element.
Following session represents the data type of different values using the type command.
If a long integer is specified using the command prompt then, python does not give any message
about illegal integer, rather it separates out the digits for example
2.6.1 Variables
Definition : A variable is nothing but a reserved memory location to store values.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 13 Data, Expressions and Statements
Variable is an entity to which the programmer can assign some values. Programmer choose the
variable name which is meaningful. For example :
In the following example we have declared the variable count to which value 10 is assigned with.
This value is displayed by passing the variable name to print statement.
We can re-declare the variables for assigning different values. For example
>>> count =10
The variable count is initially assigned
>>> print(count) with 10 and then re-assigned with the
value 1000
10
>>> count = 1000
>>> print(count)
1000
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 14 Data, Expressions and Statements
2.6.3 Keywords
The keywords are special words reserved for some purpose. The python3 has following list of
keywords
False class finally Is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if Or yield
assert else import pass
break except in raise
The first statement in above code is assignment statement. The second statement is an
expression. The interpreter evaluates the expression and displays the result.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 15 Data, Expressions and Statements
2+4
3*4
5**2
Here + operator is for addition, * is for multiplication and ** is for exponentiation.
When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence.
Python follows the same precedence rules for its mathematical operators that mathematics does.
The acronym PEMDAS is a useful way to remember the order of operations.
1. P : Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 1 * (10-5) is 5
2. E : Exponentiation has the next highest precedence, so 2**3 is 8.
3. MDAS : Multiplication and Division have the same precedence, which is higher than Addition
and Subtraction, which also have the same precedence. So 2+3*4 yields 14 rather than 20.
4. Operators with the same precedence are evaluated from left to right. So in the expression 3-2+1
will result 2. As subtraction is performed first and then addition will be performed.
Numerical Literals
There are four types of numeric literals : plain integers, Long integers, Floating Point numbers and
imaginary numers.
Numeric literals immutabl(unchangeable).
Numeric literals do not include a sign such as minus.
Examples of Numeric Literals :
a=0b1100 #binary literal
b=15 #decimal literal
c=0o221#octal literal
d=0x11b#hexadecimal literal
Review Questions
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 16 Data, Expressions and Statements
2.7 Tuple Assignment
Tuple is a sequence of items of any type.
Syntactically tuple is a comma separated list of values.
Conventionally tuples are enclosed within the parenthesis.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated.
Tuples can be thought of as read-only lists.
For example : The tuple can be created as follows :
>>> student = ('AAA',96,'Std_X')
>>> print(student)
('AAA', 96, 'Std_X')
>>> print(student[0])
AAA
>>> print(student[1:3])
(96, 'Std_X')
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
For example
Review Question
2.8 Comments
Comments are the kind of statements that are written in the program for program understanding
purpose.
By the comment statements it is possible to understand what exactly the program is doing.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character.
Python Interpreter ignores comment.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 17 Data, Expressions and Statements
For example
# This is comment line
print(“I love my country”)
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example
#This is
#another example
#of comment statement
Function Call
For calling a function we use name of the function.
By giving the call to the function, it executes and
returns with some result. For example
type is a function used for returning the data type
of the argument passed to it .
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 18 Data, Expressions and Statements
The function call also helps in converting one data type element into another element for example
Python supports built in math function for performing some mathematical operations. For example –
Before using the math function we must import it.
Then using dot operator mathematical function can be called. In the following example we call the
function sqrt
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 19 Data, Expressions and Statements
Example :
Step 1 : Create a function definition in a file.
Step 2 : Press F5 button and run the above program. You will get the following output -
The first line of function definition is called function header and rest is called body.
Note that - The code within every function starts with a colon (:) and should be indented (space).
Python functions don't have any explicit begin or end like curly braces to indicate the start and stop
for the function, they have to rely on this indentation.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 20 Data, Expressions and Statements
For example : if we write the above function without indentation, then error will occur. Following
screenshot illustrates this -
If you type a function definition in interactive mode, the interpreter prints dots (...) to let you know
that the definition isn’t complete. For example
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 21 Data, Expressions and Statements
def gridDemo() :
print("+ - - - - + - - - - +")
print("| | |")
print("| | |")
print("| | |")
print("| | |")
print("+ - - - - + - - - - +")
print("| | |")
print("| | |")
print("| | |")
print("| | |")
print("+ - - - - + - - - - +")
Output
Review Question
Step 1 : We will write the program in script mode. The name of the following file is swap.py
a=10
b=20
print("Before Swapping the values are as follows...")
print(a)
print(b)
temp=a
a=b
b=temp
print("After Swapping the values are as follows...")
print(a)
print(b)
Step 2 :
Output
Step 1 : We will write the program in script mode. The name of the following file is swap.py
def swap(a,b):
temp=a
a=b
b=temp
print(a)
print(b)
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 24 Data, Expressions and Statements
2.11.2 Circulate the Values of n Variables
We circulate the values of n variable with the help of list. Suppose list a is created as [1,2,3,4], then
these 4 variables can be rotated as follows -
The program for the above activity can be written using function as follows :
Step 1 : Create a function for circulating the values. Save this function in some file.
Step 2 : Run the above script using F5 key. The output can be obtained as follows :
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 25 Data, Expressions and Statements
Program Explanation :
In above program, we have to check multiple conditions within one If Statement, we used Logical
AND and Logical OR operators. These conditions are -
1: ( year%400 == 0) OR
2: ( year%4 == 0 ) AND
3: ( year%100 == 0))
If these conditions are true then the year value is a leap year value otherwise not.
For example
2 2
dist = (9 – 3) + (7 – 2)
2 2
= 6 +5
= 61
= 7.8102
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 26 Data, Expressions and Statements
import math
print("Enter value of x1")
x1=int(input())
print("Enter value of x2")
x2=int(input())
print("Enter value of y1")
y1=int(input())
print("Enter value of y2")
y2=int(input())
dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print("The distance between two points is: ",dist)
It can be represented as
Step 2 : Just run the above code by pressing F5 key and the output will be
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 27 Data, Expressions and Statements
2.12 Two Marks Questions with Answers
Q.1 Enlist some features of python.
Ans. : The script mode in python is a mode in which the python commands are stored in a file and
the file is saved using the extension .py
Q.3 What is the use of type command in python ?
Ans. : The type command is used to determine the type of the value used. For example type(10) will
return 10.
Q.4 Explain the precedence rules used in precedence operation.
Ans. :
1. P : Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 1 * (10-5) is 5
2. E : Exponentiation has the next highest precedence, so 2**3 is 8.
3. MDAS : Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2+3*4 yields 14 rather than 20.
4. Operators with the same precedence are evaluated from left to right. So in the expression 3 – 2+1
will result 2. As subtraction is performed first and then addition will be performed.
Q.5 What is tuple ?
Ans. : Tuple is a sequence of items of any type. Syntactically tuple is a comma separated list of
values.
For example - The tuple can be created as follows :
>>> student = ('AAA',96,'Std_X')
Q.6 What is comment statement ? How do we use comment statement in python ? Explain with
example.
Ans. : Comments are non executing statements used for program understanding purpose. In python
we use # symbol to write the comment. For example
# This is a comment line
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 2 - 28 Data, Expressions and Statements
Ans. : The function can be defined using the def. The syntax of function definition is as follows :
def function_name(parameters) :
statements
Example
def my_function(a,b):
print(“a=”)
print(b= ”)
Q.8 Name four types of scalar objects Python has AU : Jan-18
Ans. : Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages
Q.10 What are the basic modes in python ?
Ans. : The value is one of the fundamental things like a word or a number that a program
manipulates. The values we have seen so far are 5 (the result when added 2 + 3), and “Hello, World !”.
We often refer these values as objects and we will use the words value and object interchangeably.
Q.12 What is a data type or simply type ?
Ans. : Data type or simply type is a classification of data which tells the compiler or interpreter
how the programmer intends to use the data
Q.13 Give short note on expression ?
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-1 Control Flow and Functions
Unit - III
Syllabus :
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.
Contents
3.8 Iteration 3 – 15
3.8.1 State 3 – 15
3.8.2 while 3 – 15
TM
Technical Publications - An up thrust for knowledge
(3 - 1)
Problem Solving and Python Programming 3-2 Control Flow and Functions
3.8.3 for 3 – 20
3.8.4 break 3 – 26
3.8.5 continue 3 – 27
3.8.6 pass 3 – 28
3.9.2 Parameters 3 – 31
3.10 Recursion 3 – 37
3.11 Strings 3 – 40
3.11.2 Immutability 3 – 42
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-3 Control Flow and Functions
In above example, == operator is used for obtaining the boolean value of the expression.
We can also check the data type of True and False with the help of type function
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
3.2 Operators
There are various types of operators such as arithmetic operators, relational operators and logical
operators. Let us understand the use of these operators with the help of illustrative examples
1. Arithmetic Operators : The arithmetic operators are used to perform arithmetic operations like
addition, subtraction, division and so on. Following table represents the list of various arithmetic
operators used in python
Operator Meaning Example
+ Addition operator is used for performing addition of 10 + 20 = 30
two numbers.
– Subtraction operator is used for performing 20 – 10 = 10
subtraction
* Multiplication operator is used for performing 10 * 10 = 100
multiplication
/ Division operator is used for performing division of 10 / 2 = 5
two numbers
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-4 Control Flow and Functions
2. Relational Operator
The relational operators are used to compare the values. Various relational operators are enlisted in
the following table
Relational Operator Meaning Example (Consider I = 1)
< Less than i<10 will return true
> Greater than i>10 will return false
<= Less than equal to i<=1 will return true
>= Greater than equal to i>=1 will return true
== Equal to i==1 will return true
!= Not Equal to i!=1 will return false
For example
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-5 Control Flow and Functions
3. Logical Operators
There are three types of logical operators and, or, not
Operator Meaning Example
and If both the operands are true then the entire expression is true a and b
or If either first or second operand is true a or b
not If the operand is false then the entire expression is true not a
For example : Following screenshot illustrates the use of logical operators in python
4. Bitwise Operators
Bitwise operators work on the bits of the given value. These bits are binary numbers i.e. 0 or 1.
For example : the number 2 is 010, 3 is 011.
Operator Meaning Example If a = 010 , b = 011
& This is bitwise and operator a&b = 010
| This is bitwise or operator a|b = 011
~ This is bitwise not operator ~a = 101
^ This is bitwise XOR operator. The binary a xor b = 001
XOR operation will always produce a 1 output
if either of its inputs is 1 and will produce a 0
output if both of its inputs are 0 or 1
<< The left shift operator a<<1 = 010<<1 means make
left shift by one positions and
add a tailing zero
010
100
=decimal 4
>> The right shift operator a>>1= 0101>>1 means make
right shift by one position and
add leading zero.
010
001
= decimal 1
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-6 Control Flow and Functions
5. Assignment Operators
The assignment operator is used to assign the values to variables. Following is a list of assignment
operators
Operator Example and Meaning
= This is an operator using which values
is assigned to a variable
a=5
+= a+=5 means
a=a+5
-= a-=5 means
a=a-5
Similarly *=, /= operators are used for performing arithmetic multiplication and division operation.
Review Questions
Example 3.3.1 : Write a python program to perform addition of two numbers. Accept the two numbers
using keyboard
Solution :
addition.py
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-7 Control Flow and Functions
Output
Program Explanation :
In above program, we have used input() function to get the input through keyboard. But this input
will be accepted in the form of string.
For performing addition of two numbers we need numerical values and not the strings. Hence we use
int() function to which the input() function is passed as parameter. Due to which whatever we accept
through keyboard will be converted to integer.
Finally the addition of two numbers as a result will be displayed.
The above program is run using F5 and on the shell window the messages for entering first and
second numbers will be displayed so that user can enter the numbers.
We can also display the data along with some space. For that purpose, we have to use {:n}.
For example
Example 2 :
n=10
print("There are {:10d} numbers".format(n))
Output
There are 10 numbers
Example 3 :
a=10
b=20
c=30
print("There are three numbers and those are {} {} {} numbers".format(a,b,c))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-8 Control Flow and Functions
Output
There are three numbers and those are 10 20 30 numbers
Example 3.3.2 Write a Python program to exchange the value of variables.
AU : Jan.-18, Marks 8
Solution :
a = input('Enter value of a: ')
b = input('Enter value of b: ')
temp = a
a=b
b = temp
print('After swapping a: {}'.format(a))
print('After swapping b: {}'.format(b))
Output
Example 3.3.3 Write a Python program to accept two numbers, multiply them and print the result.
AU : Jan.-18, Marks 2
Solution:
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Multiply two numbers
result = int(num1)*int(num2)
# Display the result
print('The multiplicationof {0} and {1} is {2}'.format(num1, num2, result))
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-9 Control Flow and Functions
Review Question
Syntax :
if condition:
statement
Example
if a<10:
print(“The number is less than 10”)
Flowchart
Syntax
If condition :
statement
else :
statement
Example 3.5.1 : Write a python program to determine whether the number is even or odd
Solution :
def EvenOddTest(n):
if n%2==0:
print("Even Number")
else:
print("Odd Number")
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 10 Control Flow and Functions
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 11 Control Flow and Functions
Example 3.6.1 : Write a python program to display the result such as Distinction, Firstclass, Second class,
Pass or fail based on the marks entered by the user.
Solution :
def Marks(m):
if m >= 75:
print("Grade : Distinction")
elif m >= 60:
print("Grade : First Class")
elif m >= 50:
print("Grade : Second Class")
elif m >= 40:
print("Grade : Second Class")
else:
print("Grade : Fail")
Output
Solution :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 12 Control Flow and Functions
Output
Example 3.6.3 : Write a Python program to accept two numbers, find the greatest and print the result.
AU : Jan.-18, Marks 2
Solution :
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
elif(num2>num1):
largest=num2;
print("largest number is ",largest)
else:
print("Two numbers are equal")
Review Question
Nested If : A nested if is an if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement.
Syntax :
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 14 Control Flow and Functions
Example 3.7.1 : Write a Python program to check whther the given number is positive, negative or zero
using nested if condition
Solution :
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Example 3.7.2 : Write a python program to compare two numbers using nested conditionals.
Solution :
def compareTwoNum(a,b):
if a==b:
print("Both the numbers are equal")
else:
if a<b:
print("First number is less than second")
else:
if a>b:
print("Second number is greater than first")
Output
Review Question
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 15 Control Flow and Functions
3.8 Iteration
Iteration is a technique that allows to execute a block of statements repeatedly.
Definition : Repeated execution of a set of statements is called iteration.
The programming constructs used for iteration are while , for, break, continue and so on.
Let us discuss the iteration techniques with the help of illustrative examples.
3.8.1 State
The simple form of statement is assignment Statement. The statement is specified using = operator.
The reassignment statement is specified as
Reassigning variables is often useful, but you should use it with caution. If the values of variables
change frequently, it can make the code difficult to read and debug.
Similarly we can update the values by using operators. For example :
3.8.2 while
The while statement is popularly used for representing iteration.
Syntax
while test_condition:
body of while
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 16 Control Flow and Functions
Syntax
while test_condition:
body of while
else:
statement
Example
while i<=10:
i=i+1
else:
print(“Invalid value of i")
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 17 Control Flow and Functions
Example 3.8.1 : Write a python program for computing the sum of n natural numbers and finding out the
average of it.
This program can be run by pressing F5 key and following output can be obtained.
Output
Example 3.8.2 : Write a python program to display square of n numbers using while loop
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 18 Control Flow and Functions
Solution :
Output
Example 3.8.3 : Write a python program for displaying even or odd numbers between 1 to n.
Solution :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 19 Control Flow and Functions
Output
Example 3.8.4 : Write a python program to display Fibonacci numbers for the sequence of length n
Solution :
print("Enter the value of n")
n=int(input())
a=0
b=1
i=0
print("Fibonacci Sequence is...")
while i<n:
print(a)
c=a+b
a=b
b=c
i=i+1
Output
Enter the value of n
10
Fibonacci Sequence is...
0
1
1
2
3
5
8
13
21
34
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 20 Control Flow and Functions
3.8.3 for
The for loop is another popular way of using iteration. The syntax of for loop is
Syntax
for variable in sequence:
Body of for loop
The variable takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from
the rest of the code using indentation.
Example Flowchart
for val in numbers:
val=val+1
Solution :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 21 Control Flow and Functions
Output
Solution :
print("Enter number for its multiplication table")
n=int(input())
for i in range(1,11):
print(n,"X",i,i*n)
Output
Solution :
print("Enter value of N")
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+1/i
print("The Sum is ",sum)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 22 Control Flow and Functions
Output
Example 3.8.8 : Write a Python program to check whether given number is prime or not
Solution :
# User can enter the value thru keyboard
print("Enter the number");
num = int(input())
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 23 Control Flow and Functions
Example 3.8.9 : Write a Python Program to find the prime numbers between given interval.
Solution:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 24 Control Flow and Functions
Solution :
print("Enter value of n")
n=int(input())
for i in range(0,n):
for j in range(0,i+1):
print('* ',end="")
print("")
Output
Example 3.8.11 : Write a python program to display the number pattern as follows
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Solution :
for i in range (1,6):
for k in range(1,i):
print(end="")
for j in range(i,6):
print(" ",j,end="")
print();
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 25 Control Flow and Functions
Output
Example 3.8.12 : Write a python program to print the pattern as given below
A
A B
A B C
A B C D
A B C D E
Solution :
for i in range(1, 6):
for j in range(65, 65+i):
a = chr(j)
print(a," ",end="")
print()
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 26 Control Flow and Functions
Example 3.8.13 : Write a python program to print the pattern for alphabets
A A A A A
B B B B
C C C
D D
E
Solution :
num=65 #ASCII Value for A
for i in range(0,5):
for j in range(i,5):
ch=chr(num+i) # Converting ASCII to character
print(ch," ",end="")
print();
Output
3.8.4 break
The break statement is used to transfer the control to the end of the loop.
When break statement is applied then loop gets terminates and the control goes to the next line
pointing after loop body.
Syntax Flowchart
break
For example
for i in range(1,11):
if i==5:
print("Element {} Found!!!".format(i))
break
print(i)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 27 Control Flow and Functions
Output
3.8.5 continue
The continue statement is used to skip some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
The continue statement forces to execute the next iteration of the loop to execute.
Syntax Flowchart
continue
Example
In while loop the continue passes the program
control to conditional test. Following example
illustrates the idea of continue
i=0
while i<10:
i=i+1
if i%2 ==0:
continue
print(i)
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 28 Control Flow and Functions
3.8.6 pass
The pass statement is used when we do not want to execute any statement. Thus the desired
statements can be bypassed.
Syntax
Pass
Example
for i in range(1,5):
if i==3:
pass
print("Reached at pass statement")
print("The current number is ",i)
Output
Review Question
1. Explain with an example while loop, break statement and continue statement in Python.
AU : Jan.-18, Marks 10
Syntax
return [expression_list]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 29 Control Flow and Functions
Return values
Syntax
return_stmt :
return [expression_list]
Return may only occur syntactically nested in a function definition, not within a nested class
definition.
If an expression list is present, it is evaluated, else none is substituted.
Return leaves the current function call with the expression list (or None) as return value.
When return passes control out of a try statement with a finally clause, that finally clause is executed
before really leaving the function.
Fig. 3.9.1
Python's built-in min() function also returns a value. Your function is just a wrapper around it.
Technically here's what happens :
1. You pass a bunch of numbers to your smallest_number() function
2. It makes a list of them and passes that list to min()
3. min() returns the smallest member of the list back to your function
4. Your function returns that number to whoever called it (probably the top level of your Python
script).
Fig. 3.9.2
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 30 Control Flow and Functions
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 31 Control Flow and Functions
Solution :
Step 1 : Write a function for finding out area of circle in Script mode as
functionDemo.py
Step 2 : Now press the key F5 to get the output of the above program. Give the function call by passing
some value of radius to it.
The output will be displayed on the shell window as follows :
3.9.2 Parameters
We can pass different number of parameters to the function. Following example illustrates the
parameter passing to the function
Solution :
def add(x, y):
return x + y
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 32 Control Flow and Functions
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", sub(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", mult(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", div(num1,num2))
else:
print("Invalid input")
Output
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
Enter your choice
1
Enter first number
10
Enter second number:
20
10 + 20 = 30
>>>
Example 3.9.3 : Write a python program to find the largest among the three numbers.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 33 Control Flow and Functions
Solution :
def largest(x, y,z):
if (x>y) and (x>z):
print("First Number is largest")
elif (y>x) and (y>z):
print("Second Number is largest")
else:
print("Third Number is largest")
print(largest(num1,num2,num3))
Example 3.9.4 : Write a Python program using function to find the sum of first ‘n’ even numbers and
print the result. AU : Jan.-18, Marks 6
Solution :
# first n even numbers
# function to find sum of
# first n even numbers
def evensum(n):
step = 2
sum = 0
i=1
# sum of first n even numbers
while i <= n:
sum += step
# next even number
step += 2
i=i+1
return sum
# Driver Code
print("Enter value of n")
n=int(input())
print("sum of first ", n, "even number is: ",evensum(n))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 34 Control Flow and Functions
Output
Enter value of n
3
sum of first 3 even number is: 12
Example 3.9.5 : Write a Python program using function to find the factors of a given number.
Solution :
#define a function
def Find_factors(n):
# This function takes a number and prints the factors
Example 3.9.6 : Write a Python program using function to find the GCD of two numbers
Solution :
# define gcd function
def gcd(a, b):
while(b):
a, b = b, a % b
return a
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 35 Control Flow and Functions
Now consider following program, in which we try to change the value declared outside the function
def f():
print(a)
a=100 #Due to this statement the error is raised
# Global scope
a = 10
f()
print(a)
To make the above program work, we need to use global keyword. We only need to use global
keyword in a function if we want to do change that variable.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 36 Control Flow and Functions
For example
Step 3 : Create a main function in which the two functions used in above two steps are called.
def mainFun(x,y):
z=add(x,y)
result=mul(z,10)
return result
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 37 Control Flow and Functions
Step 4 : Now execute the above program by pressing F5 key. The output can be obtained as follows -
>>> mainFun(10,20)
300
>>>
Program Explanation :
In above code the function composition is used. That means one function say add is called inside
another function say mainFun and its return value say z is passed to the next function i.e. mul.
This technology is called function composition.
Review Questions
3.10 Recursion
Definition : Recursion is a property in which one function calls itself repeatedly in which the values of function
parameter get changed on each call.
Properties of Recursion
There are three important laws of recursion –
1. A recursive function must have a base case.
2. A recursive function must change its state and move toward the base case.
3. A recursive function must call itself, recursively
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 38 Control Flow and Functions
Example 3.10.1 : Display the numbers from 10 to 1(i.e. numbers in reverse order) using recursion in
python. Also draw the stack diagram representing the execution of the program
Solution :
def display(n):
if n<=0:
return
else:
print(n)
display(n-1)
Output
Example 3.10.2 : Write a Python program to find the factorial of a given number without recursion and
with recursion. AU : Jan-18, Marks 8
Solution :
Factorial Without Recursion
n = int(input("Enter a number: "))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 39 Control Flow and Functions
fact = 1
i=1
while i <= n:
fact = fact * i
i=i+1
print("factorial of ", n, " is ", fact)
Example 3.10.3 : Write a Python program to generate first ‘N’ Fibonacci numbers.
Note : The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …. where each number is the sum of the
preceding two. AU : Jan-18, Marks 8
Solution :
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 40 Control Flow and Functions
Output
Review Question
3.11 Strings
String is basically the sequence of characters.
Any desired character can be accessed using the index. For example
>>> country="India"
>>> country[1] Here using index the particular character is accessed
'n'
>>> country[2]
'd'
>>>
The index is an integer value if it is a decimal value, then it will raise an error. For example
>>> country[1.5]
TypeError: string indices must be integers
>>>
The string can be created using double quote or single quotes.For example
>>> msg="Hello"
>>> print(msg)
Hello
>>> msg='Goodbye'
>>> print(msg)
Goodbye
Finding length of a String
There is an in-built function to find length of the string. This is len function. For example
>>> msg='Goodbye'
>>> print(msg)
Goodbye
>>> len(msg)
7
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 41 Control Flow and Functions
Traversing the String
We can traverse the string using the for loop or using while loop.
Example 1 - Traversing a string using while string
Output
Here the string from 0 to less than 4 index will be displayed. In the next command the string from 5th
index to 11th index is displayed.
We can omit the beginning index. In that case, the beginning index is considered as 0 For example
>>> msg[:4] Here the starting index will be 0
'Good'
Similarly we can omit ending index. In that case, the string will be displayed upto its ending
character. For example -
>>> msg[5:] Here the last character of the string is the ending index
'Morning'
>>>
If we do not specify any starting index or ending index then the string from starting index 0 to ending
index as last character position will be considered and the entire string will be displayed. For example
>>> msg[:]
'Good Morning'
>>>
3.11.2 Immutability
Strings are immutable i.e we cannot change the existing strings. For example
>>> msg="Good Morning"
>>> msg[0]='g'
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 43 Control Flow and Functions
In above example the new_msg string is created to display “good morning” instead of “Good
Morning”
The string slice from character 1 to end of string is concatenated with the character ‘g’. The
concatenation is performed using the operator +.
1. String Concatenation
Joining of two or more strings is called concatenation.
In python we use + operator for concatenation of two strings.
For example –
2. String Comparison
The string comparison can be done using the relational operators like <,>,== . For example
>>> msg1="aaa"
>>> msg2="aaa"
>>> msg1==msg2
True
>>> msg1="aaa"
>>> msg2="bbb"
>>> print(msg1<msg2)
True
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 44 Control Flow and Functions
Note that, the string comparison is made based on alphabetical ordering. All the upper case letters
appear before all the lower case letters.
3. String Repetition
We can repeat the string using * operator. For example
>>> msg="Welcome!"
>>> print(msg*3)
Welcome!Welcome!Welcome!
4. Membership Test
The membership of particular character is determined using the keyword in. For example –
>>> msg="Welcome"
>>> 'm' in msg
True
>>> 't' in msg
False
>>>
Method Purpose
count() This methods searches the substring and returns how many times the substring is
present in it.
capitalize() This function returns a string with first letter capitalized. It doesn't modify the old
string.
find() The find() method returns the lowest index of the substring (if found). If not found,
it returns -1.
index This method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
isalnum() The isalnum() method returns True if all characters in the string are alphanumeric
isdigit() The isdigit() method returns True if all characters in a string are digits. If not, it
returns False.
islower() The islower() method returns True if all alphabets in a string are lowercase
alphabets. If the string contains at least one uppercase alphabet, it returns False
Functions
We will discuss, some useful function used in string module.
1. The capwords function to display first letter capital
The capwords is a function that converts first letter of the string into capital letter.
Syntax
string.capwords(string)
Example Program : Following is a simple python program in which the first character of each word
in the string is converted to capital letter.
stringDemo.py
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 46 Control Flow and Functions
Output
i love python programming
I Love Python Programming
StringDemo1.py
import string
text1='i love programming'
text2='PROGRAMMING IN PYTHON IS REALLY INTERESTING'
print("Original String: ",text1)
print("String in Upper Case: ",str.upper(text1))
print("Original String: ",text2)
print("String in Upper Case: ",str.upper(text2))
Output
Syntax
string.maketrans(from_ch, to_ch)
Example Program
Stringmodule2.py
from_ch = "aeo"
to_ch = "012"
new_str = str.maketrans(from_ch,to_ch)
str = "I love programming in python"
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 47 Control Flow and Functions
print(str)
print (str.translate(new_str))
Output
In above program we have generated a translation table for the characters a,e and o characters.These
characters will be mapped to 0,1 and 2 respectively using the function maketrans. The actual
conversion of the given string will take place using the function translate.
According the above programming example, the string “I Love Programming in Python” is taken.
From this string we locate the letters a, e and o, these letters will be replaced by 0,1 and 2 respectively.
The resultant string will then be displayed on the console.
Constants
Constant Value
string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits '0123456789'
string.hexdigits '0123456789abcdefABCDEF'
string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.lowercase 'abcdefghijklmnopqrstuvwxyz'
string.Octdigits '01234567'
string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.whitespace '\t\n\x0b\x0c\r ‘
We can display the values of these string constants in python program. For example
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 48 Control Flow and Functions
ConstantDemo.py
Output
Example 3.11.1 : Write a Python program using function to display number of vowels and consonants in a
given string. Accept the string from user.
Solution :
def count_vowels_consonants(text):
vowels_list = ['A', 'E', 'I', 'O', 'U']
consonants = 0
vowels = 0
for character in text:
if character.isalpha():
if character.upper() in vowels_list:
vowels += 1
else:
consonants += 1
print("Vowels are =",vowels,"Consonants are =", consonants)
#Driver Code
print("Enter string")
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 49 Control Flow and Functions
str1=input()
count_vowels_consonants(str1)
Output
Enter string
HelloPython
Vowels are = 3 Consonants are = 8
Review Question
ArrayDemo.py
arr=[10,20,30,40]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 50 Control Flow and Functions
Output
1. Appending a value
Using append() function we can add the element in the array at the end.
For example
ArrayDemo1.py
arr=[10,20,30,40]
print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
arr.append(50)
print("Now The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
Output
The elements is array are ...
10
20
30
40
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 51 Control Flow and Functions
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 52 Control Flow and Functions
For example
ArrayDemo3.py
arr=[10,20,30,40]
print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
new_arr=[50,60,70]
arr.extend(new_arr)
for i in range(len(arr)):
print(arr[i])
Output
The elements is array are ...
10
20
30
40
10
20
30
40
50
60
70
>>>
For example
ArrayDemo4.py
arr=[10,20,30,40]
print("The elements is array are ...")
for i in range(len(arr)):
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 53 Control Flow and Functions
print(arr[i])
arr.remove(30)
print("Now The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
40
>>>
5. Removing last element from array
For removing the last element from the array then pop() function is used.
Syntax
pop()
For example
ArrayDemo5.py
arr=[10,20,30,40]
print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
arr.pop()
print("Now The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
30
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 54 Control Flow and Functions
6. Reversing the elements of array
We can reverse the contents of the array using reverse() function
For example
ArrayDemo6.py
arr=[10,20,30,40]
print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
arr.reverse()
print("Now The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
40
30
20
10
>>>
7. Counting the occurrence of element in array
We can count the number of times the particular element appears in the array using the count
method.
For example
ArrayDemo7.py
arr=[10,20,30,40,50,20,30,20]
print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
print("The element 20 appears for ",arr.count(20)," times in array")
Output
The elements is array are ...
10
20
30
40
50
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 55 Control Flow and Functions
20
30
20
The element 20 appears for 3 times in array
Output
2. GCD
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 56 Control Flow and Functions
Output
GCDDemo.py
def GCD(a,b):
c=b
b=a%b
if b==0:
return c
else:
return gcd(c,b)
Output
>>> GCD(15,5)
5
>>>
3. Exponentiation
Exp.py
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 57 Control Flow and Functions
Output
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 58 Control Flow and Functions
5. Linear Search
In linear search method, the key element is compared against every element of the array. If the key
element matches with the array element then we declare element is found otherwise the element is
declared as not found.
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 59 Control Flow and Functions
6. Binary Search
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 60 Control Flow and Functions
Example :
As mentioned earlier the necessity of this method is that all the elements should be sorted. So let us
take an array of sorted elements.
Array
0 1 2 3 4 5 6 7
– 40 11 33 37 42 45 99 100
Step 2 : Find the middle element of the array. Compare it with the key
Solution :
# take a 3x3 matrix
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 61 Control Flow and Functions
B = [[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for k in result:
print(k)
Output
[20, 20, 20, 20]
[47, 47, 47, 47]
[74, 74, 74, 74]
Review Questions
Ans. : Pass means no operation statement. It can be treated as placeholder in compound statement,
where there should be blank left
Q.2 What are various control statements in python ?
Ans. : Various control statements in python are – if, if…else, while, for statements
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 62 Control Flow and Functions
Ans. : The range is used to represent the size of the list or a sequence. It is commonly used in for
loop to denote the element from given range.
Q.4 What is the use of // operator in python ?
Ans. : Using // operator is used for performing the division operation. The result will be rounded and
only integer value of the result will be displayed.
Q.5 What are the rules for global and local variables ?
Ans. : Local variables : If a variable is assigned a new value anywhere within the function’s body,
it’s assumed to be local.
Global variables : Those variables that are only referenced inside a function are implicitly global.
Q.6 Is Python Case sensitive language ?
Ans. : The operator ** is exponent operator. It calculates the power of given number. For example
2**3=8
Q.9 What is purpose of break and continue statement ?
Ans. :
The break statement is for terminating the loop statement and transfers execution to the statement
immediately following the loop.
The continue statement causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
Q.10 How will you check that in a string all the characters are numberic ?
Ans. : Using the isnumeric() function we can check that in a string all the characters are numeric.
Ans. : The pop() will return remove last element of the list and remove() will remove any desired
element from the list.
Q.13 How to represent string in Python ?
Ans. : The string is represented using either double quotes or single quotes.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 63 Control Flow and Functions
Q.14 What are the operating systems on which the Python program runs ?
Ans. : The python is platform can run on Windows, Mac, Linux and so on. It is a platform
independent language.
Q.15 What is a Boolean value ?
Ans. : A Boolean value is either true or false. It is named after the British mathematician, George
Boole, who first formulated Boolean algebra - some rules for reasoning about and combining these
values. This is the basis of all modern computer logic.
Q.16 What are the Python language supports the types of operators ?
Ans. :
Arithmetic operators
Comparison (Relational) operators
Assignment operators
Logical operators
Bitwise operators
Membership operators
Identity operators
Q.17 What is the meaning of iteration ?
Ans. : Computers are often used to automate repetitive tasks. Repeating identical or similar tasks
without making errors is something that computers do well and people do poorly.
Repeated execution of a set of statements is called iteration.
Q.18 What are the Python supports the control statements ?
Ans. :
Control statement Description
break statement Terminates the loop statement and transfers execution to the statement immediately
following the loop.
continue statement Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
pass statement The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3 - 64 Control Flow and Functions
Notes
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-1 Control Flow and Functions
Unit - IV
Syllabus :
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.
Contents
Section Name Page. No.
4.1 Lists 4-2
4.1.1 List Operations 4-2
4.1.2 List Slices 4-3
4.1.3 List Methods 4-3
4.1.4 List Loop 4 - 10
4.1.5 Mutability 4 - 11
4.1.6 Aliasing 4 - 11
4.1.7 Cloning Lists 4 - 12
4.1.8 List Parameters 4 - 13
4.2 Tuples 4 - 15
4.2.1 Tuple Assignment 4 - 15
4.2.2 Tuple as Return Value 4 - 16
4.2.3 Variable Number of Arguments 4 - 17
4.3 Dictionaries 4 - 17
4.3.1 Operations and Methods 4 - 19
4.4 Advanced List Processing - List Comprehension 4 - 22
4.5 Illustrative Programs 4 - 26
4.6 Two Marks Questions with Answers 4 - 38
(4 - 1)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-2 Compound Data : Lists, Tuples and Dictionaries
4.1 Lists
List is a sequence of values.
String is also sequence of values. But in string this sequence is of characters. On the other hand, in
case of List the values can be of any type.
The values in the list are called elements or items. These elements are separated by commas and
enclosed within the square bracket.
For example
[10,20,30,40] # list of integers
[‘aaa’,’bbb’,’ccc’] #list of strings
[‘a’,10,20,’b’,33.33] #mixed list
[10,20,[‘a’,’b’,’c’]] #nested list
The list within another list is called nested list.
The list that contains no element is called empty list. The empty list is represented by []
1. Concatenation using +
The two lists can be created and can be joined using + operator. Following screenshot illustrates it.
2. Repetition using *
The * is used to repeat the list for number of times. Following screenshot illustrates it.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-3 Compound Data : Lists, Tuples and Dictionaries
4.1.2 List Slices
The : operator used within the square bracket that it is a list slice and not the index of the list
>>> a=[10,20,30,40,50,60]
>>> a[1:4]
[20, 30, 40]
>>> a[:5]
[10, 20, 30, 40, 50]
>>> a[4:]
[50, 60]
>>> a[:]
[10, 20, 30, 40, 50, 60]
>>>
If we omit the first index then the list is considered from the beginning. And if we omit the last
second index then slice goes to end.
If we omit both the first and second index then the list will be displayed from the beginning to end.
Lists are mutable. That means we can change the elements of the list. Hence it is always better to
make a copy of the list before performing any operation.
For example
>>> a=[10,20,30,40,50]
>>> a[2:4]=[111,222,333]
>>> a
[10, 20, 111, 222, 333, 50]
>>>
List Methods
1) append() : This method is to add the element at the last position of the list.
Syntax:
list.append(element)
Example:
>>> a=[10,20,30]
>>> a.append(40) #adding element 40 at the end
>>> a
[10, 20, 30, 40]
>>> b=['A','B','C']
>>> b.append('D') #adding element D at the end
>>> b
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-4 Compound Data : Lists, Tuples and Dictionaries
2) extend(): The extend function takes the list as an argument and appends this list at the end of old list.
Syntax:
List1.extend(List2)
Where List2 is added at the end of List1
Example:
>>> a=[10,20,30]
>>> b=['a','b','c']
>>> a.extend(b)
>>> a
[10, 20, 30, 'a', 'b', 'c']
>>>
3) insert() : This function allows to insert the desired element at specified position.
Syntax :
List.insert(position, element)
Where the first parameter is a position at which the element is to be inserted. The element to be
inserted is the second parameter in this function.
Example :
a=[10,20,30]
a.insert(2,25)
print("List a = ",a)
Output will be
List a = [10, 20, 25, 30]
>>>
4) pop():
This function removes the element specified by the index.
Syntax:
List.pop(index)
The index represent the location of element in the list and the element specified by the index will be
deleted and returned. The parameter passed to the list is optional. If no parameter is passed, the default
index -1 is passed as an argument which returns the last element.
Example
#list created
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-5 Compound Data : Lists, Tuples and Dictionaries
a=[10,20,30,40,50]
ret_val=a.pop(2)
print("The deleted element is = ",ret_val)
print("The modified list is = ",a)
Output
The deleted element is = 30
The modified list is = [10, 20, 40, 50]
>>>
Example
#list created
a=[10,20,30,40,50]
ret_val=a.pop()
print("The deleted element is = ",ret_val)
print("The modified list is = ",a)
Output
The deleted element is = 50
The modified list is = [10, 20, 30, 40]
Syntax
List.pop(negative index)
Example
# Creation of list
a = [10,20,30,40,50]
# When -1 is passed
# Pops Last Element
print('\nWhen -1 is passed:')
print('Return Value: ', a.pop(-1))
print('Updated List: ', a)
# When -3 is passed
# Pops Third Last Element
print('\nWhen -3 is passed:')
print('Return Value: ', a.pop(-3))
print('Updated List: ', a)
Output
When -1 is passed:
Return Value: 50
Updated List: [10, 20, 30, 40]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-6 Compound Data : Lists, Tuples and Dictionaries
When -3 is passed:
Return Value: 20
Updated List: [10, 30, 40]
>>>
5) remove : The remove method deletes the element which is passed as a parameter. It actually
removes the first matching element.
Syntax :
List.remove(element)
Example :
>>> a=[10,20,30,20,40,50]
>>> a.remove(20)
>>> print(a)
[10, 30, 20, 40, 50]
6) erase() : This method erases all the elements of the list. After this operation the list becomes empty.
Syntax :
List.clear()
Example :
>>> a=[10,20,30,40,50]
>>> a.clear()
>>> print(a)
[]
>>>
7) del() : This method deletes all the elements within the given range.
Syntax :
List.del(a:b)
The element within the range a to b get deleted by this method.
Example :
>>> a=['a','b','c','d','e']
>>> del a[2:4]
>>> a
['a', 'b', 'e']
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-7 Compound Data : Lists, Tuples and Dictionaries
Syntax:
List.sort()
Example :
>>> a=['x','z','u','v','y','w']
>>> a.sort()
>>> a
['u', 'v', 'w', 'x', 'y', 'z']
>>>
Syntax:
List.reverse()
Example :
>>> a=[10,20,30,40,50]
>>> a.reverse()
>>> print("List after reversing is: ",a)
List after reversing is: [50, 40, 30, 20, 10]
>>>
10) count() : This method returns a number for how many times the particular element appears in the
list.
Syntax :
List.count(element)
Example :
>>> a=[10,20,10,30,10,40,50]
>>> print("Count for element 10 is: ",a.count(10))
Count for element 10 is: 3
1) all() : This function returns true if all the elements of the list are true or if the list is empty.
Syntax:
all(iterable)
The all method returns true if all elements in iterable are true otherwise it returns false.
Example :
>>> a=[1,2,3,4]
>>> print(all(a))
True
>>> b=[1,2,0,3,4]
>>> print(all(b))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-8 Compound Data : Lists, Tuples and Dictionaries
False
>>> c=[]
>>> print(all(c))
True
>>>
2) any() : This method returns True if any element of an iterable is true. If not, this method returns
False.
Syntax :
any(iterable)
Example :
>>> a=[10,0,20,30,40]
>>> print(any(a))
True
>>> b=[]
>>> print(any(b))
False
>>> c=[False,0]
>>> print(any(c))
False
>>>
3) len() : This function returns the number of items present in the list
Syntax:
len(List)
Example :
>>> a=[10,20,30,40,50]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4-9 Compound Data : Lists, Tuples and Dictionaries
>>> print("The length of list a is: ",len(a))
The length of list a is: 5
>>>
Syntax:
list([iterable])
The list() constructor returns a mutable sequence list of elements.
If no parameters are passed, it creates an empty list
If iterable is passed as parameter, it creates a list of elements in the iterable
Example :
>>> print(list())
[]
>>> mystr="hello"
>>> print(list(mystr))
['h', 'e', 'l', 'l', 'o']
>>> mytuple=('h','e','l','l','o')
>>> print(list(mytuple))
['h', 'e', 'l', 'l', 'o']
>>>
5) max() : This function returns the maximum value element from the list.
Syntax:
max(iterable)
The maximum value from the iterable is returned.
Example :
>>> a=[1,2,3,55,7]
>>> print(max(a))
55
>>>
6) min() : This function returns the minimum value element from the list.
Syntax:
min(iterable)
The minimum value from the iterable is returned.
Example :
>>> a=[100,10,1,20,30]
>>> print(min(a))
1
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 10 Compound Data : Lists, Tuples and Dictionaries
>>>
7) sum() : This function adds the items of iterable and the sum is retunred.
Syntax :
Sum(iterable, start)
The sum of all the elements from the iterable is returned. The start is optional. If start value is
mentioned then it is added to the sum.
Example :
>>> a=[1,2,3,4]
>>> result=sum(a)
>>> print(result)
10
>>> start=100
>>> print(sum(a,start))
110
>>>
Syntax
for VARIABLE in LIST :
BODY
Example
>>> a=['a','b','c','d','e'] # List a is created
>>> for i in a:
print(i)
will result into
a
b
c
d
e
>>>
If we want to update the elements of the list, then we must pass index as argument to for loop. For
example
>>> a=[10,20,30,40]
>>> for i in range(len(a)):
a[i]=a[i]+1 #incremented each number by one
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 11 Compound Data : Lists, Tuples and Dictionaries
>>> a
[11, 21, 31, 41]
>>>
If we specify the [ ] empty list then the body of for loop will never get executed.
>>> for i in []:
print("This line will never execute")
>>>
4.1.5 Mutability
Strings are immutable. That means, we can not modify the strings.But Lists are mutable. That means
it is possible to change the values of list.
If the bracket operator is present on the left hand side, then that element is identified and the list
element is modified accordingly.
For example
>>> a=['AAA','BBB','CCC']
>>> a[1]='XXX'
>>> a
['AAA', 'XXX', 'CCC']
>>>
Using the in operator we can check whether particular element belongs to the list or not. If the given
element is present in the list it returns True otherwise False. For example
>>> a = ['AAA', 'XXX', 'CCC']
>>> 'XXX' in a
True
>>> 'BBB' in a
False
>>>
4.1.6 Aliasing
Definition : An object with more than one reference has more than one name, so we say that the object is aliased.
For example -
>>> x=[10,20,30]
>>> y=x
>>> y is x
True
>>> y
[10, 20, 30]
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 12 Compound Data : Lists, Tuples and Dictionaries
>>> x=[10,20,30]
>>> y=x
>>> y
[10, 20, 30]
>>> y[0]=111
>>> y
[111, 20, 30]
>>> x
[111, 20, 30]
>>>
Note that in above list if we change the reference list y then the list x also gets changed
automatically.
Note that the clone b is created from the list a. But change in one list does not affect the other list.
The operator [:] means copy the elements in one list from beginning to end into another list.
Note that even if we make changes in the clone list, the other list does not get changed. For example
>>> a
['A', 'B', 'C']
>>> b[1]='Z'
>>> b
['A', 'Z', 'C']
>>> a
['A', 'B', 'C']
>>>
For example :
In above screen-shot, the python code is written in interactive mode. The function Insert_End is for
inserting the element at the end of the list.
Here we pass the list a as parameter to the function. Inside the function, the element is added at the
end of the list. Hence after the making call to the function, we get the list in which the element is
inserted at the end.
Solution :
a = [1,2,3,2,1,4,5,4,8,5,4]
duplicates = set()
for x in a:
if x not in duplicates :
duplicates.add(x)
print(duplicates)
Output
Example 4.1.2 : Write a Python program to read a list of words and return the length of longest one
Solution:
a=[]
print("Enter the number of words in list:")
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 15 Compound Data : Lists, Tuples and Dictionaries
n= int(input())
for i in range(0,n):
item=input("Enter word" + str(i+1) + ":")
a.append(item)
max_len=len(a[0])
temp=a[0]
for i in a:
if(len(i)>max_len):
max_len=len(i)
temp=i
print("The longest length word is ")
print(temp)
Review Question
1. What is list ? Explain any two list operations with illustrative examples.
4.2 Tuples
Tuple is a sequence of values. It is similar to list but there lies difference between tuple and list
Tuple List
Tuple is said to immutable. That means once created we can not change the tuple.
Examples of tuples
T1 = (10,20,30,40)
T2 = (‘a’,’b’,’c’,’d’)
T3 = (‘A’,10,20)
T4 = (‘aaa’,’bbb’,30,40)
The empty tuple can be created as
T1 = ()
How to Write Tuple ?
Tuple is written within the parenthesis. Even if the tuple contains a single value, the comma is used
as a separator. For example –
T1 = (10,)
The tuple index starts at 0. For example
>>> t1=(10,20,'AAA','BBB')
>>> print(t1[0])
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 16 Compound Data : Lists, Tuples and Dictionaries
10
>>> print(t1[1:3])
(20, 'AAA')
>>>
Here the left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments.
Note that the number of variables on the left and right have to be the same.
We can also separate out the values in the expression in the tuple by using the split function. For
example
>>> student='AAA,123'
>>> name,roll=student.split(',')
>>> print(name)
AAA
>>> print(roll)
123
>>>
In above example, the expression is split at comma and the two separated values are collected in two
different variables. We have name and roll variables in which the corresponding values are stored.
Test.py
def student_Info():
name='AAA'
roll=101
return name,roll
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 17 Compound Data : Lists, Tuples and Dictionaries
Output
Test.py
def student_Info(*args):
print(args)
Output
In above program * accepts the variable number of arguments and inside the function definition,
these arguments are printed.
Review Question
4.3 Dictionaries
Definition : In Python, dictionary is unordered collection of items. These items are in the form of key-value pairs.
Dictionary always represent the mappings of keys with values. Thus each key maps to a value.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 18 Compound Data : Lists, Tuples and Dictionaries
How to Create Dictionary ?
Items of the dictionary are written within the {} brackets and are separated by commas
The key value pair is represented using : operator. That is key:value
The keys are unique and are of immutable types – such as string, number, tuple.
We can also create a dictionary using the word dict(). For example –
>>> my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})
test.py
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 19 Compound Data : Lists, Tuples and Dictionaries
4.3.1 Operations and Methods
Basic Operations
Various operations that can be performed on dictionary are :
4. Checking length
The len() function gives the number of pairs in the dictionary. For example
>>> my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})#creation of dictionary
>>> len(my_dictionary) # finding the length of dictionary
3 #meaning – that there are 3 items in dictionary
>>>
Methods in Dictionary
Following are some commonly used methods in dictionary.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 20 Compound Data : Lists, Tuples and Dictionaries
Method Purpose
clear Removes all items from dictionary
copy( ) Returns a copy of dictionary
fromkeys( ) Creates a new dictionary from given sequence of elements and values
provided by user
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items( ) Return a new view of the dictionary's items (key, value).
keys( ) Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if key is not found. If d
is not provided and key is not found, raises KeyError.
popitem( ) Remove and return an arbitary item (key, value). Raises KeyError if the
dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of
d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting
existing keys.
values( ) Return a new view of the dictionary's values
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 21 Compound Data : Lists, Tuples and Dictionaries
3. The fromkey method
The fromkeys( ) method creates a new dictionary from the given sequence of elements with a value
provided by the user.
Syntax
dictionary.fromkeys(sequence[, value])
The fromkeys( ) method returns a new dictionary with the given sequence of elements as the keys of
the dictionary. If the value argument is set, each element of the newly created dictionary is set to the
provided value.
For example
>>> keys={10,20,30}
>>> values = 'Number'
>>> new_dict=dict.fromkeys(keys,values)
>>> print(new_dict)
{10: 'Number', 20: 'Number', 30: 'Number'}
>>>
4. The get method
The get( ) method returns the value for the specified key if key is in dictionary. This method takes
two parameters key and value. The get method can return either key, or value or nothing.
Syntax
dictionary.get(key[, value])
For example
>>> student={'name':'AAA','roll':10,'marks':98} #creation of dictionary
>>> print("Name: ",student.get('name'))
Name: AAA
>>> print("roll: ",student.get('roll'))
roll: 10
>>> print("marks: ",student.get('marks'))
marks: 98
>>> print("Address: ",student.get('address')) #this key is ‘address’ is not specified in the list
Address: None #Hence it returns none
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 22 Compound Data : Lists, Tuples and Dictionaries
6. The pop method
This method The pop() method removes and returns an element from a dictionary having the given
key.
Syntax
pop(key[, default])
where key is the key which is searched for removing the value. And default is the value which is to
be returned when the key is not in the dictionary. For example
my_dictionary={1:'Red',2:'Blue',3:'Green'}#creation of dictionary
>>> val=my_dictionary.pop(1) #removing the element with key 1
>>> print("The popped element is: ",val)
The popped element is: Red
>>> val=my_dictionary.pop(5,3)
#specifying default value. When the specified key is not present in the list, then the
#default value is returned.
>>> print("The popped element using default value is: ",val)
The popped element using default value is: 3 #default value is returned
>>>
Review Questions
The above code creates a list of square numbers from 0 to 10. This list can be created using a
simplified expression “x**2 for x in range(10)”. This is basically list comprehension.
List comprehensions apply an arbitrary expression to items in an iteration.
The list comprehension is achieved using the tools like map, lambda and filter.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 23 Compound Data : Lists, Tuples and Dictionaries
1. Map
The map( ) function applies the values to every member of the list and returns the result.
The map function takes two arguments -
result=map(function, sequence)
For example
>>> def increment_by_three(x):
return x+3
>>> new_list=list(map(increment_by_three,range(10)))
>>> new_list
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>>
Another Example :
There is a built in function for calculating length of the string and i.e. len( ). We can pass this
function to map and find the length of every element present in the list as a list.
>>> names=['Sandip','Lucky','Mahesh','Sachin']
>>> lengths=list(map(len,names))
>>> lengths
[6, 5, 6, 6]
>>>
2. Filter
The Filter( ) function selects some of the elements and filters out others.
If we use if with list compression, it is almost equivalent to the filter built-in.
This function takes two arguments –
result=filter(function, sequence)
For example –
>>> def even_fun(x):
return x%2==0
>>> r=filter(even_fun,[1,2,3,4,5])
>>> list(r)
[2, 4]
>>>
In above example, using filter( ) function the odd numbers are filtered out and only even
numbers are displayed.
filter( ) works in the similar manner like map( ), it applies function to all the elements of the list.
3. Lambda
The lambda function is a simple inline function that is used to evaluate the expression using the
given list of arguments.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 24 Compound Data : Lists, Tuples and Dictionaries
The syntax is
lambda argument_list : expression
where the argument_list consists of a comma separated list of arguments and the expression is
an arithmetic expression using these arguments.
For example :
>>> sum=lambda x,y:x+y
>>> sum(1,3)
4
>>>
Thus the expression x+y is evaluated and the result of evaluation is returned.
4. Reduce
The kind of function that combines sequence of elements into a single value is called reduce
function.
The reduce function also takes two arguments –
Result=reduce(function, sequence)
The function reduce( ) had been dropped from the core of Python when migrating to Python 3.
Hence for using the reduce function we have to import functools to be capable of using reduce.
For example
>>> import functools
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4])
10
>>>
Write a python program, which returns a list with 2 tuples – Each tuple consists of item no, and product of
price and quantity.
If value of the order is less than `. 100 then the product is increased by ` 10.
Write a program in Python using map and lambda functions
Solution :
>>> order=[["111",12,20],["112",5,100],["113",7,5]]
>>> min_order=100
>>> Total_Bill=list(map(lambda x:x if x[1]>=min_order else(x[0],x[1]+10),
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 25 Compound Data : Lists, Tuples and Dictionaries
map(lambda x:(x[0],x[1]*x[2]),order)))
>>> print(Total_Bill)
[('111', 240), ('112', 500), ('113', 45)]
>>>
Example 4.4.2 : Write a Python program to display power of 2 using Anonymous function.
Solution : The Anonymous function is a lambda function. We can write the program to display the
power of 2 using Anonymous function
Test.py
Output
Review Question
1. Explain map, reduce, filter and lambda functions with suitable example.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 26 Compound Data : Lists, Tuples and Dictionaries
4.5 Illustrative Programs
1. Selection Sort
The selection sort method descibes as follows - Scan the array to find its smallest element and swap
it with the first element. Then, starting with the second element scan the entire list to find the smallest
element and swap it with the second element. Then starting from the third element the entire list is
scanned in order to find the next smallest element. Continuing in this fashion we can sort the entire list.
70 30 20 50 60 10 40
70 30 20 50 60 10 40
i Smallest element found
10 30 20 50 60 70 40
nd
2 pass :
A[0] A[1] A[2] A[3] A[4] A[5] A[6]
10 30 20 50s 60 70 40
i,
Scan the array for finding
Min smallest element
10 30 20 50 60 70 40
i Smallest element
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 27 Compound Data : Lists, Tuples and Dictionaries
10 20 30 50 60 70 40
rd
3 pass :
A[0] A[1] A[2] A[3] A[4] A[5] A[6]
10 20 30 50 60 70 40
i, Min Smallest elements is searched
in this list
10 20 30 50 60 70 40
i Smallest element
All these elements
have occupied their
final positions
10 20 30 40 60 70 50
th
5 pass :
A[0] A[1] A[2] A[3] A[4] A[5] A[6]
10 20 30 40 60 70 50
i
Search smallest
element in this list
10 20 30 40 60 70 50
i Smallest
element
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 28 Compound Data : Lists, Tuples and Dictionaries
10 20 30 40 50 70 60
th
6 pass :
10 20 30 40 50 70 60
i Smallest
element
Swap A[i] with smallest element. The array then becomes,
A[0] A[1] A[2] A[3] A[4] A[5] A[6]
10 20 30 40 50 60 70
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 29 Compound Data : Lists, Tuples and Dictionaries
2. Insertion Sort
In this method the elements are inserted at their appropriate place. Hence is the name insertion sort.
Let us understand this method with the help of some example -
For Example
Consider a list of elements as,
0 1 2 3 4 5 6
30 70 20 50 40 10 60
Algorithm
Although it is very natural to implement insertion using recursive(top down) algorithm but it is very
efficient to implement it using bottom up(iterative) approach.
Algorithm Insert_sort(A[0…n-1])
//Problem Description: This algorithm is for sorting the
//elements using insertion sort
//Input: An array of n elements
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 30 Compound Data : Lists, Tuples and Dictionaries
InsertionSort.py
def insertionsort( a):
for i in range( 1, len( a ) ):
tmp = a[i]
k=i
while k > 0 and tmp < a[k - 1]:
a[k] = a[k - 1]
k -= 1
a[k] = tmp
a = [50,30,10,20,40,70,60]
print("Original List is...")
print(a)
insertionsort(a)
print("The sorted List is...")
print(a)
Output
3. Merge Sort
Merge sort on an input array with n elements consists of three steps :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 31 Compound Data : Lists, Tuples and Dictionaries
Step 1 : partition array into two sub lists s1 and s2 with n/2 elements each.
mergersort.py
def merge(left, right):
if not len(left) or not len(right):
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 32 Compound Data : Lists, Tuples and Dictionaries
def mergesort(a):
if len(a) < 2:
return a
middle = int(len(a)/2)
left = mergesort(a[:middle])
right = mergesort(a[middle:])
return merge(left, right)
a=[30,50,10,40,20]
print("Before sorting ...")
print(a)
print("After sorting ...")
print(mergesort(a))
Output
Bars
Y Axis
X Axis Bin
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 33 Compound Data : Lists, Tuples and Dictionaries
Parts of Histogram
Title : The title gives a brief description of what the information is represented by the histogram.
Horizontal or X-Axis : The horizontal or X-axis shows you the range or the values of gaps in
between variables. They are commonly called class intervals which represent or summarize large data
sets.
Vertical or Y-Axis : The vertical or Y-axis represents the range values of frequencies or the number
of times that the class intervals occurred.
Bars : The bars represent the object, item, event, or person from where the variables arise. Their
height denotes their respective frequencies, while the bar placement along the X-axis indicates their
respective interval values. The width, however, is the same for all bars.
Bin : Histograms use bins to display data-where a bin represents a given range of values.
It is very simple to plot the Histogram in Python, but for that we need to install few libraries - namely
numpy, scipy and mathplotlib.
Step 1 : For installing numpy, open the command prompy and issue following command
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 34 Compound Data : Lists, Tuples and Dictionaries
Step 2 : For installing scipy, open the command prompy and issue following command
Step 3 : For installing matlib, open the command prompt and issue following command
Very often, installation of Scipy in above manner fails. Hence we need to adopt another method to
install Scipy. For that purpose open the site http://www.lfd.uci.edu/~gohlke/pythonlibs/
Search for Scipy. Here before installing SciPy, you need to install numpy+MKL by clicking
following link.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 35 Compound Data : Lists, Tuples and Dictionaries
Now open the command prompt, change the directory to your download folder and issue the pip
install command for numpy installation and then for Scipy
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 36 Compound Data : Lists, Tuples and Dictionaries
Step 4 : Thus now all the necessary installations for plotting the histogram is complete. This can be
verified by opening the Python Shell and issuing following commands
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 37 Compound Data : Lists, Tuples and Dictionaries
Open the New file, and write following program for plotting the histogram.
histogram.py
import matplotlib.pyplot as plt
from numpy.random import normal
gaussian_numbers = normal(size=1000)
#plt.hist(gaussian_numbers)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 38 Compound Data : Lists, Tuples and Dictionaries
Now run the above program by pressing F5 key and you will get following output
Review Questions
1. Write a Python program to store ‘n’ numbers in a list and sort the list using selection sort.
AU : Jan.-18, Marks 8
Ans. : Lists is a sequence of values enclosed within a square bracket. For example
[10,20,30,40]
Q.2 What is the use of * operator in association with List in Python ?
Ans. : The * operator is used to repeat the list number of times. For example
[1,2,3]*3 will give
[1,2,3,1,2,3,1,2,3]
Q.3 What is the purpose of extend method in python ?
Ans. : The extend method takes new list as argument and append it with old list. Thus using extend
two lists can be combined.
Q.4 Suppose you have given a list a=[1,2,3,4], how will you iterate through this list and print each
element of it ?
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 39 Compound Data : Lists, Tuples and Dictionaries
Ans. : Following Python code is used for iterating through the list and display of the numbers
>>> a=[10,20,30,40]
>>> for i in range(len(a)):
print(a[i])
Ans. : Mutability is a property indicating whether we can change the element of the sequence or not.
List is mutable. That means we can change the element of list.
Q.6 What is aliasing ?
Ans. : An object with more than one reference has more than one name, so we say that the object is
aliased.
For example -
>>> x=[10,20,30]
>>> y=x
>>> y is x
True
Q.7 What is tuple ? How literals of type tuple are written give example.
AU : Jan-18
Ans. : Tuple is a sequence of values. It is similar to list but there lies difference between tuple and
list.
Examples of tuples
T1=(10,20,30,40)
T2=(‘a’,’b’,’c’,’d’)
Q.8 Differentiate between tuple and list.
AU : Jan-18
Ans. :
Tuple List
Tuple use parenthesis List use square brackets
Tuples can not be change Lists can be changed.
Q.9 How can we pass variable number of arguments to tuple ?
Ans. : In python, it is possible to have variable number of arguments. In that case the parameter
name begins with *. Then these variable number of arguments are gathered into a tuple. For example –
def student_Info(*args):
print(args)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 40 Compound Data : Lists, Tuples and Dictionaries
Ans. : In Python, dictionary is unordered collection of items. These items are in the form of key-
value pairs.
The dictionary contains the collection of indices called keys and collection of values.
For example
My_dictionary={1:’AAA’,2:’BBB’,3:’CCC’}
Ans. : A list can store a sequence of objects in a certain order such that we can iterate over the list.
List is a mutable type meaning that lists can be modified after they have been created.
A tuple is similar to a list except it is immutable. In tuple the elements are enclosed with in
parenthesis. Tuples have structure, lists have order.
A dictionary is a key-value store. It is not ordered.
Q.12 Explain what is range() function and how it is used in lists?
Ans. : The range function returns an immutable sequence object of integers between the given start
integer to the stop integer.
range(start,stop,[step])
>>>for I in range(1,10,2):
print(i,end=” “)
13579
Ans. :
a) append()- add an element to end of list
b) insert()- insert an item at the defined index
c) remove()- removes an item from the list
d) clear()- removes all items from the list
e) reverse()- reverse the order of items in the list
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 41 Compound Data : Lists, Tuples and Dictionaries
Ans. :
Tuple is used for heterogeneous data types and list is used for homogeneous data types.
Since tuple are immutable, iterating through tuple is faster than with list.
Tuples that contain immutable elements can be used as key for dictionary.
Implementing data that doesn’t change as a tuple remains write-protected
Q.16 What is indexing and negative indexing in Tuple?
Ans. : The index operator is used to access an item in a tuple where index starts from 0.
Python also allows negative indexing where the index of -1 refers to the last item, -2 to the
second last item and so on.
>>>my_tuple=(‘p’,’y’,’t’,’h’,’o’,’n’)
>>>print(my_tuple[5] ) n
>>>print(my_tuple[- 6]) p
Q.17 What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
Ans. : In the given command, tuple[1:3] is accessing the items in tuple using indexing.
It will print elements starting from 2nd till 3rd. Output will be (786, 2.23).
Q.18 What are the methods that are used in Python Tuple?
Ans. : Methods that add items or remove items are not available with tuple. Only the following two
methods are available :
a) count(x)- returns the number of items that is equal to x
b) index(x)- returns index of first item that is equal to x
Q.19 Is tuple comparison possible? Explain how with example.
Ans. : The standard comparisons (‘<’,’>’,’<=’,’>=’,’==’) work exactly the same among tuple
objects. The tuple objects are compared element by element.
>>>a=(1,2,3,4,5)
>>>b=(9,8,7,6,5)
>>>a<
b True
Q.20 What are the built-in functions that are used in Tuple?
Ans. :
all()- returns true if all elements of the tuple are true or if tuple is empty
any()- returns true if any element of tuple is true
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 4 - 42 Compound Data : Lists, Tuples and Dictionaries
Q.21 What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and
tinytuple = (123, 'john')?
Ans. : It will print concatenated tuples. Output will be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
Ans. : Dictionaries are similar to other compound types except that they can use any immutable type
as an index. One way to create a dictionary is to start with the empty dictionary and add elements.
The empty dictionary is denoted {}:
>>> eng2sp = {}
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’
Ans. : The elements of a dictionary appear in a comma-separated list. Each entry contains an index
and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are
called key-value pairs.>>> print eng2sp {’one’: ’uno’, ’two’: ’dos’}
Q.24 How to slice list in python?
AU : Jan 18
Ans. :
The : operator used within the square bracket that it is a list slice and not the index of the list
>>> a=[10,20,30,40,50,60]
>>> a[1:4]
[20, 30, 40]
>>> a[:5]
[10, 20, 30, 40, 50]
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 1-1 Algorithmic Problem Solving
Unit - V
Syllabus :
Files and exception : text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
programs : word count, copy file.
Contents
5.1 Files 5-2
5.4 Modules 5 – 17
5.5 Packages 5 – 21
TM
Technical Publications - An up thrust for knowledge
(5 - 1)
Problem Solving and Python Programming 5-2 Files, Modules and Packages
5.1 Files
AU : Jan.-18, Marks 16
Syntax
File_object=open(file_name,mode)
Here file named test.txt is opened and the file object is in variable F
We can open the file in text mode or in binary mode. There are various modes of a file in which it is
opened. These are enlisted in the following table
Mode Purpose
‘r’ Open file for reading
‘w’ Open file for writing. If the file is not created, then create new file and then write.
If file is already existing then truncate it.
‘x’ Open a file for creation only. If the file already exists, the operation fails.
‘a’ Open the file for appending mode. Append mode is a mode in which the data is
inserted at the end of existing text. A new file is created if it does not exist.
‘t’ Opens the file in text mode
‘b’ Opens the file in binary mode
‘+’ Opens a file for updation i.e. reading and writing.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-3 Files, Modules and Packages
For example :
fo=open(“test.txt”,w) #opens a file in write mode
fo=open(“text.txt”,rt) #Open a file for reading in text mode
Closing a File
After performing all the file operations, it is necessary to close the file.
Closing of file is necessary because it frees all the resources that are associated with file.
Example -
fo=open(“test.txt”,rt)
fo.close() #closing a file.
Writing to a File
For writing the contents to the file, we must open it in writing mode. Hence we use ‘w’ or ’a’ or ‘x’
as a file mode.
The write method is used to write the contents to the file.
Syntax
File_object.write(contents)
The write method returns number of bytes written.
While using the ‘w’ mode in open, just be careful otherwise it will overwrite the already written
contents. Hence in the next subsequent write commands we use “\n” so that the contents are written
on the next lines in the file.
For example :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-4 Files, Modules and Packages
Reading File
For reading the file , we must open the file in r mode and we must specify the correct file name
which is to be read
The read() method is used for reading the file. For example - Following screenshot illustrates how
read function operates.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-5 Files, Modules and Packages
Example 5.1.1 : Write a python program to write n number of lines to the file and display all these lines as
output.
Solution :
print("How many lines you want to write")
n=int(input())
outFile=open("d:\\test.txt",'wt')
for i in range(n):
print("Enter line")
line=input()
outFile.write("\n"+line)
outFile.close()
print("The Contents of the file 'test.txt' are ...")
inFile=open("d:\\test.txt",'rt')
print(inFile.read())
inFile.close()
Output
Example 5.1.2 : Write a python program to write the contents in ‘one.txt’ file. Read these contents and
write them to another file named ‘two.txt’
Solution :
print("How many lines you want to write")
n=int(input())
outFile=open("d:\\one.txt",'wt')
for i in range(n):
print("Enter line")
line=input()
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-6 Files, Modules and Packages
outFile.write("\n"+line)
outFile.close()
inFile=open("d:\\one.txt",'rt')
outFile=open("d:\\two.txt",'wt')
i=0
for i in range(n+1):
line=inFile.readline()
outFile.write("\n"+line)
inFile.close()
outFile.close()
print("The Contents of the file 'two.txt' are ...")
inFile=open("d:\\two.txt",'rt')
print(inFile.read())
inFile.close()
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-7 Files, Modules and Packages
5.1.3 Other File Operations
There are some other important operations that can be performed on the file. Let us understand them
with the help of illustrative examples.
We can pass number of bytes to the seek method. These many bytes are skipped and then remaining
contents are displayed. For example
>>> inf.seek(10)
10
>>> print(inf.read())
#note that 10 bytes are skipped and then the remaining contents are displayed
on to File Operations
Reading and writing operations in Python are easy
We enjoy it
This line is written in file
This is a last line of this file
>>>
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-8 Files, Modules and Packages
Note that the subsequent readline calls moves the cursor to next line and display that line as output.
3. The readlines method
The readlines method displays all the lines of the file at a time. But this method returns the lines as a
list. Hence we get all the lines of the file in list format For example :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5-9 Files, Modules and Packages
If there is more than one format sequence in the string, the second argument has to be a tuple. Each
format sequence is matched with an element of the tuple, in order.
For example : Following errors are due to mismatch in tuple with format sequence.
>>> 'There are %d%d%d numbers'%(1,2) #mismatch in number of elements
TypeError : Not enough arguments for format string
>>> 'There are %d rows'%'three'
TypeError : %d format: a number is required, not str #mismatch in type of element
Review Questions
1. What is file ? Explain the reading and writing to the file with illustrative python program.
2. Tabulate the different modes for opening a file and explain the same.
AU : Jan.-18, Marks 16
2. We can use sys.argv for getting the list of command line arguments.
3. The len(sys.argv) gives total number of command line arguments.
The python program illustrating the access to command line arguments is as given below.
Step 1 : Write a python script as follows. Here the name of the script file is CmdLine.py
Step 2 : The command prompt window is opened and type the python command at the prompt and we
get the output of the above program
Review Question
Definition of exception : An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program.
In general, when a python script encounters a situation that it cannot cope with, it raises an
exception.
When a python script raises an exception, it must either handle the exception immediately otherwise
it terminates and quits.
The exception handling mechanism using the try…except…else blocks.
The suspicious code is placed in try block.
After try block place the except block which handles the exception elegantly.
If there is no exception then the else block statements get executed.
Syntax of try…except…else
try:
write the suspicious code here
except Exception 1:
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 12 Files, Modules and Packages
Example
Suppose programmer wants some integer value and some character value is entered then python will
raise error. This scenario can be illustrated by following screenshot
Such situation can be gracefully handled using exception handling mechanism as follows :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 13 Files, Modules and Packages
Step 2 : Now run the above code for both valid and invalid inputs.
Output(Run1: Execution of except block)
A single try can have multiple except statements. We can specify standard exception names for
handling specific type of exception. For example
Example 5.3.1 : Write a python program to perform division of two numbers. Raise the exception if the
wrong input(other than integer) is entered by the user. Also raise an exception when divide by zero occurs.
Solution :
try :
a=int(input("Enter value of a: "))
b=int(input("Enter value of b: "))
c=a/b
except ValueError:
print("You have entered wrong data")
except ZeroDivisionError:
print("Divide by Zero Error!!!")
else:
print("The result: ",c)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 14 Files, Modules and Packages
Output(Run1)
Output(Run2)
Output(Run3)
Example 5.3.2 : Write a program to read the contents of the file. If the file does not exist then raise
appropriate exception.
Solution :
try :
inFile=open("myfile.txt",'rt')
except IOError:
print("Error:File Not found")
else:
print(inFile.read()) #displaying contents of file on getting file
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 15 Files, Modules and Packages
Output
Example 5.3.3 : Write a python program to open a file having no write permission but trying to write the
data. Handle this situation using exception handling mechanism.
Solution :
try:
FileObj=open("myfile.txt",'rt')
FileObj.write("This is my data")
except IOError:
print("Error:File does not have write permission!!!")
else:
print("Contents are written Successfully!!!")
Output
Name Purpose
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 16 Files, Modules and Packages
EOFError Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
NameError Raised when an identifier is not found in the local or global namespace.
SystemError Raised when the interpreter finds an internal problem, but when this error
is encountered the python interpreter does not exit.
SystemExit Raised when python interpreter is quit by using the sys.exit() function. If
not handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the
specified data type.
ValueError Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
Use of finally
The finally clause will be executed at the end of the try-except block no matter what - if there is no
exception, if an exception is raised and handled, if an exception is raised and not handled, and even if
we exit the block using break, continue or return. We can use the finally clause for cleanup code that we
always want to be executed.
For example :
try :
age=int(input("Enter your age"))
except ValueError:
print("Invalid age")
else:
print("Your age is: ",age)
finally:
print("Good Bye")
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 17 Files, Modules and Packages
Output(Run1)
Output(Run2)
Review Questions
3. Appraise the use of try block and except block in Python with syntax.
AU : Jan-18, Marks 6
5.4 Modules
There some standard functionalities in python that are written in particular module. For using those
functionalities, it is essential to import the corresponding module first.
For example : There are various functionalities available under the module math. For instance, if
you want to find out the square root of some number then you need to import module math first and
then use the sqrt function.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 18 Files, Modules and Packages
Basically modules in python are .py files in which set of functions are written.
Modules are imported using import command.
Step 1 : Create a file having extension .py. Here we have created a file PrintMsg.py. In this file, the
function fun is defined.
PrintMsg.py
Step 2 : Now open the python shell and import the above module.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 19 Files, Modules and Packages
Step 3 : Now using the module name access the function as follows
The _ _name_ _ is a built-in variable that is set when the program starts. If the program is running as
a script, _ _name_ _ has the value '_ _main_ _'.In that case, the test code runs. Otherwise, if the
module is being imported, the test code is skipped.
The above program can be modified as
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 20 Files, Modules and Packages
Simply Run the above code and you will get the following output on the Python Shell(Note that now
there is no need to use import statement)
Solution :
Step 1 :
FibSeries.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
Step 2 : Open the python shell and import the above module and access the functionality within it. The
output will be as follows :
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 21 Files, Modules and Packages
5.5 Packages
Packages are namespaces which contain multiple
packages and modules. They are simply directories.
Along with packages and modules the package
contains a file named _ _init_ _.py. In fact to be a
package, there must be a file called _ _init_ _.py in
the folder.
Packages can be nested to any depth, provided that the
corresponding directories contain their own
__init__.py file.
For example :
We can access the package and various subpackages and
modules in it as follows :
Fig. 5.5.1 Arrangement of Package
import My_Package #loads My_Package/__init__.py
import My_Package.module1 #loads My_Package/module1.py
from My_Package import module2
import My_Package.SubPackage1
When we import Main package then there is no need to import subpackage. For example
import My_Package
My_Package.SubPackage1.my_function1()
Thus we need not have to import SubPackage1.
The primary use of __init__.py is to initialize Python packages. Simply putting the subdirectories
and modules inside a directory does not make a directory a package, what it needs is a __init__.py
inside it. Then only Python treats that directory as package.
How to Create a Package ?
To understand how to create a package, let us take an example. We will perform arithmetic
operations addition, multiplication, division and subtraction operations by creating a package. Just
follow the given steps to create a package
Step 1 : Create a folder named MyMaths in your working drive. I have created it on D: drive.
Step 2 : Inside MyMaths directory create __init__.py file. Just create an empty file.
Step 3 : Create a folder named Add inside MyMaths. Inside Add folder creation file named
addition.py. The addition.py will be as follows
addition.py
def add_fun(a,b):
return a+b
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 22 Files, Modules and Packages
Step 4 : Similarly the folder Sub insider MyMaths is created. Inside which create a file subtraction.py.
The code for this file is
subtraction.py
def sub_fun(a,b):
return(a-b)
Step 5 : Similarly the folder Mul insider MyMaths is created. Inside which create a file
multiplication.py. The code for this file is
multiplication.py
def mul_fun(a,b):
return(a*b)
Step 6 : Similarly the folder Div insider MyMaths is created. Inside which create a file division.py.
The code for this file is
division.py
def div_fun(a,b):
return (a/b)
Step 7 : The overall directory Structure will be as given below. Note that _pycache_ is automatically
generated directory.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 23 Files, Modules and Packages
Step 8 : Now on the D: drive create a driver program which will invoke all the above functionalities
present in the MyMaths package. I have named this driver program as testing_arithmetic.py. It is as
follows
import MyMaths.Add.addition
import MyMaths.Mul.multiplication
We need to import the models in this way, to
import MyMaths.Div.division
use the respective functionalities
import MyMaths.Sub.subtraction
print("The addition of 10 and 20 is: ",MyMaths.Add.addition.add_fun(10,20))
print("The multiplication of 10 and 20 is: ",MyMaths.Mul.multiplication.mul_fun(10,20))
print("The division of 10 and 5 is: ",MyMaths.Div.division.div_fun(10,5))
print("The subtraction of 20 and 10 is: ",MyMaths.Sub.subtraction.sub_fun(20,10))
Step 9 : Now just run this testing program and you will get following output
Review Question
1. Word Count : This program counts the number of words present in the given file. If the specified file
is not present, then exception is raised.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 24 Files, Modules and Packages
WordCount.py
The test file from which the words are counted is as given below
test.txt
Output
2. Copy File : In this program, the contents of one file are copied line by line to another file. For that
purpose I have created a file named one.txt in which some contents are stored. These contents are
copied to another file named two.txt. The python program for this is as given below -
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 25 Files, Modules and Packages
Output
Ans. : File is a named location on the disk to store information. It is a mechanism for persistent
storage.
Q.2 What is the syntax for file open method ?
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 26 Files, Modules and Packages
Syntax
File_object=open(file_name,mode)
Here file named test.txt is opened and the file object is in variable F
Q.3 What are different modes of file operation ?
Ans. :
Mode Purpose
‘w’ Open file for writing. If the file is not created, then create new file and then
write. If file is already existing then truncate it.
‘x’ Open a file for creation only. If the file already exists, the operation fails.
‘a’ Open the file for appending mode. Append mode is a mode in which the data
is inserted at the end of existing text. A new file is created if it does not exist.
Q.4 Explain the seek and tell methods used in python file handling
Ans. : The seek method is used to change the file position. Similarly the tell method returns the
current position.
Fobj.seek(0) #will set the position at the beginning of the file
Fobj.seek(1) #will set the position at current location
Fobj.seek(2) # will set the position at the end of the file
Ans. : The readline method reads a single line from the file while the readlines read all the lines
written in the file at a time.
Q.6 Explain the use of format operator.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 27 Files, Modules and Packages
Ans. : The format operator is specified using % operator. For example - if we want to display
integer value then the format sequence must be %d, similarly if we want to display string value then
the format sequence must be %s and so on.
Q.7 What are command line arguments in python ?
Ans. : The sys.argv is a list in python, which contains the command-line arguments passed to the
script. With the len(sys.argv) function you can count the number of arguments.
Q.8 Give examples of syntax errors.
Ans. : The python finds the syntax errors when it parses the source program. Commonly occurring
syntax errors are -
(i) Putting a keyword at wrong place
(ii) Misspelling the keyword
(iii) Incorrect indentation
(iv) Forgetting the symbols such as comma, brackets, quotes
(v) Empty block.
Q.9 What is exception ?
Ans. : An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program.
Q.10 Give the syntax of exception handling.
Ans. : This is a kind of exception that is raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid values specified.
Q.12 What is TypeError ?
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 5 - 28 Files, Modules and Packages
Ans. : This exception is raised when an operation or function is attempted that is invalid for the
specified data type.
Q.13 What is module ?
Ans. : The modules are basically the files having .py extension and containing some special
functionalities.
Q.14 What is package ?
Ans. : Package is a specialized directory containing subpackages, modules and __init__.py file.
Ans. : The primary use of _ _init_ _.py is to initialize python packages. Simply putting the
subdirectories and modules inside a directory does not make a directory a package, what it needs is a _
_init_ _.py inside it. Then only python treats that directory as package.
Q.16 What is the difference between module and python ?
Ans. :
The module is single file(or files) that are imported and then used. Whereas package is a
collection of modules in directories.
There is no need of _ _init_ _.py file for module. The package must contain _ _init_ _.py file.
Q.17 Write a Python script to display current date and time.
AU : Jan 18
Ans. :
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Ans. : Modular design approach in python is a design technique which allows to keep the python
code in separate files. The executable application will be created by putting all the modules together.
It makes the application readable, reliable and maintainable.
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming 3-1 Control Flow and Functions
Contents
Program 11 : Find the most frequent words in a text read from a file L - 11
TM
Technical Publications (L- An
- 1)up thrust for knowledge
Problem Solving and Python Programming L-2 Laboratory
Program :
(i) Recursive GCD Program
def GCD(a,b):
c=b
b=a%b
if b==0:
return c
else:
return GCD(c,b)
print(GCD(10,20))
Program
def newtonSqrtDemo(num, frequency):
approx = 0.5 * num
for i in range(frequency):
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-3 Laboratory
print("Enter the number for finding out the square root: ")
num=int(input())
print("The Sqaure root is computed with apporximation: ")
print(newtonSqrtDemo(num,1))
print(newtonSqrtDemo(num,5))
print(newtonSqrtDemo(num,10))
Output
Program Explanation : In above program, the Newton’s method of approximation is used. If you
start with almost any approximation, you can compute a better approximation with the following
formula :
result = 1/2 * (approx + n/approx)
Thus in above program with approximation 1,5, and 10 the result is computed. As we increase the
approximation, we get the more appropriate result.
Solution :
Exp.py
def expo(base,degree):
result = 1
i=1
while i <= degree:
result = base * result
i += 1
print("result is ", result)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-4 Laboratory
Output
Program :
MaxNum.py
print("\tPROGRAM TO FIND MAXIMUM OF A LIST OF NUMBERS")
print("How many elements are there in the list? ")
n=int(input())
a=[]
for i in range(n):
print("Insert a number: ")
num=int(input())
a.append(num)
print(a)
max_num=a[0]
for i in range(n):
if(max_num<a[i]):
max_num=a[i]
print("The maximum number is a list is : ",max_num)
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-5 Laboratory
Program :
LinearSearch.py
print("Enter total number of elements in array")
n=int(input())
i=0
for i in range(0,n):
print("Enter the element: ")
a[i]=int(input())
print("The elements in array are...")
for i in range(0,n):
print(a[i])
print("Enter the key element to be searched")
key=int(input())
for i in range(0,n):
if a[i]==key:
found=True
break;
else:
found=False
if found==True:
print("The element is found")
else:
print("The element is not found")
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-6 Laboratory
Program :
BinarySearch.py
def binary_Search(a,n,key):
low = 0
high = n
while(low <= high):
mid = int((low + high)/2)
if (key == a[mid]):
return mid
elif(key < a[mid]):
high = mid - 1
else:
low = mid + 1
return -1
n =int(input("Enter the size of the list: "))
a = [i for i in range(n)]
print(n)
print("Enter the element: ")
for i in range(0,n):
a[i]=int(input())
print("Enter the element to be searched: ")
k=int(input())
position = binary_Search(a, n, k)
if(position != -1):
print("Entered number %d is present at position: %d"%(k,position))
else:
print("Entered number %d is not present in the list"%k)
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-7 Laboratory
Program :
SelectionSort.py
def selectionsort( a ): #function definition
for i in range( len( a ) ):
least = i
for k in range( i + 1 , len( a ) ):
if a[k] < a[least]:
least = k
temp = a[least]
a[least] = a[i]
a[i] = temp
a = [50,30,10,20,40,70,60]
print("Original List is...")
print(a)
selectionsort(a) #Call to the function
print("The sorted List is...")
print(a)
Output
Program :
InsertionSort.py
def insertionsort( a):
for i in range( 1, len( a ) ):
tmp = a[i]
k=i
while k > 0 and tmp < a[k - 1]:
a[k] = a[k - 1]
k -= 1
a[k] = tmp
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-8 Laboratory
a = [50,30,10,20,40,70,60]
print("Original List is...")
print(a)
insertionsort(a)
print("The sorted List is...")
print(a)
Output
Program :
mergersort.py
def merge(left, right):
if not len(left) or not len(right):
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L-9 Laboratory
def mergesort(a):
if len(a) < 2:
return a
middle = int(len(a)/2)
left = mergesort(a[:middle])
right = mergesort(a[middle:])
a=[30,50,10,40,20]
print("Before sorting ...")
print(a)
print("After sorting ...")
print(mergesort(a))
Output
Program
PrimeNum.py
def isPrime(num):
if num == 2:
return True
elif num < 2 or not num % 2: # even numbers > 2 not prime
return False
# factor can be no larger than the square root of num
for i in range(3, int(num ** .5 + 1), 2):
if not num % i: return False
return True
Output
Program :
# First 3x3 matrix
A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
# Second 3x4 matrix
B = [[15,2,1,5],
[8,6,0,4],
[2,4,1,6]]
# The Resultant 3x4
C = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
for m in C:
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 11 Laboratory
print(m)
Output
Solution :
import sys
print ("Number of arguments:",len(sys.argv),"arguments.")
print ("Argument List:", str(sys.argv))
Output
Program 11 : Find the most frequent words in a text read from a file
Program :
FreqCnt.py
from collections import Counter
def word_freq_count(fname):
with open(fname) as inFile:
return Counter(inFile.read().split())
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 13 Laboratory
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 14 Laboratory
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
pygame.display.flip()
Code Explanation :
import pygame – This is the most required statement at the beginning of any Pygame program.
pygame.init() - It initializes all the modules required for PyGame.
pygame.display.set_mode((width, height)) - This will launch a window of the desired size. The
return value is a Surface object which is the object you will perform graphical operations on.
pygame.event.get() - This empties the event queue. If you do not call this, the windows messages
will start to pile up and your game will become unresponsive in the opinion of the operating system.
pygame.QUIT - This is the event type that is fired when you click on the close button in the corner
of the window.
pygame.display.flip() - PyGame is double-buffered. This swaps the buffers. All you need to know is
that this call is required in order for any updates that you make to the game screen to become visible.
When we run the above code we will get
We can draw rectangles, circles, ellipse and so on using various commands. Before you draw any
object fill the screen with suitable color.
screen.fill(color)
The color is in the form of R,G,B values. For example
red = (255,0,0)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 15 Laboratory
green = (0,255,0)
blue = (0,0,255)
darkBlue = (0,0,128)
white = (255,255,255)
black = (0,0,0)
pink = (255,200,200)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 16 Laboratory
pygame.draw.ellipse(screen,black,(220,120,140,180),2)
pygame.draw.ellipse(screen,black,(200,100,180,220),2)
pygame.draw.ellipse(screen,black,(180,80,220,260),2)
pygame.draw.ellipse(screen,black,(160,60,260,300),2)
pygame.draw.ellipse(screen,black,(140,40,300,340),2)
pygame.draw.ellipse(screen,black,(120,20,340,380),2)
pygame.draw.ellipse(screen,black,(100,00,380,420),2)#outermost ellipse
pygame.display.update()
Output
Solution :
import pygame
# Define color for Screen
WHITE = (255, 255, 255)
# Define color for ball
RED = (255, 0, 0)
pygame.init()
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 17 Laboratory
# Starting position
x = 50
y = 50
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming L - 18 Laboratory
Output
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-1 Programs for Practice
Experiment 1 : Write a Python Program to display current date and Time A-3
Experiment 3 : Write a Python Program to check whether the input year is leap year or A-3
not
Experiment 4 : Write a Python program to accept two numbers, multiply them and A-4
print the result
Experiment 5 : Write a Python Program to accept two numbers, find the greatest and A-4
print the result.
Experiment 6 : Write a Python program to implement simple calculator A-5
Experiment 7 : Write a Python Program to check whether the number is positive, A-6
negative or zero
Experiment 8 : Write a Python program to find area of triangle(using Base and height) A-6
Experiment 9 : Write a Python program to find area of triangle(using three sides) A-7
Experiment 13 : Write a Python Program for finding L.C.M. of two numbers A-8
Experiment 15 : Write a Python program to display all the prime numbers within the A-9
given interval
Experiment 16 : Write a Python Program to print the factors of a given number A-9
Experiment 26 : Write a python Program to separate out and display the letters, digits A - 14
and special characters from the given string.
Experiment 27 : Write a Python Program to remove punctuation marks from the given A - 15
string
Experiment 28 : Write a Python Program to sort the words alphabetically from given A - 15
string
Experiment 29 : Write a Python Program to swap to strings A - 15
Experiment 30 : Write a Python Program to delete a desired word from given string A - 16
Experiment 35 : Write a Python Program to find the sum of all the elements in a List A - 18
Experiment 36 : Write a Python Program to find the largest element from the List A - 18
Experiment 37 : Write a Python Program to replace the last element of first list by the A - 19
entire second list elements
Experiment 38 : Write a Python Program to accept a string from console and display the A - 19
characters present at even indexes.
Experiment 39 : Write a Python Program to iterate a list in reverse order A - 19
Experiment 43 : Write a Python program to create a tuple from a list of numbers from 1 A - 20
to 10
Experiment 44 : Write a Python program to create another tuple of even numbers from A - 21
the tuple containing the numbers from 1 to 10
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-3 Programs for Practice
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Output
Current date and time :
2018-04-10 10:58:53
import calendar
print("Enter Year: ");
yy=int(input())
print("Enter month: ");
mm = int(input());
print("\n",calendar.month(yy,mm));
Output
Enter Year:
2018
Enter month:
4
April 2018
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Experiment 3 : Write a Python Program to check whether the input year is leap year or not
Output
Enter a year:
2016
2016 is a leap year
Experiment 4 : Write a Python program to accept two numbers, multiply them and print the result
Jan 18
Output
Enter first number:
10
Enter second number:
20
The multiplication is: 200
Experiment 5 : Write a Python Program to accept two numbers, find the greatest and print the result.
Jan 18
print("Enter first number: ")
a=int(input())
print("Enter second number: ")
b=int(input())
if a>b:
print("First number is greater")
else:
print("Second number is greater")
Output
Enter first number:
10
Enter second number:
20
Second number is greater
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-5 Programs for Practice
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", sub(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", mult(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", div(num1,num2))
else:
print("Invalid input")
Output
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
Enter your choice
1
Enter first number
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-6 Programs for Practice
10
Enter second number:
20
10 + 20 = 30
Experiment 7 : Write a Python Program to check whether the number is positive, negative or zero
Output(Run 1)
Enter some number
4
Positive number
Output(Run 2)
Enter some number
-4
Negative number
Output(Run 3)
Enter some number
0
Zero
Experiment 8 : Write a Python program to find area of triangle(using Base and height)
Output
Enter base:
10
Enter height:
20
The area of triangle is: 100.0
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-7 Programs for Practice
import math
print("Enter first side: ")
a=float(input())
print("Enter second side: ")
b=float(input())
print("Enter third side: ")
c=float(input())
s=(a+b+c)/2
area=math.sqrt((s*(s-a)*(s-b)*(s-c)))
print("The area of triangle is: ",area)
Output
Enter first side:
3
Enter second side:
4
Enter third side:
5
The area of triangle is: 6.0
Output
Enter the celsius value:
40.5
Fahrenheit value = 104.9
Output
Enter the Fahrenheit value:
104.9
Celsius value = 40.5
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-8 Programs for Practice
Output
Enter value in kilometers:
100
miles= 62.137100000000004
Output
Enter first number: 4
Enter second number: 6
The L.C.M. of 4 and 6 is 12
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A-9 Programs for Practice
Output
Enter first number:
15
Enter second number:
5
gcd of given numbers is: 5
Experiment 15 : Write a Python program to display all the prime numbers within the given interval
Output
Enter the range [a,b]
1
10
Prime numbers between 1 and 10 are...
2
3
5
7
Output
Enter number:
12
The factors of 12 are...
1
2
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 10 Programs for Practice
3
4
6
12
Experiment 17 : Write a Python Program to convert decimal number to binary using recursion
def DecToBin(n):
if n > 1:
DecToBin(n//2)
print(n % 2,end = '')
Output
Enter decimal number:
10
1010
A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
B = [[11,12,13],
[14,15,16],
[17,18,19]]
C = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
# iterate through columns
for j in range(len(A[0])):
C[i][j] = A[i][j] + B[i][j]
print("Matrix A..")
for i in A:
print(i)
www
print("Matrix B..")
for j in B:
print(j)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 11 Programs for Practice
Output
Matrix A..
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix B..
[11, 12, 13]
[14, 15, 16]
[17, 18, 19]
The addition of two matrices is..
[12, 14, 16]
[18, 20, 22]
[24, 26, 28]
A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
B = [[11,12,13],
[14,15,16],
[17,18,19]]
C = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
# iterate through columns
for j in range(len(A[0])):
for k in range(len(B)):
C[i][j]+= A[i][k] * B[k][j]
print("Matrix A..")
for i in A:
print(i)
print("Matrix B..")
for j in B:
print(j)
Output
Matrix A..
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix B..
[11, 12, 13]
[14, 15, 16]
[17, 18, 19]
The multiplication of two matrices is..
[90, 96, 102]
[216, 231, 246]
[342, 366, 390]
A = [[1, 2],
[3, 4],
[5, 6]]
B = [[0, 0, 0],
[0, 0, 0]]
for i in range(len(A)):
for j in range(len(A[0])):
B[j][i] = A[i][j]
print("Original Matrix is...")
for k in A:
print(k)
Output
Original Matrix is...
[1, 2]
[3, 4]
[5, 6]
Transposed Matrix is...
[1, 3, 5]
[2, 4, 6]
def power(x,y):
if(y==1):
return(x)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 13 Programs for Practice
if(y!=1):
return(x*power(x,y-1))
x=int(input("Enter base: "))
y=int(input("Enter exponential value: "))
print("Result:",power(x,y))
Output
Enter base: 2
Enter exponential value: 3
Result: 8
Output(Run 1)
Enter some number to check if it is Armstrong number:
153
153 is an Armstrong Number.
Output(Run 2)
Enter some number to check if it is Armstrong number:
101
101 is not an Armstrong Number.
Output
Enter a character: A
The ASCII value of 'A' is 65
str = 'madam'
# reverse the string
rev_str = reversed(str)
if list(str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
Output
It is palindrome
Experiment 26 : Write a python Program to separate out and display the letters, digits and special
characters from the given string.
string=input("Enter string:")
vowels=0
consonants=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowels=vowels+1
else:
consonants=consonants+1
Output
Enter string:hello
Number of vowels are:
2
Number of consonants are:
3
Experiment 27 : Write a Python Program to remove punctuation marks from the given string
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
str = input("Enter a string: ")
result = ""
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 15 Programs for Practice
for ch in str:
if ch not in punctuations:
result = result + ch
print("The string after removing punctuations: ",result)
Output
Enter a string: hello!how are you? Bye.
The string after removing punctuations: hellohow are you Bye
Experiment 28 : Write a Python Program to sort the words alphabetically from given string
Output
Enter a string: Shilpa Archana Supriya
The sorted words are:
Archana
Shilpa
Supriya
Output
Enter First String: aaa
Enter Second String: bbb
Before swapping:
First String = aaa
Second String = bbb
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 16 Programs for Practice
After swapping:
First String = bbb
Second String = aaa
Experiment 30 : Write a Python Program to delete a desired word from given string
Output
Enter any string to remove particular word: This is big Python program
Enter word to be deleted: big
This is Python program
Output
Enter some string with spaces in between: Hello Friend
j=0
print("Enter number of rows: ")
rows = int(input())
for i in range(1, rows+1):
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 17 Programs for Practice
for space in range(1, (rows-i)+1):
print(end=" ")
while j != (2*i-1):
print("* ", end="")
j=j+1
j=0
print()
Output
Enter number of rows:
10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
Output
Enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 18 Programs for Practice
Output
Enter number of rows:
5
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
Experiment 35 : Write a Python Program to find the sum of all the elements in a List
def sum_list(items):
total = 0
for x in items:
total += x
return total
print(sum_list([10,20,30,40]))
Output
100
Experiment 36 : Write a Python Program to find the largest element from the List
def Largest(items):
max_ele=items[0]
for x in items:
if x > max_ele:
max_ele=x
return max_ele
print(Largest([5,-1,100,2,30]))
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 19 Programs for Practice
Output
100
Experiment 37 : Write a Python Program to replace the last element of first list by the entire second list
elements
def Replace_element(num1,num2):
num1[-1:] = num2
print(num1)
num1 = [1, 2, 3, 4, 5]
num2 = [11, 12, 13, 14]
Replace_element(num1,num2)
Output
[1, 2, 3, 4, 11, 12, 13, 14]
Experiment 38 : Write a Python Program to accept a string from console and display the characters present
at even indexes.
def display_even(str):
str=str[::2]
print(str)
Output
Enter some string: python
pto
def display_reverse(str):
str=str[::-1]
print(str)
Output
Enter some string: python
nohtyp
Experiment 40 : Write a Python program to count number of characters in a string. Display the character
and its count. Make use of concept of dictionary.
def display_char_count(str):
d={}
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 20 Programs for Practice
print("The occurrences of characters are as follows ...")
for s in str:
d[s]=d.get(s,0)+1
print (d.items())
Output
Enter some string: abccaade
The occurrences of characters are as follows ...
dict_items([('a', 3), ('b', 1), ('c', 2), ('d', 1), ('e', 1)])
Experiment 41 : Write a Python program to display a number from 1 to 10 along with its square.Make use of
concept of dictionary.
def display_Square():
d=dict()
for i in range(1,11):
d[i]=i*i
print (d)
display_Square()
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
def display_Str():
t=('M','y','I','n','d','i','a')
str=''.join(t)
print(str)
display_Str()
Output
MyIndia
Experiment 43 : Write a Python program to create a tuple from a list of numbers from 1 to 10
def Create_tuple():
li=list()
for i in range(1,11):
li.append(i)
print(tuple(li))
Create_tuple()
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 21 Programs for Practice
Output
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Experiment 44 : Write a Python program to create another tuple of even numbers from the tuple containing
the numbers from 1 to 10
def Even_tuple():
t1=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in t1:
if i<10:
if t1[i]%2==0:
li.append(t1[i])
t2=tuple(li)
print(t2)
Output
Even_tuple()
Output
(2, 4, 6, 8, 10)
TM
Technical Publications - An up thrust for knowledge
Problem Solving and Python Programming A - 22 Programs for Practice
Notes
TM
Technical Publications - An up thrust for knowledge
Semester - I (Common to All Branches) - Regulation 2017
TM