GE3151
GE3151
3 0 0 3
COURSE OBJECTIVES: To understand the basics of algorithmic problem solving. To learn to solve problems
using Python conditionals and loops. To define Python functions and use function calls to solve problems. To
use Python data structures - lists, tuples, dictionaries to represent complex data. To do input/output with files in
Python.
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments; Illustrative programs:
exchange the values of two variables, circulate the values of n variables, distance between two points.
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.
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: simple sorting, histogram, Students marks statement, Retail bill preparation.
TOTAL : 45 PERIODS
COURSE OUTCOMES: Upon completion of the course, students will be able to CO1: Develop algorithmic
solutions to simple computational problems. CO2: Develop and execute simple Python programs. CO3: Write simple
Python programs using conditionals and looping for solving problems. CO4: Decompose a Python program into
functions. CO5: Represent compound data using Python lists, tuples, dictionaries etc. CO6: Read and write data
from/to files in Python programs.
TEXT BOOKS:
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition, O’Reilly Publishers,
2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and programming”, 1st
Edition, BCS Learning & Development Limited, 2017.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data
Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python: With Applications to
Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press 2021.
4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to Programming”, 2nd Edition, No
Starch Press, 2019.
5. https://www.python.org/ 6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill,
2018.
GE3151 Problem Solving and Python Programming
FUNDAMENTALS OF COMPUTING:
A computer is an electronic device that performs sequences of arithmetic or logical operations on
information or data. Computers can store, retrieve, and process data. A computer consists of five main
components: 1) Input Unit, 2) Memory Unit, 3) Processing Unit, 4) Output Unit, and 5) Control Units.
1. Input Unit accepts information from user using devices such as keyboards, mouse, etc. It
also accepts information from other computers over digital communication lines.
2. Memory Unit stores the information received from the user. The information is either
used later or processed immediately by the processing unit.
3. Processing Unit (or) Arithmetic and Logic Unit (ALU) transforms the input into
output. All calculations & comparisons are made in the processing Unit.
4. Output Unit sends back the results of processing unit to the user. Some output units are
monitor, printer, etc.
5. Control Unit coordinates all the actions of the computer. Control unit allows all units to
exchange information and coordinate their actions. It provides the sequence in which all
operations need to be performed.
Characteristics of Computers:
1. Speed - A computer works with high speeds than compared to humans. Speed of the
computer is measured in microseconds or nanoseconds. Computers can run millions of
instructions per second.
2. Accuracy - Computers perform operations with 100% accuracy. Errors may occur due to
wrong input by human.
3. Diligence - Computer perform repeated operations with the same consistency and
accuracy. It doesn’t feel any fatigue or lack of concentration.
4. Versatility - Versatility means a computer can perform different kinds of works with same
accuracy and efficiency.
5. Reliability - A computer gives consistent result for similar set of data. We will get the
same output, for the same input always.
6. Automation - Computers performs all the operations automatically, without human
intervention.
7. Memory - A computer has built-in memory called primary memory. Primary memory
stores data during execution. Secondary memory stores data permanently.
Capabilities of Computers:
1. Computers are extremely fast, accurate and reliable.
2. It can handle large volumes of repetitive tasks with high accuracy.
3. It stores large amounts of data in its memory, and it can recall data instantly.
4. It can communicate with other machines, called interactive processing.
5. It can do critical and dangerous jobs that may be hazardous to humans.
6. It can be used in decision making that answers either yes or no.
Limitation of Computers:
1. Computer's biggest limitation is their dependence on humans. A
computer can only accept instructions from users and cannot do
anything on their own.
2. Computers cannot express their ideas.
3. Only the user who knows computer can use the computer.
Applications of Computers:
Computers play an important role in every day human activities.
They are used in homes, business, educational institutions, research
organizations, medical field, government offices, entertainment, etc.
1. Home - Computers are used at homes for online bill payment, watching
movies at home, social media activities, playing games, etc. They help to
avail work-from-home facility for employees.
Generations of a Computer
Growth in the computer industry is determined by the development in technology. Based on
various stages of development, computers can be categorized into different generations.
Sl. Generation Period Main Merits/Demerits
No Component
used
1 First 1940-1956 Vacuum • Big in size
Generation Tubes • Consumed more power
• Malfunction due to overheat
• Machine language was used.
Eg: ENIAC , EDVAC , UNIVAC 1
2 Second 1956-1964 Transistor • Smaller compared to First
Generation Generation
• Generated less heat
• Consumed less power compared
to first generation
• Punched cards were used
• First operating system was
developed - Batch Processing
and Multiprogramming
Operating System
• Machine language as well as
Assembly language was used.
Eg: IBM 1401, IBM 1620
COMPUTING DEVICES
• Computing devices are the mathematical devices which can do the math muchin faster
way. They do the math calculations on the streams of binary digits (0and 1) and produce
• It consists of three units. They are keyboard, monitor, and a system unit
containing the CPU, memory, hard disk drive, etc.
• It is not very expensive and it is used in home, small business units, and
organizations.
• Examples: Apple, Microsoft, HP, Dell and Lenovo are some of the PC
manufacturers.
Net book
Tablet Computer
• A tablet computer does not have keyboard and mouse. It can accept input froma stylus
or a pen.
• It is a portable computer.
• It is a new kind of PC.
• It is small in size. Instead of the keyboard, PDA uses a pen or a stylus forinput.
• PDAs do not have a disk drive. They have a limited memory and are less
powerful.
Smart Phones
• They are cellular phones that function both as a phone and as a small PC.
• They may use a stylus or a pen, or may have a small keyboard.
Minicomputers
Mainframe Computers
• They are large powerful systems and operate at a very high speed. They havevery large
storage capacity centralized databases and can handle the workloadof many users.
• The mainframe computer accessed via a dumb terminal, an intelligent terminal or a PC.
They use the processing power and the storage facility of the mainframe computer.
• A dumb terminal cannot store data or do processing of its own. It has the inputand output
device only.
• An intelligent terminal has the input and output device, can do processing, butcannot
store data of its own. Mainframe computers are used in organizations like banks or
companies, where many people require frequent access to the same data.
• Examples: CDC 6600 and IBM ES000 series.
Wearable Computers
Supercomputers
• Supercomputers are the fastest and the most expensive machines. They have high
processing speed compared to other computers.
• The speed of a supercomputer is generally measured in FLOPS (FLoating Point
Operations Per Second). Some of the faster supercomputers can perform trilions of
calculations per second.
• Supercomputers are built by interconnecting thousands of processors that canwork in
parallel.
• Supercomputers are used for highly calculation intensive tasks, such as, weather
forecasting, climate research (global warming), molecular research, biological
research, nuclear research and aircraft design.
• They are also used in major universities, military agencies and scientific research
laboratories.
• Some examples of supercomputers are IBM Roadrunner, IBM Blue gene andIntel ASCI
red.
• PARAM is a series of supercomputer assembled in India by C-DAC. PARAMPadma is
the latest machine in this series. The peak computing power of PARAM Padma is 1
TeraFLOP (TFLOP).
- ALGORITHMS
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm
is a well-defined computational procedure consists of a set of instructions that takes some values
as an input, then manipulate them by following prescribed texts in order to produce some values
as output.
– Characteristics of an Algorithm:
An algorithm should have the following characteristics.
Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the
result of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Effectiveness – algorithm should be most effective among many different ways to solve
a problem.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.
Examples:
1. Write an algorithm to find the area of circle.
Step1: Start
Step2: Read the value of radius as r
Step3: Calculate area = 3.14*r*r
Step4: Print the value of area.
Step5: Stop
3. Write an algorithm for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89.
Step1: Start
Step2: Read Numbers as N
Step3: Initialize the value of Total as 0 and as 1
Step4: Repeat step 5 to step7 until i is less than n
Step5: Read the marks
Step6: Add mark to the total
Step7: Increment the value of i
Step6: Print the value of total
Step7: Stop
c) Control Flow
Control Flow or Flow of Control is the order function calls, instructions and statement are
executed or evaluated when a program is running. Program Control structures are defined as the
program statements that specifies the order in which statements are executed. There are three types
of control structures. They are.
i. Sequence Control Structure
ii. Selection Control Structure
iii. Case Structure
Start
Process 1
Read radius
Process 2 S=3.14*r*r
Print S
Process n
Stop
IF Condition THEN
Process A
… IF
Condition
…
…
Process
END IF
2) IF….THEN…ELSE
• In this structure
o If the condition is true. It performs the process A.
o Else the condition is false. It executes process B.
• The process execution is depending on the condition.
Pseudo code Flow Chart
IF Condition THEN
Process A
IF
ELSE
Condition
Process B
Process A Process B
END IF
case Type-2:
Process 2
…
…
Process 1 Process 2 Process N
…
case Type-n:
Process n
END CASE
d) Functions
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data as INPUT, process it, and "return" a result as OUTPUT. Once a function is
written, it can be used over and over and over again. Functions can be "called" from the inside of
other functions. Functions "Encapsulate" a task (they combine many instructions into a single line
of code).
Ex:
>>>def add(num1,num2): #Function Definition
num3=num1+num2
print(“The sum is”,num3)
return num3
>>>a=10
>>>b=20
>>>c=add(a,b) #Function Call
Flow of a Function:
When a function is "called" the program "leaves" the current section of code and begins
to execute the first line inside the function. Thus the function "flow of control" is:
• The program comes to a line of code containing a "function call".
• The program enters the function (starts at the first line in the function code).
• All instructions inside of the function are executed from top to bottom.
• The program leaves the function and goes back to where it started from.
• Any data computed and RETURNED by the function is used in place of the function in
the original line of code.
Function Workspace
Every function has its own Workspace which means that every variable inside the function
is only usable during the execution of the function. After that we cannot use the variable. The
variables can be created inside the function or passed as an argument.
Ex:
READ num1, num2
result = num1 + num2
WRITE result.
Examples:
1. Write a pseudocode to find the area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
COMPUTE Area=pi*r*r
PRINT r
2. Write a pseudocode to find the biggest of two numbers
BEGIN
READ A, B
IF A>B
PRINT “B is big”
ELSE
PRINT “A is big”
3. Write a pseudocode for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89
BEGIN
INITIALIZE total=0,i=1
WHILE i<n
READ mark
total=total+mark
INCREMENT i
PRINT i
END
Flowchart
• A flow chart is a diagrammatic representation that illustrates the sequence of operations
to be performed to arrive the solution.
• Each step in the process is represented by a different symbol and has a short description
of the process steps.
• The flow chart symbols are linked together with arrows showing flow directions.
(or)
• Only one flow line should enter a decision symbol but two or three flow lines can leave.
Start Stop
• Write within standard symbols briefly. You can also use annotation symbol to describe
the data more clearly.
– – – Calculation Part
• If the flowchart becomes complex then it is better to use connector symbols to reduce the
number of flow lines.
• Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
• Flow Charts are better in communication.
• Flow Charts acts as a blue print during system analysis and program development phase.
• The maintenance of operating program becomes easy with the help of flow chart.
Disadvantages of Flow Chart:
• Sometimes the program logic is quite complicated, In that case flowchart becomes
complex and clumsy.
• If alterations are required the flowchart may require re-drawing completely.
• As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Example:
1. Draw a flowchart to find the area of circle.
Start
Read r
area=3.14*r*r
Print area
Stop
Start
Read a,b
If
yes No
a>b
Stop
Start
Read N
Total=0
i=1
Yes If No
i<n
Stop Total=Total+Mark
i=i+1
Define Compiler:
• A Compiler is a computer software that transforms computer code written in High Level
Programming Language into Machine Language (0,1) as well as vice versa.
Define Interpreter:
• An Interpreter translates a High Level Programming Language into an immediate form of
Machine Level Language. It executes instructions directly without compiling.
Define Assembler:
• An Assembler is used to convert the Assembly Language into an executable Machine
Level Language.
Define Computer Program:
• A Computer Program is a combination of Computer algorithm and a Programming
language. Most programs are English like languages.
• A Computer Program will solve the problem specified in the algorithm.
Algorithmic Problem Solving:
A sequence of steps involved in designing and analyzing an algorithm is shown in the
figure below.
Design an algorithm
Prove Correctness
Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and the
particular function is called again and again.
Examples:
Algorithm, Pesudocode, Flowchart for finding Factorial using Recursion
1. Algorithm to find the factorial of given number using recursion
Step1: Start
Step2: Read the value of n
Step3: Call factorial(n) and store the result in f
Step 4: Print the factorial f
Step5: Stop
Subprogram
Step1: Start factorial(n)
Step2: If n is equal to zero then return the value 1
else return n*factorial(n-1).
Sep 3: Stop factorial
Start Factorial(n)
Read n
Return
No if
n*factorial(n-1)
n==0
f =factorial(n)
yes
Print f Return 1
Stop
Stop
ILLUSTRATIVE EXAMPLES
Find Minimum in a list:
Algorithm:
Step1:Start
Step2:Read total number of elements in the list
Step3:Read the first element as E
Step4:MIN=E
Step5:SET i=2
Step6:If i>n goto Step 11 ELSE goto Step 7
Step7:Read ith element as E
Step8:if E < MIN then set MIN=E
Step9:i=i+1
Step10:goto Step 6
Step11:Print MIN
Step12:stop
Pseudocode
BEGIN
READ total number of elements in the list
Min= E I=2
IS I<N
Read I th Element as E
Is N
E<N
MIN=E
I=I+1
Print MIN
Stop
Position 0 1 2 3 4 5
Original list 4 6 9 10 11
7>11 4 6 9 10 11
7>10 4 6 9 10 11
7>9 4 6 9 10 11
7>6 4 6 7 9 10 11
Algorithm:
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1
Pseudocode
READ Number of element in sorted list as N
SET i=0
WHILE i<N
READ Sorted list element as List[i]
i=i+1
ENDWHILE
READ Element to be insert as X
SET i = N-1
WHILE i >=0 and X < List[i]
List[i+1] =List[i]
i=i–1
END WHILE
List[i+1] = X
Flow Chart
Start
Read no of element as E
i=0
i<N
Read x
i=N-1
i>=0 &&
X<List[i] N
List[i+1]=List[i]
i=i+1
List[i+1]=X
Stop
Pseudocode:
SET Count =0
READ Range as N
SELECT an RANDOM NUMBER from 1 to N as R
WHILE TRUE
READ User guessed Number as G
Count =Count +1
IF R== G THEN
BREAK
ELSEIF R<G THEN
DISPLAY “Guess is Too High”
ELSE
DISPLAY “Guess is Too Low”
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took
Count=0
Read range N
Count=Count+1
IS
Y
R==G
IS
N
R>G
Y
Print “Grade is too low”
Print count
Stop
An outline to solve this problem, from the starting pole, to the goal pole, using an
intermediate pole:
1. Move a tower of height-1 to an intermediate pole, using the final pole.
2. Move the remaining disk to the final pole.
3. Move the tower of height-1 from the intermediate pole to the final pole using the
original pole.
we can use the three steps above recursively to solve the problem.
Output:
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
END IF
END Procedure
Flow Chart for Tower of Hanoi Algorithm
Begin Hanoi(disk,source,dest,aux)
IS disk==1
Honai(disk-1,source,aux,dest)
Move disk from source to dest
Honai(disk-1,source,aux,dest)
Stop
WORKSHEETS
1.1 Draw a Flowchart and write a pesudocode to add two numbers.
Flowchart:
Pseudocode:
1. 2. Draw a Flowchart and write a pesudocode to find biggest between three numbers.
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
TWO MARKS
1. What is an algorithm? (University question)
Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for
completing a task. It is an English-like representation of the logic which is used to solve the
problem. It is a step- by-step procedure for solving a task or a problem. The steps must be ordered,
unambiguous and finite in number.
7. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
BEGIN
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
8. Give the rules for writing Pseudo codes.
o Write one statement per line.
o Capitalize initial keywords.
o Indent to show hierarchy.
o End multiline structure.
o Keep statements to be language independent
.
9. Give the difference between flowchart and pseudo code.
• Flowchart is a graphical representation of the algorithm.
• Pseudo code is a readable, formally English like language representation.
10. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is
drawn using boxes of different shapes with lines connecting them to show the flow of control. The
purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.
A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
20. Write an algorithm to accept two number. compute the sum and print the
result. (University question)
Step 1: Start
Step 2: READ the value of two numbers
Step 3:Compute sum of two numbers
Step 4 :Print the sum
Step 5:Stop
21. Write an algorithm to find the minimum number in a given list of numbers. (University
question)
• Step 1: Start
• Step 2:Read the total number of element in the list as N
• Step3:Read first element as E
• Step 4:MIN=E
• Step 5:Set i=2
• Step6:IF i>n goto Step 11 ELSE goto Step 7
• Step 7:Read i th element as E
• Step 8:IF E<MIN then set MIN=e
• Step 9:i=i+1
• Step 10:goto step 6
• Step 11:print MIN
• Step12:Stop
22. Outline the logic to swap the contents of two identifiers without using the third variable
(University question)
• Step1: Start
• Step 2:Read A,B
• Step 3 :A=A+B
• Step 4:B=A-B
• Step5:A=A-B
• Step 6:Print A ,B
• Step 7:Stop
UNIT 2
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points
1
Rohini College of Engineering and Technology GE3151
2
Rohini College of Engineering and Technology GE3151
Source code
Output
Python
data
Interpreter
Input data
3
Rohini College of Engineering and Technology GE3151
4
Rohini College of Engineering and Technology GE3151
5
Rohini College of Engineering and Technology GE3151
Data types
1. Complex 1. Strings
2. Integer
2. Tuples Dictionary
3. Floating
point 3. Lists
4. Boolean
Fig 2.3: List of data types in Python
Integer (type int)
An integer data type represents the whole numbers. It represents positive and negative
numbers. Integer data type have unlimited size in Python.
Example: -3, 2 etc
Types of integer data type:
i) Regular integer
ii) Binary literals (base 2)
iii) Octal literals (base 8)
iv) Hexa decimal literals (base 16)
6
Rohini College of Engineering and Technology GE3151
i) Regular integer
They are normal integers.
Example:
>>>a=9293
>>>b= -136
ii) Binary literals (base 2)
A binary literal is of the form zero followed by an uppercase B or lowercase b. The
literals are 0 and 1.
Example:
>>>bin=0b1111
>>>print(bin)
Output:
15
iii) Octal literals (base 8)
An octal literal is a number prefixed with zero followed by either uppercase O or lower
case o. The literals are 0 to 7.
Example:
>>>oct=0O24
>>>print(oct)
Output:
20
iv) Hexa decimal literals (base 16)
A hexa decimal literal is prefixed by 0(zero) followed by an upper case X or a lower case
x. The literals are 0 to9, [a-f/A-F].
Example:
>>>hex=0x9A
>>>print(hex)
Output:
154
7
Rohini College of Engineering and Technology GE3151
8
Rohini College of Engineering and Technology GE3151
>>>X+Y
+ Concatenation-Adds values of 2 strings
python program
>>>x[0:3]
[] Slice-Gives the character from the given range.
pyt
>>>x[1:2]
[:] Range slice-Give the characters from the given range.
y
9
Rohini College of Engineering and Technology GE3151
>>>print str[0:3]
Hel
>>>print str[5:]
Python
>>>print str*2
HelloPython HelloPython
>>>print str+”welcome”
HelloPython welcome
Lists
List data type contains elements of various data types. Values in a list are called elements
or items of list. The list is enclosed by square brackets [ ], where items are separated by commas.
List values can be accessed using slice operator ([] or [:]) .The index 0 represents beginning of
the list and -1 represents ending of the list.
list[0] represents beginning of list.
list[-1] represents ending of list.
Syntax:
listname= [value1,value2,…value n]
Example:
>>>mylist = [10, 10.5, ‘programming’]
Example Program:
>>>mylist= ()
>>>mylist=[‘python’,10,10.5,’program’]
>>>print mylist
[‘python’,10,10.5,’program’]
>>>print mylist[1:3]
[10, 10.5]
>>>print mylist[2:]
[10.5,’program’]
>>>print mylist*2
10
Rohini College of Engineering and Technology GE3151
[‘python’,10,10.5,’program’,’python’,10,10.5,’program’]
>>>print mylist[-1]
[‘program’]
VARIABLES
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
Rules for naming variables
Variable name can be any length.
They can contain both letters and numbers. But they cannot begin with numbers.
Both upper case and lower case letters are used.
Variable names are case sensitive.
Example: midname, midName, MidName are different variables.
Variable name cannot be any one of the keywords.
Assigning values to variables
The equal (=) sign is used to assign the values to variables.
Left of = operator is the name of the variable.
Right of = operator is the value of variable.
Example:
>>>X=5
>>>name=”Python”
>>>print X
5
>>>print name
Python
In the above program X and name are variables. The value of X is 5 and the value of name is
Python.
11
Rohini College of Engineering and Technology GE3151
EXPRESSIONS
Expression is a combination of values, variables, operators and operands. A value itself is
considered as an expression.
Example:
17 #expression
X #expression
x+17 #expression
Expression consists of combination of operators and operands.
Example:
5+ (8*k) #expression
The above expression consists of 2 sub expressions. That is 5 and (8*k).Here sub expression
(8*k) is evaluated first.
Evaluation of expressions:
When expression is typed at the prompt, the interpreter evaluates it, and finds the value of
expression.
Program:
>>>12+8 #expression
20
>>>n=100 #expression
>>>print(n) #expression
100
>>>100 #expression
100
STATEMENTS (or) I/O STATEMENTS
Statement is a section of code (or) instruction that represents a command (or) action.
Types of statements
i) Assignment statements
ii) Simultaneous assignment statements
iii) Input statements
iv) Print statements
12
Rohini College of Engineering and Technology GE3151
i)Assignment statements
Assignment statements assigns right of = symbol to left of = symbol.
Example:
>>>Name=’CSE’
>>>age=100
>>>Name
CSE
>>>age
100
ii) Simultaneous assignment statements
Simultaneous assignment statement is used to assign more number of values to more
variables simultaneously.
Example:
>>>x,y=10,20
>>>x
10
>>>y
20
>>>sum, diff=x+y, y-x
>>>sum
30
>>>diff
10
13
Rohini College of Engineering and Technology GE3151
CSE
100 -45 0
Here left side is a tuple of variable. The right side is a tuple of expression.
Working of tuple assignment
i) The first variable in the tuple of left side is assigned to first expression in tuple of right side.
ii) Similarly, the second variable in the tuple of left side is assigned to second expression in
tuple of right side. Number of variables on left side and the number of expressions on the right
side must be same.
Example: Program on tuple assignment
>>>#empty tuple
>>>mytuple=( )
>>>mytuple
()
>>>#tuples having same datatypes
>>>mytuple=(1,2,3,4,5)
>>>mytuple
(1, 2, 3, 4, 5)
>>>#tuples having different datatypes
>>>mytuple=(1,”Python”,2.5)
>>>mytuple
(1,”Python”, 2.5)
>>>#tuple assignment
>>>X, Y, Z= mytuple
>>>X
1
>>>Y
Python
>>>Z
2.5
15
Rohini College of Engineering and Technology GE3151
PRECEDENCE OF OPERATORS
Operator:
An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is
applied to be called operands. For e.g., in the expression 4 + 5, 4 and 5 are operands and + is an
operator. The following tokens are operators in Python:
+ - * ** / // %
Operator precedence:
When an expression contains more than one operator, precedence is used to determine
the order of evaluation. The order of evaluation depends on rules of precedence.
Rules of precedence
i) Parenthesis has the highest precedence.
Example: 5*(9-3)
Here expression in parenthesis is evaluated first.
5*(9-3) = 5 * (6) = 30
ii) Exponentiation has next highest precedence.
Example: 1+2**3
1+2**3 = 1 + 8 = 9
iii) Multiplication and division have next higher precedence than addition and subtraction.
Example: 3*2-1
3*2-1 = 6 – 1 = 5
iv) Operators with same precedence are evaluated from left to right (Except exponentiation).
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).
16
Rohini College of Engineering and Technology GE3151
The acronym PEMDAS is useful way to remember the rules. That is,
P (parenthesis first)
E (Exponent)
MD (multiplication and division)
AS (addition and subtraction)
Arithmetic evaluation is carried out using two phases from left to right. During the first phase
highest priority operators are evaluated. The second phase lowest priority operators are
evaluated.
Example:
6+4/2 is 8, not 5.
Example:
>>>X, Y, Z=2, 3, 4
>>>value=X-Y/3+Z*3-1
>>>print(“Result=”,value)
Result=12
COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Comment contains information for persons reading the program. Comment lines are
ignored during program execution. Comment lines have no effect on the program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment
Types of comments
i) Single line comments
ii) Multi line comments
i) Single line comments - Single line comments describes information in one line(short),and
they start with the symbol #.Everything from the # to the end of the line is ignored, it has no
effect on the execution of the program.
18
Rohini College of Engineering and Technology GE3151
Example:
>>>#This is a print statement
>>>print(“Hello python”)
Hello python
ii) Multi line comments - Multi line comments describes information in detail. Here, more than
one line of comments can be added to the program in between the triple quotes(“ ” ”).
Example:
”””This is print statement
This line print “Hello python”
Written by ABC, April 2017”””
DEBUGGING
Possible errors with Variables:
1. Variable names can contain both letters and numbers. But they cannot begin with
numbers.
2. Both upper case and lower-case letters can be used.
3. Variable names are case sensitive. For example, midname, midName, MidName are
different variables.
4. Variable name cannot be any one of the keywords.
5. Variable names cannot have space in between.
i) Syntax Error:
The text of the program does not comply with the rules of the language is known as a
syntax error. For syntax errors, the error messages don’t help much. The most common messages
are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very
informative. The syntax error you are most likely to make is:
1. An illegal variable name, like class and yield, which are keywords.
2. Variable names such as odd~job and US$, which contain illegal characters.
3. If you put a space in a variable name, Python thinks it is two operands without an
operator:
>>> bad name = 5
SyntaxError: invalid syntax
19
Rohini College of Engineering and Technology GE3151
ILLUSTRATIVE PROGRAMS
Exchange the values of two variables Swap
- Without using temp function:
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
20
Rohini College of Engineering and Technology GE3151
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
Enter the second number: 10
Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
Swap - Using temp function:
n1=input (“Enter the value of a:”)
n2=input (“Enter the value of b:”)
print (“Before Swap:”)
print (“Value of a:”,n1)
print (“Value of b:”,n2)
temp =n1
n1=n2
n2=temp
print(“After Swap:”)
print(“Value of a:”,n1)
print(“Value of b:”,n2)
Output:
Before Swap:
Value of a: 10
Value of b: 15
After Swap:
21
Rohini College of Engineering and Technology GE3151
Value of a: 15
Value of b: 10
Circulate the values of n variables
def rotate(L,n):
newlist=L[ n: ]+L[ :n ]
return newlist
list = [1,2,3,4,5]
print(“The original list is:”,list)
mylist=rotate(list,1)
print(“List rotated clockwise by 1:”,mylist)
mylist=rotate(list,2)
print(“List rotated clockwise by 2:”,mylist)
mylist=rotate(list,3)
print(“List rotated clockwise by 3:”,mylist)
mylist=rotate(list,4)
print(“List rotated clockwise by 4:”,mylist)
Output:
The original list is: [1, 2, 3, 4, 5]
List rotated clockwise by 1: [2, 3, 4, 5, 1]
List rotated clockwise by 2: [3, 4, 5, 1, 2]
List rotated clockwise by 3: [4, 5, 1, 2, 3]
List rotated clockwise by 4: [5, 1, 2, 3, 4]
Distance between two points
import math
def distance(x1,y1,x2,y2):
dx=x2 - x1
dy=y2 - y1
dsquare=dx**2 - dy**2
result=math . sqrt(dsquare)
return result
22
Rohini College of Engineering and Technology GE3151
23
Rohini College of Engineering and Technology GE3151
Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.
values the operator is applied to are called operands. For eg, in the expression 4 + 5, 4 and 5 are
operands and + is an operator.
5. What is the difference between * operator and ** operator?
* is a multiplication operator which multiplies two operands.
Example: 3*2 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Example: 3**2 returns 9.
6. Compare arguments and parameters.
Arguments Parameters
1.It is the value, which is given to 1.It is the name, which is given in
function call. function definition.
2.Syntax: 2.Syntax:
functionname(arguments) def functionname(parameter):
25
Rohini College of Engineering and Technology GE3151
26
Rohini College of Engineering and Technology GE3151
27
Rohini College of Engineering and Technology GE3151
26. State the reason to divide programs into functions. (JANUARY 2019)
Creating a new function gives an opportunity to name a group of statements, which makes
program easier to read and debug. Functions can make a program to smaller by eliminating the
repeated code.
27. Compare interpreter and compiler. What type of translator is used for Python?
(JANUARY 2020)
Interpreter - Translates program one statement at a time Compiler - Translates program one
statement at a time. Python uses interpreter as a translator
28. Write a python program to print sum of cubes of the values of n variables.
(JANUARY 2020)
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+i**3
print(sum)
29
Rohini College of Engineering and Technology GE3151
30
Rohini College of Engineering and Technology GE3151
1.Explain how to write and execute a program in python illustrate the steps for writing a python
program to check whether the number is palindrome or not.
2. Formulate with an example program to pass the list arguments to a function.
3. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii) sum
of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple vii)
Compare two tuples viii) printing two tuples of different data types.
4. Formulate with an example program to find out all the values in the list that is greater than the
specified number.
5. Write a program to find out the square root of two numbers.
31
Rohini College of Engineering and Technology GE3151
Additional Programs
1. Python program to calculate the average of numbers in a given list.
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter the element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter the element: 23
Enter the element: 45
Enter the element: 56
Average of elements in the list 41.33
2. Python program to exchange the values of two numbers without using a temporary
variable.
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
32
Rohini College of Engineering and Technology GE3151
Output:
Enter the lower limit for the range:1
Enter the upper limit for the range:16
1
3
5
7
9
11
13
15
9. Python program to find the sum of digits in a number.
n=int(input("Enter the number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter the number:1892
The total sum of digits is: 20
10. Python program to count the number of digits in a number
n=int(input("Enter the number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
36
Rohini College of Engineering and Technology GE3151
Output:
Enter the number:123
The number of digits in the number are: 3
11. Python program to check if a number is a palindrome.
n=int(input("Enter the number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not a palindrome")
Output:
Enter the number:121
The number is palindrome
12. Python program to take the temperature in Celsius and convert it to Fahrenheit.
Celsius=int(input("Enter the Temperature in Celsius:"))
f=(Celsius*1.8)+32
print("Temperature in Fahrenheit is:",f)
Output:
Enter the Temperature in Celsius:32
Temperature in Fahrenheit is: 89.6
37
Problem Solving and Python Programming GE3151
CHAPTER 3
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values, parameters, local and global scope, function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum an array of numbers, linear search, binary search.
101
Problem Solving and Python Programming GE3151
102
Problem Solving and Python Programming GE3151
3.1 CONDITIONALS
3.1.1 Boolean values and operators
Boolean values:
Boolean data types have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keywords. Boolean values are used in comparisons and conditional
expressions. The most common way to produce boolean value is relational operators.
103
Problem Solving and Python Programming GE3151
+ Addition
- Subtraction
* Multiplication
/ Division
Example Program:
x=5
y=5
print(“x+y=”,x+y)
print(“x-y=”,x-y)
print(“x*y=”,x*y)
104
Problem Solving and Python Programming GE3151
print(“x/y=”,x/y)
print(“x%y=”,x%y)
print(“x//y=”,x//y)
Output:
x+y=30
x-y=20
x*y=125
x/y=5.0
x%y=0
x//y=5
ii) Comparison (Relational) operators
Comparison operators are used to compare values. It either returns True or False according
to the condition.
== Equality
!= Not equal to
> Greater than
< Less than.
>= Greater than or equal to
<= Less than or equal to
Example Program:
x=10
y=20
print(“x>y=”,x>y)
print(“x<y=”,x<y)
print(“x==y=”,x==y)
print(“x!=y=”,x!=y)
105
Problem Solving and Python Programming GE3151
print(“x>=y=”,x>=y)
print(“x<=y=”,x<=y)
Output:
x>y=False
x<y=True
x==y=False
x!=y=True
x>=y=False
x<=y=true
iii) Assignment operators
Assignment operators are used in Python to assign values to variables.
Operator Description
106
Problem Solving and Python Programming GE3151
Example Program:
x=True
y=False
print(“x and y=”,x and y)
print(“x or y=”,x or y)
print(“not x=”,not x)
Output:
x and y=False
x or y=True
not x=False
v) Bitwise operators
Bitwise operators are used to perform bit-level operations which makes processing faster.
107
Problem Solving and Python Programming GE3151
Example Program:
x=2
y=3
print(“x&y=”,x&y)
Output:
x&y=2
vi) Membership operators
It evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
and dictionary or not.
To check particular element is available in the list or not.
The membership operators are in and not in.
Operator Description
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
vii) Identity operators
They are used to check if two values (or variables) are located on the same part of the
memory.
Operator Description
is True if the operands are identical(refer to the same object)
108
Problem Solving and Python Programming GE3151
is not True if the operands are not identical(do not refer to the same
object)
Example:
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y)
print(a is b)
Output:
False
True
3.1.3 Conditional Statements
i)Conditional if
If conditional is a decision making statement. It is always used with condition. It executes
code only if condition is satisfied.
syntax:
if condition:
statements
Flowchart:
False
condition
True
statements
109
Problem Solving and Python Programming GE3151
True False
if
condition
110
Problem Solving and Python Programming GE3151
111
Problem Solving and Python Programming GE3151
112
Problem Solving and Python Programming GE3151
default statements
Flowchart:
False
Condition
True
True
False
Statement 1 Condition
True False
Statement 2 Condition
True
113
Problem Solving and Python Programming GE3151
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
Output:
enter a value:1
enter b value:0
enter c value:0
same and real roots
3.2 ITERATION/CONTROL STATEMENTS/LOOPING STATEMENTS
Iteration means repetition of loop until base condition is false. Repeated execution of set of
statements is called as iteration.
state
while
for
break
continue
pass
3.2.1 State
It is possible to have more than one assignment for the same variable. Reassignment
replaces existing value with new value.
Example Program1:
>>>x=10
>>>y=17
>>>print x
10
>>>x=18
114
Problem Solving and Python Programming GE3151
>>>print x
18
Example Program2:
>>>x=10
>>>y=176
>>>x=8
>>>print x
8
3.2.2 While loop
While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
Flowchart:
False
Condition
True
Body of while
statements
115
Problem Solving and Python Programming GE3151
116
Problem Solving and Python Programming GE3151
Factorial is 125
for in sequence:
The for loop in Python is used to iterate over a sequence (list, tuple, string).. Loop
continues until we reach the last element in the sequence.
Syntax:
for loopvariable in sequence:
Body of for statements
Flowchart:
False
Condition
Body of for
statements
R
for i in "Ramu": A
1. For loop in string
print(i) M
U
for i in [2,3,5,6,9]: 2
2. For loop in list
print(i) 3
117
Problem Solving and Python Programming GE3151
5
6
9
2
for i in (2,3,1):
3. For loop in tuple 3
print(i)
1
3.2.4 Break
Break statements can alter the flow of a loop. It terminates the current loop and executes
the remaining statement outside the loop.
Syntax:
i) while loop
while(condition):
if(condition):
break
ii) for loop
for loop variable in sequence:
if(condition):
break
Flowchart:
condition
a
True
Break?
Body of loop
118
Problem Solving and Python Programming GE3151
Example Program:
for i in "welcome":
if(i=="c"):
break
print(i)
Output:
w
e
l
3.2.5 Continue
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
i) while loop
while(condition):
if(condition):
continue
ii) for loop
for loopvariable in sequence:
if(condition):
continue
Flowchart:
condition
Continue
Body of loop
119
Problem Solving and Python Programming GE3151
Example Program:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
3.2.6 Pass
It is a null statement, nothing happens when it is executed.
Syntax:
pass
Example Program:
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output:
w
e
l
c
o
120
Problem Solving and Python Programming GE3151
m
e
1 It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
2 syntax: syntax:
break continue
3 for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
4 w w
e e
l l
o
m
e
Void function:
A function that does not return any value is called void function.
Example 1:
print(“Hello”)
Example 2:
def add():
a=10
b=20
c=a+b
print(c)
add()
3.3.1 Return values
Return statement may or may not send back any value to main program. The return
statement is also used to exit a function and go back to place where it was called, return keywords
are used to return the values from the function.
Syntax:
return(expression)
Types of parameters/arguments:
i) Required/positional parameters
ii) Keyword parameters
iii) Default parameters
iv) Variable length parameters
122
Problem Solving and Python Programming GE3151
student( “Aarika”):
a=50
def add():
b=20
c=a+b Global variable
print(c) 70
def sub():
b=30
Local variable
c=a-b
print(c) 20
123
Problem Solving and Python Programming GE3151
print(a) 50
124
Problem Solving and Python Programming GE3151
else:
return n*fact(n-1)
n=int(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
Output:
enter no. to find fact:5
Fact is 120
3.4 STRINGS
String is defined as sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “ ). An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative). A index starts from 0 to n-1. Strings
are immutable i.e. the contents of the string cannot be changed after it is created.
String operators/operations:
i) Indexing
ii) Slicing
iii) Concatenation
iv) Repetition
v) Membership
vi)Comparision
i) Indexing
Positive indexing helps in accessing the string from the beginning. Negative subscript helps
in accessing the string from the end.
>>>a=”HELLO HAI”
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>I
ii) Slicing
125
Problem Solving and Python Programming GE3151
The slice[start : stop] operator extracts sub string from the strings. A segment of a string
is called a slice.
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO
iii) Concatenation
The + operator joins the text on both sides of the operator.
a=”save”
b=”water”
>>>print(a+b)
savewater
iv) Repetition
The * operator repeats the string on the left hand side times the value on right hand side.
a=”python”
>>>print(3*a)
pythonpythonpython
v) Membership
Using membership operators to check a particular character is in string or not. Returns
true if present
>>> s="good morning"
>>>"m" in s
True
>>> "a" not in s
True
vi)Comparison
The strings can be compared using relational operators.
>>>msg1=”Good”
>>>msg2=”Good”
>>>msg1==msg2
True
126
Problem Solving and Python Programming GE3151
3.4.2 Immutability
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
127
Problem Solving and Python Programming GE3151
128
Problem Solving and Python Programming GE3151
in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example Program:
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
Output:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
/:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
import array
Syntax to create array:
arrayname = modulename.functionname(‘datatype’,[elements])
Example:
a=array.array(‘i’,[1,2,3,4])
Here,
a- array name
array- module name
i- integer datatype
131
Problem Solving and Python Programming GE3151
132
Problem Solving and Python Programming GE3151
133
Problem Solving and Python Programming GE3151
sum=0
for i in a:
sum=sum+i
print("The total is",sum)
Output:
The total is 35
3.5.5 Linear search
mylist=[11,23,38,40,52,63,78,98,29,45]
print(mylist)
x = int(input("Enter number to search: "))
found=False
for i in range(len(mylist)):
if(mylist[i] == x):
found=True
print ("Element found at position:",i+1)
break
if(found==False):
print "Element not found"
Output:
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 78
(‘Element found at position:’ 7)
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 2
Element not found
3.5.6 .Binary search
def bsearch(list,x):
first = 0
last= len(list)-1
134
Problem Solving and Python Programming GE3151
while (first<=last):
midpoint= (first+ last)//2
if x==list[midpoint]:
return midpoint
elif(x<list[midpoint]):
last=midpoint-1
else:
first= midpoint+1
return -1
list=[10,20,30,40,50]
print("Original list is:",list)
x=input("Enter the element to be searched:")
pos=bsearch(list,x)
if(pos!=-1):
print “Element found at the position:”,pos
else:
print “Element not found”
Output:
Original list is:[10,20,30,40,50]
Enter the element to be searched:30
Element found on position:2
Original list is:[10,20,30,40,50]
Enter the element to be searched:60
Element not found
135
Problem Solving and Python Programming GE3151
The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
If statement:
The syntax of if statement is:
Syntax:
if
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens.
137
Problem Solving and Python Programming GE3151
138
Problem Solving and Python Programming GE3151
Example:
def factorial(n):
if n == 1:
139
Problem Solving and Python Programming GE3151
return 1
else:
return n * factorial(n-1)
14. Explain global and local scope.
The scope of a variable refers to the places that we can see or access a variable. If we define
a variable on the top of the script or module, the variable is called global variable. The variables
that are defined inside a class or function is called local variable.
Example:
def my_local():
a=10
print(“This is local variable”)
Example:
a=10
def my_global():
print(“This is global variable”)
15. Compare string and string slices.
A string is a sequence of character.
Example:
fruit = ‘banana’
String slices:
A segment of a string is called string slice, selecting a slice is similar to selecting a
character.
Example:
>>> s =' Pythonprogram'
>>> print s[0:5]
pytho
>>> print s[6:12]
progra
140
Problem Solving and Python Programming GE3151
Example:
a = “foo”
b=a
a=a+a
print a
print b
Output:
foofoo
foo
It is observed that ‘b’ hasn’t changed even though ‘a’ has changed.
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string
18. What are string methods?
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper()
>>> word = 'lion'
>>> new_word = word.upper()
>>> print new_word
LION
141
Problem Solving and Python Programming GE3151
25. Write a program to accept two number,multiply them and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
val1=int(input())
val2=int(input())
prod=val1*val2
print(“product is:”,prod,”\n”)
26. Write a python program to accept two numbers, find the greatest and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
num1=input()
num2=input()
number1=int(num1)
number2=int(num2)
if number1>number2:
Largest=number1
else:
Largest=number2
print(“largest number is:”,largest)
27. Present the flow of execution for a while statement. (JANUARY 2019)
While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
28. Define recursion with example. (JANUARY 2019)
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
143
Problem Solving and Python Programming GE3151
29. Do loop statements have else clause? When will it be executed? (JANUARY 2020)
Yes. Loop’s else part runs if no break occurs and the condition is false
30. Write a program to display a set of strings using range () function. (JANUARY 2020)
144
Problem Solving and Python Programming GE3151
145
Problem Solving and Python Programming GE3151
see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
i) Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with the
given lengths. (4)
ii) Write a function that prompts the user to input three stick lengths, converts them to integers,
and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii) Write a python program to generate all permutations of a given string using built-in
functions. (8) (JANUARY 2020)
19.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10) (JANUARY 2020)
146
Problem Solving and Python Programming GE3151
1. Write a python program to design simple calculator performing arithmetic functions like
addition, subtraction, multiplication and division with the input given by user.
2. Create a program for linear search using Arrays
3. Illustrate a program to find GCD of m and n.
4. How to find the square root of a number using newton’s method
5. Write a python program to sum an array of numbers
6. Write a python program for student mark system.
7. Write a python program greatest of three numbers.
147
Problem Solving and Python Programming GE3151
CHAPTER 4
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing - list comprehension; Illustrative programs: selection sort, insertion sort,
mergesort, histogram.
151
Problem Solving and Python Programming GE3151
152
Problem Solving and Python Programming GE3151
4.1 LIST
List contain elements of various data types, the list is enclosed by square brackets where
elements are separated by commas. The values in a list are called elements or items. A list within
another list is called nested list.
List values can be accessed using slice operator ([] or [:])
list[0] represents beginning of list
list[-1] represents ending of list
Syntax:
listname=[value1,value2,…value n]
Example :
>>>mylist = [10,10.5, ‘programming’]
Example program for creating lists:
list1 = [‘Rama’, ‘Delhi’, 2018]
list2 = [10, 20, 30, 40, 50]
list3 = []
list4 = [‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
print list1
print list2, list3
print list4
Output:
[‘Rama’, ‘Delhi’, 2018]
[10, 20, 30, 40, 50] [ ]
[‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
Creating list:
i) The simplest way to create a list is enclose the elements in square brackets([])
nlist =[10,20,30,40]
slist =[“Hai”, “Python”]
ii) A list that contains no element is called an empty list. It can be created with empty brackets [].
elist = []
153
Problem Solving and Python Programming GE3151
154
Problem Solving and Python Programming GE3151
3
>>>a[-1]
3
156
Problem Solving and Python Programming GE3151
iv) Membership
There are 2 membership operators in python programming.
i) in - Returns true if value is in list, returns false if value is not in list.
ii) not in - Returns true if value is not in list, returns false if value is in list.
Example:
>>>a= [1,2,3]
>>>1 in a
True
>>>4 in a
False
>>>3 not in a
False
4.1.2 List slices
A segment of list is called as list slice. The list elements can be accessed using the slice
operator ([]). Slice operator [n:m] returns a part of list from nth element to mth element , including
first and excluding last.
If the first index is omitted, the slice starts at the beginning of the string. If the second index
is omitted, the slice goes to the end of the string. If the first index is greater than or equal to the
second, the slice is an empty string. If both indices are omitted, the slice is a given string itself.
Syntax:
listname [start: finish -1]
Example:
>>>mylist=[‘Python’,10,10.5,’program’]
>>>mylist[0]
‘Python’
>>>mylist[1]
10
>>>mylist[2]
10.5
157
Problem Solving and Python Programming GE3151
>>>mylist[3]
‘program’
>>>mylist[0:3]
[‘Python’,10,10.5]
>>>mylist[1:3]
[10, 10.5]
>>>mylist[:3]
[‘Python’,10,10.5]
>>>mylist[:]
[‘Python’,10,10.5,’program’]
>>>mylist[1:]
[10,10.5,’program’]
mylist
python 10 10.5 program
0 1 2 3
mylist[0] -> element in 0th position.
mylist[-1] -> element in ending of list
mylist[0:3] -> Starting from 0th position to 2nd position
mylist[1:] -> ending position is not given , so 1st position to ending of list
mylist[:] -> beginning to ending of list.
4.1.3 List methods
Python provides a set of list methods. They are
i) append()
ii) extend()
iii) sort()
iv) reverse()
v) pop()
vi) clear()
vii) index()
viii) count()
158
Problem Solving and Python Programming GE3151
ix) insert()
x) remove()
xi) copy()
i) append()
Adds element to the end of specified list and does not return any value.
>>>a =[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]
ii) extend()
This method add all elements of list to another list.
>>>a= [1,2,3]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()
This method sorts elements in list.
>>>a= [3,1,2]
>>>a.sort()
>>>a
[1,2,3]
iv) reverse()
This method reverse the elements in a list.
>>>a =[1,2,3]
>>>a.reverse()
>>>a
[3,2,1]
159
Problem Solving and Python Programming GE3151
v) pop()
This method removes and returns an element at the given index. If the index is not given,
it removes and returns the last element on the list.
Example:
list=[“eng”,”chem”,”python”,”maths”]
>>>list.pop(2)
python
>>>list
[“eng”,”chem”,”maths”]
>>>list.pop()
[“eng”,”chem,’python”]
vi) clear()
This method clear elements in a list.
>>>a= [1,2,3]
>>>a.clear()
>>>print(a)
[]
vii) index()
This method returns index of given element. If the element is not in the list it returns
error.
>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()
160
Problem Solving and Python Programming GE3151
listname.count(value)
161
Problem Solving and Python Programming GE3151
ix) insert()
It inserts an element on a desired position of a list.
Syntax:
listname.insert(index,element)
>>>a=[1,2,3]
>>>a.insert(1,4)
>>>a
[1,4,2,3]
x) remove()
It removes the specified element from the list.
>>>a=[1,2,3]
>>>a.remove(2)
>>>print(a)
[1,3]
xi) copy()
listname.copy()
List functions:
i) len()
ii) max()
iii) min()
iv) cmp()
v) sum()
vi) sorted()
160
Problem Solving and Python Programming GE3151
161
Problem Solving and Python Programming GE3151
>>>a= [1,2,3,4]
>>>len(a)
4
ii) max(): Returns maximum value from the list .
>>>a= [1,2,3,4]
>>>max(a)
4
iii) min(): Returns minimum value from list.
>>>a= [1,2,3,4]
>>>min(a)
1
iv) cmp(): Compares the elements of lists.
>>>list1 = [123, 'xyz']
>>>list2 = [456, 'abc']
>>>print cmp(list1, list2)
-1
>>>print cmp(list2, list1)
1
>>>list3 = list2 + [786];
>>>print cmp(list2, list3)
-1
v) sum(): It returns the sum of all elements in a list.
>>>a= [5,10,15,5,4]
>>>sum(a)
39
vi) sorted(): Returns the sorted list of elements in ascending order.
>>>a= [4,3,2,1]
>>>sorted(a)
[1,2,3,4]
162
Problem Solving and Python Programming GE3151
163
Problem Solving and Python Programming GE3151
data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
>>>data[1][1]
0
>>>data[2][2]
0
>>>data[1][1]
8
>>>data[2][2]
7
>>>data[1][1]
8
>>>data[2][2]
7
>>>data
[0,0,0],[0,8,0],[0,0,0],[0,0,0],[0,0,0]
4.1.6 List aliasing
List aliasing is defined as circumstance where two (or) more variables refer to the same object.
Example:
>>>a=[1,2,3]
>>>b=a
>>>b is a
True
>>>b is not a
False
In this example, a is assigned to b then both variables refers to same objects.
a
[1,2,3]
b
164
Problem Solving and Python Programming GE3151
Here, the same list has two different names (‘a’ and ‘b’).so it is aliased.
If the aliased object is mutable, modifications done in one object affect the other object also.
Aliasing with mutable object:
Lists are mutable (changeable)
Example:
>>>a=[1,2,3]
` >>>b=a
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=10
>>>a
[10,2,3]
>>>b
[10,2,3]
4.1.7 Cloning list
Assignment statements in Python do not copy objects. They simply create bindings between
two objects. For mutable sequences (like lists), a copy of an existing object may be required so
that one object can be changed without affecting another. In lists, cloning operation can be used to
create a copy of an existing list so that changes made in one copy of list will not affect another.
The copy contains the same elements as the original. This can be done using
i) list() function
ii) copy() function
iii) copy.deepcopy() function
i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)
165
Problem Solving and Python Programming GE3151
Example:
>>>a= [1,2,3]
>>>b= list(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=4
>>>a
[4,2,3]
>>>b
[1,2,3]
ii) copy() function
copy.copy() is little slower than list() since it has to determine data type of old list first.
Syntax:
newlistname= copy.copy(oldlistname)
Example:
>>>import copy
>>>a= [1,2,3]
>>>b= copy.copy(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
iii) copy.deepcopy() function
copy.deepcopy() is the slowest and memory-consuming method.
Syntax :
newlistname = copy.deepcopy(Oldlistname)
Example Program1:
import copy
166
Problem Solving and Python Programming GE3151
167
Problem Solving and Python Programming GE3151
Here list passed as parameter to function (circulate), this list is circulated based on value the value.
4.1.10 Deleting list elements
To remove a list element, del operator can be used if an element to be deleted is known.
In the following code, the element ‘Chennai’ is deleted by mentioning its index in the del operator.
Example Program:
stulist = [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
Now the list is : [‘Rama’, 2018, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
4.2 TUPLES
Tuple is a collection sequence of values of different types. Unlike lists, tuple values are
indexed by integers. The important difference is that tuples are immutable. Tuples are created
using parenthesis (). The important points to be noted are
i) The values in tuples can be any type and they are indexed by integers
ii) A type is a comma-seperated list of values.
Example:
>>>t=’a’,’b’,’c’,’d’,’e’
Creation of tuples:
i) Create a tuple with a single element.
>>>t1= ‘a’
>>>type(t1)
<class ‘tuple’>
>>>t2=(‘a’)
>>>type(t2)
168
Problem Solving and Python Programming GE3151
<class ‘str’>
ii) A tuple can be created using the built-in function tuple. It can create an empty tuple
with no argument.
>>>t= tuple()
>>>t
()
iii) A tuple built-in- functions can be used to create a tuple with sequence of arguments.
>>>t= tuple(‘computer’)
>>>t
(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Operators on tuple:
i) Bracket operator
ii) Slice operator
iii) Relational operator
i) Bracket operator
Bracket operator indexes an element.
>>>t= (‘c’,’o’,’m’,’p’)
>>>t[0]
‘c’
>>>t[3]
‘p’
ii) Slice operator
Slice operator selects a range of elements.
>>>t[0:3]
(‘c’,’o’,’m’)
iii) Relational operator
The relational operators work with tuples and other sequences.
Python starts by comparing the first element from each sequence.
If they are equal, it goes on to the next elements and so on, until it finds elements that
differ.
169
Problem Solving and Python Programming GE3151
170
Problem Solving and Python Programming GE3151
The right side can be any kind of sequence (string, list or tuple).
Example:
To split an email address into a username and a domain consider the following
>>>addr=’[email protected]’
>>>uname,domain= addr.split(‘@’)
Here split is a keyword, the return value from split is a list with two elements and the first
element is assigned to username, the second to domain
>>>uname
‘effie’
>>>domain
‘python.org’
4.2.2 Tuples as return values
A function can return only one value, but if the value is a tuple, it can return multiple values.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient
and the remainder. Here the type of returning a values are
i) It can store the result as a tuple.
>>>t= divmod(13,4)
>>>t
(3,1)
ii) To store the elements separately, use tuple assignment.
>>>Q,R= divmod(13,4)
>>>Q
3
>>>R
1
iii) A function can return a tuple. The built-in function def minmax(t) is used to find the
largest and smallest elements of a sequence and can return a tuple of two values.
def minmax(t):
return min(t),max(t)
170
Problem Solving and Python Programming GE3151
max and min are built-in functions that find the largest and smallest elements of the
sequence.
minmax computes both the largest and smallest elements and returns a tuple of two
values.
Example Program:
>>>def minmax(t):
return min(t), max(t)
>>>minmax([6,3,7,12])
(3,12)
>>>minmax(‘abcd’)
(‘a’,’d’)
4.2.3 Accessing values
To access the tuple elements slicing (bracket operator [ ]) operator along with index or
indices is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
t2 = (1, 2, 3, 4, 5, 6, 7 );
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print “tup1[0]: “, tup1[0]
print “tup1[1]: “, tup1[1]
print “tup2[1:5]: “, tup2[1:5]
print “tup2[1:]: “, tup2[1:]
print t[0]
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a
171
Problem Solving and Python Programming GE3151
172
Problem Solving and Python Programming GE3151
Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is
replaced by ‘A’.
4.2.6 Built-in functions with tuple
The built-in functions with tuples are given below.
i) all(): Return True if all elements of the tuple are true (or if the tuple is empty).
ii) any():Return True if any element of the tuple is true. If the tuple is empty, return False.
iii) enumerate():Return an enumerate object. It contains the index and value of all the items of
tuple as pairs.
iv) len():Return the length (the number of items) in the tuple.
v) max():Return the largest item in the tuple.
vi) min():Return the smallest item in the tuple
vii) sorted():Take elements in the tuple and return a new sorted list (does not sort the tuple
itself).
viii) sum():Return the sum of all elements in the tuple.
4.2.7 Comparing tuples
With relational operators it is possible to work with tuples and other sequences. To compare
two elements, Python starts by comparing the first element from each sequence. If the elements
are equal, it goes on to the next elements, and so on, until it finds an element that is different,
subsequent elements are not considered (even if they are really big)
>>> (0, 1, 2) < (0, 3, 4)
True
4.3 Dictionaries
Dictionary is a collection that shows values along with key,the sequence of such key and
value pair is separated by commas, these pairs are sometimes called entries or items,all the entries
are enclosed by {}.A colon seperates key and its values.
Dictionaries in Python are implemented using hash table. It is an array whose indexes
are obtained using a hash function on the keys.
173
Problem Solving and Python Programming GE3151
174
Problem Solving and Python Programming GE3151
i) dict()
ii) dict(s)
iii) len()
iv) max()
v) min()
vi) all()
vii) sorted()
viii) any()
ix) pop()
x) copy()
xi) key()
xii) values()
xiii) update()
xiv) clear()
i) dict() : It creates a new, empty dictionary.
>>>cse=dict()
>>>cse
{}
ii) dict(s): It creates a new dictionary with key-value.
>>>cse=dict(s)
iii) len(): It counts the number of key value pairs.
>>>cse={‘name’:’ABC’,’age’:20}
>>>len(cse)
2
iv) max(): It returns the maximum key in dictionary.
>>>max(xse)
2
v) min(): It returns the minimum key in dictionary.
>>>min(cse)
1
175
Problem Solving and Python Programming GE3151
176
Problem Solving and Python Programming GE3151
177
Problem Solving and Python Programming GE3151
value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value. There is no direct
method to handle reverse lookup. The following function takes a value and returns the first key
that map to that value.
Example Program:
def getvalue(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print getvalue(squares,4)
Output:
2
4.3.6 Inverting a dictionary
A dictionary can be inverted with list values. For example, if you were given a dictionary
that maps from child to parent, you might want to invert it; that is, create a dictionary that maps
from parent to children. Since there might be several children with the same parent each value in
the inverted dictionary should be a list of children.
Example Program:
def invertdict(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = { ‘child1’: ‘A1’,
‘child2’: ‘A1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}
178
Problem Solving and Python Programming GE3151
print invertdict(d)
Output:
{‘parent2’: [‘child3’, ‘child4’], ‘A1’: [‘child1’, ‘child2’]}
4.4 ADVANCED LIST PROCESSING
.The list comprehension is the advanced list processing is given below.
4.4.1 List comprehensions
List comprehension is an elegant and concise way to create new list from existing list in
python. List comprehension process is described by series of keywords.
Syntax:
[expression for item in list if conditional]
newlist is the resultant list. expression (i) is based on the variable used for each element in the
old list. If needed filter can be applied using if statement.
A list comprehension consists of the following parts:
i) An input sequence.
ii) Variable representing members of the input sequence.
iii) An optional predicate expression.
iv) An Output expression producing elements of the output list from members of the
input sequence that satisfy the predicate.
Example Program1:
>>>a=[11,22,33,44]
>>>b=[x*2 for x in a]
>>>b
[22,44,66,88]
179
Problem Solving and Python Programming GE3151
Example Program2:
>>>names=[‘alice’,’bob’,’charly’]
>>>b=[ x.upper() for x in names]
[‘ALICE’,’BOB,’CHARLY]
>>>c=[x.capitalize() for x in names]
>>>c
[‘Alice’,’Bob’,’Charly’]
Example Program3:
>>>vowels=(‘a’,’e’,’i’,’o,’u’)
>>>t=’hello’
>>>[c for c in t if c in vowels]
[‘e’,’o’]
Example Program4:
>>>a=[1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
Example Program5:
>>>a= [10,5,0,-5,-10]
>>>[x for x in a if x>0]
[10,5]
>>>[x for x in a if x<0]
[-5,-10]
180
Problem Solving and Python Programming GE3151
a[position]=a[position-1]
position=position-1
a[position]=currentvalue
list=[50,60,40,30,20,70]
print( “Original list is:”,list)
insertionsort(list)
print(”List after insert:”,a)
Output:
Original list is: =[50,60,40,30,20,70]
List after insert:[20,30.40,50,60,70]
181
Problem Solving and Python Programming GE3151
left=a[:mid]
right=a[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1
list=[50,60,40,20,70,100]
print ("Original list is:" ,list)
mergesort(list)
print ("Sorted list is:",list)
Output:
Original list is: [50, 60, 40, 20, 70, 100]
182
Problem Solving and Python Programming GE3151
183
Problem Solving and Python Programming GE3151
184
Problem Solving and Python Programming GE3151
185
Problem Solving and Python Programming GE3151
186
Problem Solving and Python Programming GE3151
187
Problem Solving and Python Programming GE3151
188
Problem Solving and Python Programming GE3151
29. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (JANUARY 2019)
def reverse_lookup(d,v):
for k in d:
if d[k]==v:
return k
raise Value Error
30. How will you update list items? Give one example. (JANUARY 2020)
List will be updated using index value.
Example:
>>>a=[1,2,3]
>>>a[0]=10
>>> print(a)
[10,2,3]
31. Can function return tuples? If yes give example. (JANUARY 2020)
Yes function return tuples.
Example:
def add(a,b)
return(a+b)
add(3,2)
189
Problem Solving and Python Programming GE3151
190
Problem Solving and Python Programming GE3151
191
Problem Solving and Python Programming GE3151
Additional Programs
148
Problem Solving and Python Programming GE3151
if(b>c):
149
Problem Solving and Python Programming GE3151
else:
print(“The greatest number is”,c)
Output
i=i+1
151
Problem Solving and Python Programming GE3151
print(sum)
output
Enter the value of n :
10
55
6. Print no’s divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Output:
enter a:30
5
15
25
150
Problem Solving and Python Programming GE3151
Additional Programs
1. Python program to find the largest number in a list.
a=[]
n=int(input("Enter the number :"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Output:
Enter the number :3
Enter element:33
Enter element:569
Enter element:73
Largest element is: 569
2. Python program to put even and odd elements in a list into two different lists.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
192
Problem Solving and Python Programming GE3151
Output:
Enter number of elements:5
Enter element:69
Enter element:45
Enter element:46
Enter element:28
Enter element:457
The even list [46, 28]
The odd list [69, 45, 457]
3. Python program to remove the duplicate items from a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Output:
Enter the number of elements in list:5
Enter element1:100
Enter element2:100
Enter element3:220
Enter element4:220
Enter element5:220
193
Problem Solving and Python Programming GE3151
Non-duplicate items:
[100, 220]
4. Python program to add a key-value pair to the dictionary.
key=int(input("Enter the key (int) to be added:"))
d={}
d.update({key:value})
print(d)
Output:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
5. Python program to concatenate two dictionaries in to one.
d1={'A':1,'B':2}
d2={'D':3}
d1.update(d2)
print(d1)
Output:
Case 1:
Concatenated dictionary is:
{'A': 1, 'D': 3, 'B': 2}
6. Python program to check if a given key exists in a dictionary or not.
d={'A':1,'B':2,'C':3}
194
Problem Solving and Python Programming GE3151
if key in d.keys():
print(d[key])
else:
Output:
Enter key to check: A
Key is present and value of the key is:
1
7. Python program to sum all the items in a dictionary.
d={'A':100,'B':540,'C':239}
print(sum(d.values()))
Output:
Total sum of values in the dictionary:
879
8. Python program to multiply all the items in a dictionary.
d={'A':100,'B':100,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Output:
2390000
9. Python program to remove the given key from a dictionary.
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
195
Problem Solving and Python Programming GE3151
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Output:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
10. Python program to count the frequency of words appearing in a string using a
dictionary.
test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
Enter string: hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}
196
Problem Solving and Python Programming GE3151
CHAPTER 5
Files and exception: text files, reading and writing files, format operator; command line arguments,
errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count,
copy file.
197
Problem Solving and Python Programming GE3151
198
Problem Solving and Python Programming GE3151
access mode The access mode denotes the mode in which the file has to be opened (read,
199
Problem Solving and Python Programming GE3151
Opens a file for appending in binary format. The file pointer is at the end
ab
of the file if the file exists. If the file does not exist, it creates a new file
200
Problem Solving and Python Programming GE3151
for writing.
Opens a file for both appending and reading. The file pointer is at the end
a+ of the file if the file exists. If the file does not exist, it creates a new file
for reading and writing.
Opens a file for both appending and reading in binary format. The file
ab+ pointer is at the end of the file if the file exists. If the file does not exist, it
creates a new file for reading and writing.
Attribute Description
Returns true if the file is closed, otherwise
file.closed
false.
Returns the file access mode with which file
file.mode
was opened.
file.name Returns name of the file.
ii) Reading and writing files
Python provides read () and write () methods to read and write files through file object
respectively.
Reading files:
The read() method read the file contents, from opened file. To read the content of file, the
file must be opened in read mode (r).There are 4 methods for reading files.
i ) Reading a file using read(size) method
ii) Reading a file using for loop
iii) Reading a file using readline() method
iv) Reading a file using readlines() method
The file test.txt contains
problem solving and python programming.
Introduction to python
i) Reading a file using read(size) method
201
Problem Solving and Python Programming GE3151
The read(size) method is used to read in size number of data.If the size parameter is not
specified, it reads and returns up to the end of file.
Syntax:
fileobject . read([size])
Example:
f=open(“test.txt”, “r+”)
S=f.read(15);
print(“Read string is:”,S)
f.close()
Output:
Read string is: problem solving
ii) Reading a file using for loop
A file can be read using for loop. This method is efficient and fast.
Syntax:
for loopvariable in fileobject:
print(loopvariable)
Example Program:
f=open(“test.txt”, “r+”)
for i in f:
print(i)
f.close()
Output:
Problem solving and python programming
Introduction to python
iii) Reading a file using readline() method
The readline() method is used to read individual line of a file. It reads a file till the
newline(\n) character is reached (or) end of file is reached.
Syntax:
fileobject . readline()
Example Program:
202
Problem Solving and Python Programming GE3151
f=open(“test.txt”, “r+”)
f.readline()
f.close()
Output:
Problem solving and python programming
iv) Reading a file using readlines() method
The readlines() method is used to read all the lines of file at a time.
Syntax:
fileobject.readlines()
Example Program:
f=open(“test.txt”, “r+”)
f.readlines()
f.close()
Output:
Problem solving and python programming
Introduction to python
Writing files:
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
a-appending mode
x-exclusive creation
The ‘w’ mode will overwrite into the file if already exists. So all previous data’s are erased.
Syntax:
fileobject . write(string)
Example Program:
f=open(“test.txt”, “r+”)
f.write(“Welcome to python”)
f.close()
iii) Closing the file
203
Problem Solving and Python Programming GE3151
The function close() of a file object flushes if there is any unwritten information and closes
the file object when there is no more writing can be done. Python closes a file automatically when
the reference object of a file is reassigned with another file. The syntax of close () function is given
below.
Syntax:
fileobject.close()
Example Program:
f1=open(“test.txt”,”w”)
print(“Name of file is:”,f1.name)
print(“closed or not:”,f1.closed)
print(“opening mode is:”,f1.mode)
f1.close()
Output:
Name of file is:test.txt
closed or not:False
opening mode is:w
5.1.3 Format Operator
write() function takes the argument as a string . To put other values in a file, it must be
converted to strings. It is done by 2 methods:
i) str() method is used to convert other values into string.
Example Program:
>>>x=52
>>>f.write(str(x))
52
ii) Format operator is an % operator that converts other values into string.
with integers, % is considered as modulus operator
with strings,% is considered as format operator
Example Program:
>>>x=15
204
Problem Solving and Python Programming GE3151
>>>”%d”%x
15
%d is formatted as decimal integer.
Format sequence in string:
Format sequence can appear anywhere in the string
Example Program:
>>>computers=10
>>>’I have bought %d computers’, %computers
Output:
I have bought 10 computers
More than one format sequence:
If there is more than one format sequence, second argument must be tuple.
Example Program:
>>>”In %d years, I have bought %g%s”.%(2,3.0,’computers’)
In 2 years, I have bought 3.0 computers
In the above program:
%d is formatted to integer
%g is formatted to floating point number
%s is formatted to string.
Number of elements in tuple and number of format sequences must be same.
5.2 COMMAND LINE ARGUMENTS
Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our script other languages.
Command line argument in python can be processed by using two modules.
i) sys module
ii) argparse module
i) sys module
Sys module is used to access the command line arguments through sys.argv. The sys
module is used for two purposes.
i) sys.argv is a list in Python, which contains the command line arguments passed to the script.
205
Problem Solving and Python Programming GE3151
206
Problem Solving and Python Programming GE3151
Errors
207
Problem Solving and Python Programming GE3151
208
Problem Solving and Python Programming GE3151
209
Problem Solving and Python Programming GE3151
print (10/0)
ZeroDivisionError: integer division or modulo by zero
Exceptions come in different types, and the type is printed as part of the message: the type
in the example is ZeroDivisionError which occurs due to division by 0. The string printed as the
exception type is the name of the built-in exception that occurred. Exception refers to unexpected
condition in a program. The unusual conditions could be faults, causing an error which in turn
causes the program to fail. The error handling mechanism is referred to as exception handling.
Many programming languages like C++, PHP, Java, Python, and many others have built-in support
for exception handling.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it stops the current process and passes
the control to corresponding exception handler. If not handled, our program will crash.
Some of the standard exceptions available in Python are listed below.
Exception Name Description
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
OverflowError Raised when a calculation exceeds maximum limit for
a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place
for all numeric types.
AssertionError Raised in case of failure of the Assert statement
EOFError Raised when there is no input from either the
raw_input() or input() function and the end of file is
reached.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence
KeyError Raised when the specified key is not found in the
dictionary.
210
Problem Solving and Python Programming GE3151
211
Problem Solving and Python Programming GE3151
Syntax:
try:
statements
----------------
-----------------
Except exception1:
Except exception2:
ii) If no exception occurs, the except block is skipped and execution of the try statement
is finished.
iii) If an exception1 occurs rest of try block is skipped, except block1 gets executed.
iv) If an exception2 occurs rest of try block is skipped, except block2 gets executed.
A simple example to handle divide by zero error is as follows.
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”
Output:
divide by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to see
if the exception type matches. If none of the except clauses match, the exception will be considered
unhandled, and your program will crash.
212
Problem Solving and Python Programming GE3151
Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
Output (successful):
Please enter the dividend: 12
Please enter the divisor: 2
12 / 2 = 6.000000
Output (unsuccessful-divide by zero error):
Please enter the dividend: 100
Please enter the divisor: 0
The dividend may not be zero!
213
Problem Solving and Python Programming GE3151
214
Problem Solving and Python Programming GE3151
Example:
try:
raise NameError
except NameError:
print(‘Error’)
Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as re-raise. If no expressions are present, raise re-raises the
last exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise
Output:
Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(‘Hi’)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
5.4.2 The else and finally statements
Two clauses that can be added optionally to try-except block are else and finally. else
will be executed only if the try clause doesn’t raise an exception.
try:
age = int(input(“Please enter your age: “))
except ValueError:
215
Problem Solving and Python Programming GE3151
else:
print(“I see that you are %d years old.” % age)
Output:
Please enter your age:10
I see that you are 10 years old.
Please enter your age:’a’
Value error occured
5.4.3 User-defined exceptions
Python allows the user to create their custom exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception class.
# define Python user-defined exceptions
class Error(Exception):
“””Base class for other exceptions”””
pass # null operation
class PosError(Error):
“””Raised when the input value is positive”””
pass
class NegError(Error):
“””Raised when the input value is negative”””
Pass
5. 5 MODULES
Module is a file containing Python definitions and statements. Modules are imported from
other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found, “module not found” will be displayed.
216
Problem Solving and Python Programming GE3151
Modules
217
Problem Solving and Python Programming GE3151
>>>math . factorial(4)
24
iii) datetime
This module is used to calculate date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
5.5.2 User Defined modules
To create module,write one or more functions in file, then save it with .py extentions.
i) Create a file
def add(a,b):
c=a+b
return c
ii) Save it as sum.py
iii) Import module
>>>import sum
>>>print sum.add(10,20)
5.6 PACKAGES
When we have a large number of Python modules, they can be organized into packages
such that similar modules are placed in one package and different modules are placed in different
packages. A package is a tree like hierarchical file directory structure that consists of modules,
sub-packages, sub-sub packages, and so on. In another words, it is a collection of modules. When
a package is imported, Python explores in list of directories on sys.path for the package
subdirectory.
Example:
Assume we are creating a package named Animals with some sub packages as shown in
following.
218
Problem Solving and Python Programming GE3151
Animals
(Package)
_init_.py _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
219
Problem Solving and Python Programming GE3151
Syntax:
import Animals.Birds.display
Now if this display.py module contains a function named displayByName(), we must use
the following statement with full name to reference it.
Syntax:
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
Syntax:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
Syntax:
display.displayByName()
5.7 ILLUSTRATIVE PROGRAMS
5.7.1 Word count
This Program counts the number of words present in a given file.
try:
InFile=open(“test.txt”,’r’)
except IOError:
print “Error:File Not Found”
else:
data=inFile.read()
words=data.split()
print(words)
print “Total number of words are:”,len(words)
Output:
test.txt
221
Problem Solving and Python Programming GE3151
1. Define file.
File is the named location on the system which stores data, information or commands for later
access. It stores the information permanently.
2. Define Text File.
Text files are the types of files that store information in the form of readable and printable
characters. They are the persistent storage.
3. What are the basic file operations in python?
Opening a file
Writing to a file.
Reading from a file
Closing a file.
4. What are the different types of files?
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5. Write the syntax for opening and closing a file.
Opening a file: fileobject.open(“filename”,mode)
Closing a file: fileobject.close()
6. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
f.write("hello world")
f.close()
7. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
8. What are the two arguments taken by the open() function?
222
Problem Solving and Python Programming GE3151
The open function takes two arguments: name of the file and the mode of operation.
Example:
f = open("test.txt","w")
9. What is a file object?
A file object allows us to use, access and manipulate all the user accessible files. It
maintains the state about the file it has opened.
i) sys module
ii) argparse module
14. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
For example, dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo
15. Define an error. What are its types?
Errors are mistakes in the program, which are created by fault of the programmer. They
are often referred to as bugs.
Types of errors:
iv) Syntax errors
v) Runtime errors
vi) Logical error
16. Define Debugging.
Debugging is the process of finding and eliminating errors.
17. Define Runtime errors.
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
Division by Zero
Access not defined identifier
Access not defined file
18. What are the error messages that are displayed for the following exceptions?
Accessing a non-existent list item
Accessing a key that isn’t in the dictionary
Trying to open a non-existent file
IndexError: list index out of range
KeyError: what
IOError: [Errno 2] No such file or directory: 'filename'
224
Problem Solving and Python Programming GE3151
19. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
20. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
the except branch and then continues.
21. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes
two arguments: the exception type and specific information about the error.
22. What are modules?
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
23. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are
simply directories.
Syntax: from <mypackage> import <modulename>
24. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py.
25. Write a python program to count number of lines, words and characters in a text file.
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")
225
Problem Solving and Python Programming GE3151
for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
26. Write a python script to display the current date and time. ( JANUARY 2018)
>>>import datetime
>>>datetime.time()
9:15:20
>>>datetime.date()
19/5/2018
27. Write a note on modular design. (JANUARY 2018)
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
• Sys.argv
• argparse
• getopt
31. Write methods to rename and delete files. (JANUARY 2020)
Delete - remove()
Rename – rename()
227
Problem Solving and Python Programming GE3151
228
Problem Solving and Python Programming GE3151
1. Write a function that copies a file reading and writing up to 50 characters at a time.
2. Write a Python program to handle multiple exceptions.
3. Write a python program to count number of lines, words and characters in a text file.
4. Write a program to illustrate multiple modules.
5. Write a Python program to append the contents of one file to another file.
6. Write a Python program to count the occurrences of a word in a text file.
7. Write a Python program to count the number of blank spaces in a text file.
229
Problem Solving and Python Programming GE3151
Additional Programs
230
Problem Solving and Python Programming GE3151
231
Problem Solving and Python Programming GE3151
Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
Contents of file test.txt:
Appending!!
Contents of file test1.txt (before appending):
Original
Contents of file test1.txt (after appending):
Original Appending!!
5. Python program to count the number of blank spaces in a text file.
fname = input("Enter file name: ")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Contents of file:
he l l o world hello
Output:
Output:
Enter file name: read.txt
Occurrences of blank spaces:5
6. Python program to read a file and capitalize the first letter of every word in the file.
fname = input("Enter file name: ")
with open(fname, 'r') as f:
232
Problem Solving and Python Programming GE3151
for line in f:
l=line.title()
print(l)
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
7. Python program to read the contents of a file in reverse order.
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
hello
hello word
233
Problem Solving and Python Programming GE3151
234
Problem Solving and Python Programming GE3151
ANNA UNIVERSITY
MODEL
QUESTION PAPERS
235
Problem Solving and Python Programming GE3151
236
Problem Solving and Python Programming GE3151
237
Problem Solving and Python Programming GE3151
238
Problem Solving and Python Programming GE3151
239
Problem Solving and Python Programming GE3151
OR
b. Define recursion. Write a Program for finding factorial of given number. (13)
14. a. Define list. Explain the various techniques to slice the list. (13)
OR
b.i) Define dictionary and its operation in detail.(7)
ii) Explain about the different types of arguments in detail. (6)
15. a .i)Explain in detail about how to read contents from file with example.(6)
ii) Explain in detail about package concepts in python with example. (7)
OR
b. i) Define exception handling? Explain user defined exception handling in detail.(6)
ii) Write a program to count the occurrence of all letters in file. (7)
PART –C (1 x15=15)
16. a. Summarize the difference between algorithm, flowchart and pseudo code.(15)
OR
b. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii)
sum of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple
vii) Compare two tuples viii) printing two tuples of different data types.(15)
240
Problem Solving and Python Programming GE3151
1. What is an algorithm?
2. Write a pseudo-code to accept two numbers, add the numbers and print the result.
3. Outline the modes Python interpreter works.
4. State the difference between (I) and (II) operators in Python.
5. Write a Python program to accept two numbers, find the greatest and print the result.
6. What is recursion?
7. What is a list in Python? Give example.
8. Write the syntax for concatenating two lists in Python.
9. What is an exception? Give example.
10. Write the syntax for opening a file in Python for reading only.
242
Problem Solving and Python Programming GE3151
1. What is an algorithm?
2. Write an algorithm to accept two numbers, compute the sum and print the result.
3. Name the four types of scalar objects Python has.
4. What is a tuple? How literals of type tuple are written? Give example.
5. Write a Python program to accept two numbers, multiply them and print the result.
6. Write a Python program to accept two numbers, find the greatest and print the result.
7. What is a list? How lists differ from tuples?
8. How to slice a list in Python?
9. Write a Python script to display the current date and time.
10. Write a note on modular design.
11. a) i) Draw a flow chart to accept three distinct numbers, find the greatest and print the result.
(8)
ii) Draw a flow chart to find the sum of the series 1 + 2+ 3+4+5+….+100. (8)
(OR)
b) Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem
with relevant diagrams. (16)
243
Problem Solving and Python Programming GE3151
(OR)
b) i) Write the Python program to perform linear search on a list. (8)
ii) Write a Python program to store ‘n’ numbers in a list and sort the list using
selection sort. (8)
15. a) Tabulate the different modes for opening a file and explain the same. (16)
(OR)
b)i) Appraise the use of try block and except block in Python with syntax. (6)
ii) Explain with an example exceptions with arguments in Python. (10)
244
Problem Solving and Python Programming GE3151
245
Problem Solving and Python Programming GE3151
12. a. i)Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python (8)
(OR)
b.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in functions. (12)
ii)Write a python function to swap the values of two variables (4)
13. a) List the three types of conditional statements and explain them (16)
(OR)
b. i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
14. a.i)Discuss the different options to traverse a list (8)
ii)Demonstrate the working of +,* and slice operators in python (8)
(OR)
b.i)Compare and contrast tuples and list in python (4)
ii)Write a script in python to sort n number using selection sort (12)
15. a.i)Explain the commands used to read and write into a file with examples (8)
ii)Discuss about the use of format operator in file processing (8)
(OR)
b) Describe how exceptions are handled in python with necessary examples (16)
246
Problem Solving and Python Programming GE3151
247
Problem Solving and Python Programming GE3151
b). i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer.
It was created by the ancient Greek mathematician Eratosthenes. The algorithm to find all
prime numbers less than or equal to a given integer n:
1) Create a list of integers from two to n:2,3,4,….n
2) Start with a counter i set to 2. (i.e)the first prime number
3) Starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4) Find the first number of the list following i. This is the next prime number
5)Set I to the number found in the previous step
6) Repeat steps 3 and 4 until I is greater than n.
7) All the numbers, which are still in the list are prime numbers (10)
12. a.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4)
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
OR
b)i)Write a python program print the maximum among ‘n’ randomly generate ‘d’ numbers
by storing them in a list(10)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6)
13.a.i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be
able to get the short sticks to meet in the middle. For any three length, there is a simple test to see
if it is possible to form a triangle: If any of three lengths is greater than the sum of the other two,
then you cannot form a triangle. Otherwise ,you can.
248
Problem Solving and Python Programming GE3151
i) Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with the
given lengths. (4)
ii) Write a function that prompts the user to input three stick lengths, converts them to integers,
and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii) Write a python program to generate all permutations of a given string using built-in
functions. (8)
OR
b.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10)
14.a.i) Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v) Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6)
OR
b.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using merge sort.(8)
15.a.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8)
b.i)How to merge multiple files into a new file using python.(6)
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (10)
249
Problem Solving and Python Programming GE3151
REFERENCES
TEXT BOOKS:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist’’, 2nd edition,
Updated for Python 3, Shroff/O’Reilly Publishers, 2016 (http://greenteapress.com/wp/think-
python/)
2. Guido van Rossum and Fred L. Drake Jr, “An Introduction to Python – Revised and
updated for Python 3.2, Network Theory Ltd., 2011.
REFERENCES:
1. Charles Dierbach, “Introduction to Computer Science using Python: A Computational
Problem-Solving Focus, Wiley India Edition, 2013.
2. John V Guttag, “Introduction to Computation and Programming Using Python’’, Revised
and expanded Edition, MIT Press , 2013
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning,
2012.
4. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An Introduction
to Computer Science using Python 3”, Second edition, Pragmatic Programmers,LLC,2013.
5. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in
Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,, 2015.
250