Vous êtes sur la page 1sur 73

GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING


QUESTION BANK

UNIT I
ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
1. What is an algorithm?(Jan-2018)
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.
2. Write an algorithm to find minimum of three numbers.
ALGORITHM : Find Minimum of three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A,B and A,C. If A is minimum, perform step 4 else perform step 5.
Step 4:Compare B and C. If B is minimum, output “B is minimum” else output “C is minimum”.
Step 5: Stop
3. List the building blocks of algorithm.
The building blocks of an algorithm are
 Statements
 Sequence
 Selection or Conditional
 Repetition or Control flow
 Functions
An action is one or more instructions that the computer performs in sequential order (from first to last).
A decision is making a choice among several actions. A loop is one or more instructions that the
computer performs repeatedly.
4. Define statement. List its types.
The instructions in Python, or indeed in any high-level language, are designed as components for
algorithmic problem solving, rather than as one-to-one translations of the underlying machine
language instruction set of the computer. Three types of high-level programming language statements.
Input/output statements make up one type of statement. An input statement collects a specific value
from the user for a variable within the program. An output statement writes a message or the value of a
program variable to the user’s screen.
5. Write the pseudocode to calculate the sum and product of two numbers and display it.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2
COMPUTE sum = number1 + number2
PRINT “The sum is", sum
COMPUTE product = number1 * number2
PRINT “The Product is", product
END program
6. How does flow of control work?
Control flow (or flow of control) is the order in which individual statements, instructions or function
calls of an imperative program are executed or evaluated. A control flow statement is a statement in
which execution results in a choice being made as to which of two or more paths to follow.
7. What is a function?
Functions are named sequence of statements that accomplish a specific task. Functions usually "take
in" data, process it, and "return" a result. 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.
8. Write the algorithm to calculate the average of three numbers and display it.
Step 1: Start
St.Joseph’s Institute of Technology 1
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Step 2: Read values of X,Y,Z
Step 3: S = X+Y+Z
Step 4: A = S/3
Step 5: Write value of A
Step 6: Stop
9. Give the rules for writing Pseudocode.
 Write one statement per line.
 Capitalize initial keywords.
 Indent to show hierarchy.
 End multiline structure.
 Keep statements language independent.
10. Give the difference between flowchart and pseudocode.
Flowchart Pseudocode

 A flowchart is a diagram showing an  Pseudocode is a means of expressing the


overview of the problem. stepwise instructions for solving a
 It is a pictorial representation of how the problem without worrying about the
program will work, and it follows a syntax of a particular programming
standard format. language.
 It uses different kinds of shapes to  Unlike a flowchart, it uses a written
signify different processes involved in format which requires no absolute rules
the problem for writing.
 It can be written in ordinary English, and
we can use some keywords in it too.
11. Define a flowchart.
 A flowchart is a diagrammatic representation of the logic for solving a task.
 A flowchart isdrawn 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.
12. Give an example of iteration.
a=0
for i in range(4): # i takes the value 0,1,2,3
a=a+i
print(a) #number 6 is printed (0+0;0+1;1+2;3+3)
13. Write down the rules for preparing a flowchart.
While drawing a flowchart, some rules need to be followed:
 A flowchart should have a start and end
 The direction of flow in a flowchart must be from top to bottom and left to right
 The relevant symbols must be used while drawing a flowchart.
14. List the categories of Programming languages.
Programming Languages are divided into the following categories:
 Interpreted
 Functional
 Compiled
 Procedural
 Scripting
 Markup
 Logic-Based
 Concurrent
 Object-Oriented Programming Languages.
15. Mention the characteristics of algorithm.
 Algorithm should be precise and unambiguous.
 Instruction in an algorithm should not be repeated infinitely.
St.Joseph’s Institute of Technology 2
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
 Ensure that the algorithm will ultimately terminate.
 Algorithm should be written in sequence.
 Algorithm should be written in normal English.
 Desired result should be obtained only after the algorithm terminates

16. Compare machine language, assembly language and high-level language.


Machine Language Assembly Language High-Level Language

 The language of 0s and 1s  It is low level  High level languages are


is called as machine programming language English like statements and
language. in which the sequence programs .
 The machine language is of 0s and 1s are  Written in these languages
system independent replaced by are needed to be translated
because there are different mnemonic (ni-monic) into machine language
set of binary instruction codes. before to their execution
for different types of  Typical instruction for using a system software
computer systems addition and subtraction compiler.
17. Describe algorithmic problem solving.
Algorithmic Problem Solving deals with the implementation and application of algorithms to a variety
of problems. When solving a problem, choosing the right approach is often the key to arriving at the
best solution.
18. List out the simple strategies to develop an algorithm.
Algorithm development process consists of five major steps.
Step 1: Obtain a description of the problem.
Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.
19. Give the difference between recursion and iteration.
Recursion Iteration
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
In recursive function, base case (terminate Iterative approach involves four steps:
condition) and recursive case are specified. initialization, condition, execution and updation.
Recursion is slower than iteration due to overhead Iteration is faster.
of maintaining stack.
Recursion takes more memory than iteration due Iteration takes less memory.
to overhead of maintaining stack.
20. What are advantages and disadvantages of recursion?
Advantages Disadvantages
Recursive functions make the code look clean and Sometimes the logic behind recursion is hard to
elegant. follow through.
A complex task can be broken down into simpler Recursive calls are expensive (inefficient) as
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.
21. Write an algorithm to accept two numbers, compute the sum and print the result.(Jan-2018)
Step1: Read the two numbers a and b.
Step 2: Calculate sum = a+b
Step 3: Display the sum
22. Write an algorithm to find the sum of digits of a number and display it.
Step 1: Start
Step 2: Read value of N
St.Joseph’s Institute of Technology 3
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Step 3: Sum = 0
Step 4: While (N != 0)
Rem = N % 10
Sum = Sum + Rem
N = N / 10
Step 5: Print Sum
Step 6: Stop
23. Write an algorithm to find the square and cube and display it.
Step 1: Start
Step 2: Read value of N
Step 3: S =N*N
Step 4: C =S*N
Step 5: Write values of S,C
Step 6: Stop
24. Explain Tower of Hanoi.
The Tower of Hanoi is a mathematical game. It consists of three rods and a number of disks of
different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in
ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
 Only one disk can be moved at a time.
 Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack.
 No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to
solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
25. What is recursion ?
Recursion is a method of solving problems that involves breaking a problem down into smaller and
smaller subproblems until you get to a small enough problem that it can be solved trivially. Usually
recursion involves a function calling itself. While it may not seem like much on the surface, recursion
allows us to write elegant solutions to problems that may otherwise be very difficult to program.
Example:
defcalc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
26. Write an algorithm to find minimum in a list. (Jan-2019)
ALGORITHM : To find minimum in a list
Step 1: Start
Step 2: Read the list
Step 3: Assume the first element as minimum
Step 4: Compare every element with minimum. If the value is less than minimum, reassign that value
as minimum.
Step 5: Print the value of minimum.
Step 6: Stop
27. Distinguish between algorithm and program. (Jan-2019)
Algorithm Program

Algorithm is the approach / idea to solve some A program is a set of instructions for the computer
problem. to follow.

St.Joseph’s Institute of Technology 4


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
It does not have a specific syntax like any of the It is exact code written for problem following all
programming languages the rules (syntax) of the programming language.

It cannot be executed on a computer. It can be executed on a computer

28. List the Symbols used in drawing the flowcart. (Apr 2019)
Flowcharts are usually drawn using some standard symbols
 Terminator
 Process
 Decision
 Connector
 Data
 Delay
 Arrow
29. Give the python code to find the minimum among the list of 10 numbers. (Apr 2019)
numList = []
n=int(raw_input('Enter The Number of Elements in List :'))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
numList.append(x)
maxNum = numList[0]
for i in numList:
if i > maxNum:
maxNum = i
print('Maximum Element of the Given List is %d' %(int(maxNum)))

PART B (16 MARKS)

1. What are the building blocks of an algorithm? Explain in detail.


The building blocks of algorithm are
-Statements
-State
-Control flow
-Functions
Statements:
There are 3 types of statements:
-Input/Output Statement
-Assignment Statement
-Control Statement
State:
There are 3 types of state:
-Initial state
-Current state
-Final state
Control flow:
-Sequence
The sequence structure is the construct where one statement is executed after another

-Selection
St.Joseph’s Institute of Technology 5
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The selection structure is the construct where statements can executed or skipped depending on
whether a condition evaluates to TRUE or FALSE. There are three selection structures in C:
1. IF
2. IF – ELSE
3. SWITCH

-Repetition
The repetition structure is the construct where statements can be executed repeatedly until a condition
evaluates to TRUE or FALSE. There are two repetition structures in C:
1. WHILE
2. FOR

Functions:
A function is a block of organized reusable code that is used to perform a single action.

2. Briefly describe iteration and recursion. Illustrate with an example.

S.No Iteration Recursion

1 The process is repeated until the The function calls itself until the base condition is
condition fails. satisfied.

2 It consumes less memory. It consumes more memory

3 It is faster It is slower

4 The code is long. The code is short.

5 Tracing is easier if any problem Tracing is difficult if any problem occurs.


occurs.

Example: Iterative algorithm for factorial of a number

Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop

factorial(n)
Step 1: Initialize f=1,i=1
Step 2: Repeat step 2.1 and 2.2 until i<=n
Step 2.1: f= f*i
Step 2.2: Increment i by 1 (i=i+1)
Step 3: Return f

St.Joseph’s Institute of Technology 6


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Example: Recursive algorithm for factorial of number

Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f

3. Explain in detail Algorithmic problem solving.

4. Write an algorithm and draw a flowchart to calculate 24.


Algorithm:
Step 1: Start
Step 2: Initialize the value of result, r=1.
Step 3: Repeat step4 for 4 times
Step 4: calculate r=r*2
Step 5: Print the value of r
Step 6: Stop

Flowchart:
St.Joseph’s Institute of Technology 7
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

5. a) Describe pseudo code with its guidelines.


Pseudo code consists of short, readable and formally-styled English language used for explaining an
algorithm. Pseudo code does not include details like variable declarations, subroutines etc.
Preparing a Pseudo Code
 Pseudo code is written using structured English.
 In a pseudo code, some terms are commonly used to represent the various actions.
For example,
for inputting data the terms may be (INPUT, GET, READ),
for outputting data (OUTPUT, PRINT, DISPLAY),
for calculations (COMPUTE, CALCULATE),
for incrementing (INCREMENT),
in addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction, and
initialization, respectively.
 The control structures—sequence, selection, and iteration are also used while writing the pseudo
code.
 The sequence structure is simply a sequence of steps to be executed in linear order.
The selection constructs—if statement and case statement. In the if-statement, if the condition is true
then the THEN part is executed otherwise the ELSE part is executed. There can be variations of the
if-statement also, like there may not be any ELSE part or there may be nested ifs. The case statement
is used where there are a number of conditions to be checked. In a case statement, depending on the
value of the expression, one of the conditions is true, for which the corresponding statements are
executed. If no match for the expression occurs, then the OTHERS option which is also the default
option, is executed.
 WHILE and FOR are the two iterative statements.
b) Give an example for pseudo code.
Pseudocode for finding maximum in a list:
BEGIN
SET numlist=[ ]

St.Joseph’s Institute of Technology 8


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET maximum = numlist[0]
FOR i in numlist
IF (n > maximum)
maximum = n
ENDIF
ENDFOR
PRINT maximum
END
c) Write the pseudo code for Towers of Hanoi.
Pseudocode
START
Procedure Hanoi(disk, source, dest, aux)
IF disk = = 0, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest)
move disk from source to dest
Hanoi(disk - 1, aux, dest, source)
END IF
END Procedure
6. a) What is flowchart?
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.
b) Draw a flowchart to count and print from1 to 10.

c) List down symbols and rules for writing flowchart.

St.Joseph’s Institute of Technology 9


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

7. a) Write an algorithm and give the flowchart to find the net salary of an employee.
Algorithm:
Step 1: Start
Step 2: Read the basic salary
Step 3: IF the basic is greater than or equal to 4000 ELSE Goto Step 4
Step 3.1: DA= 0.32 * basic (Dearness Allowance)
Step 3.2: HRA = 0.15 * basic (House Rent Allowance)
Step 3.3: CCA = 325 (City Compensatory Allowance)
Step 3.4: Net Salary = basic +DA + HRA + CCA
Step 4: Print the Net Salary
Step 5: Stop

St.Joseph’s Institute of Technology 10


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

b) Write an algorithm and give the pseudo code to guess an integer number in a range.
Algorithm:
step 1: Start the program
step 2: Read an 'n' number
step 3: Read an Guess number
step 4: if Guess> n; print "Your Guess too high" Step 5: elif Guess <n ; print "Your Guess
too low" step 6: elif Guess = = n; print "Good job"
Step 7: else print"Nope "
Step :8 Stop the program
Pseudocode:
BEGIN
READ n
READ Guess = 20
IF Guess> n
print"Your Guess too High" elif Guess< n
print "Your Guess too low" elif Guess = = 20
print "Good Job"
ELSE
PRINT "Nope"

8. a) Write an algorithm to insert a card in a list of sorted cards.


ALGORITHM:
Step 1: Start
Step 2: Declare the 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

St.Joseph’s Institute of Technology 11


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
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 step 15
Step 13: i=i-1
Step 14: go to step 11
Step 15: List[i+1]=X
Step 16: Stop

b) Write an algorithm to find the minimum number in a list.


Algorithm:
Step 1 : Start
Step 2 : Initialize the value of minimum = 0
Step 3 : Enter the input number (n) of items in a list.
Step 4 : Get all the elements using for loop and store it in a list.
Step 5: Assign the first element in a list as minimum.
Step 6: Compare maximum with the first element in a list,n.
Step 7: Repeat step 8,9 until list becomes empty.
Step 8 : If n is less than the minimum
Step 9 : Assign minimum = n
Step 10 : Display minimum

Pseudocode:
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET minimum = numlist[0]
FOR i in numlist
IF (n < minimum)
minimum = n
ENDIF
ENDFOR
PRINT minimum
END

9. a) Draw a flowchart to accept three distinct numbers, find the greatest and print the result.
(Jan 2018 (8 Marks))
St.Joseph’s Institute of Technology 12
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

Start

Input a, b, c

yes
no yes yesyes
Output b b>c a>b a>c Output a

no
no

Output c

Stop
b) Draw a flowchart to find the sum of the series 1 + 2 + 3 + 4 + 5 ….. + 100. (Jan 2018 (8
Marks))

Start

SUM = 0

N=0

N=N+1

SUM=SUM + N
no

IS
yes
N=100

PRINT SUM

Stop
10. Outline the Towers of Hanoi problem. Suggest a solution to the Tower of Hanoi problem
with relevant diagrams. (Jan 2018(16 Marks))
Rules:
 Only one disk can be moved among the towers at any given time
 Only the “top” disk can be removed
 No large disk can sit over a small disk

St.Joseph’s Institute of Technology 13


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

11. (i) Identify simple strategies for developing an algorithm. (Jan-2019)


The simple strategies for developing an algorithm are as follows:
1. In the algorithm each and every instruction should be precise and unambiguous.
2. The instruction in an algorithm should not be repeated infinitely.
3. Ensure that the algorithm will ultimately terminate.
4. The algorithm should be written in sequence.
5. It looks like normal English.
6. The desired result should be obtained only after the algorithm terminates.

(ii) Write an algorithm to insert a card in a list of sorted cards. (Jan-2019)


Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
12. Mention the different types of iterative structures allowed in python. Explain the use of
continue and break statements with an example. (Apr 2019)

while statement

St.Joseph’s Institute of Technology 14


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The keyword while followed by a test expression (which can be any valid expression), and a
colon. Following the header is an indented body. The test expression is evaluated. If it evaluates to
True, then the body of the loop is executed. After executing the body, the test expression is evaluated
again. While test expression evaluates to True, the body of the loop is executed. When the test
expression evaluates to False, the loop is terminated and execution continues with the statement
following the body.

while
<test_expression>:
<body>

Eg:
def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1

The condition for this loop is n != 1, so the loop will continue until n is 1, which makes
the condition false.
Each time through the loop, the program outputs the value of n and then checks whether
it is even or odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3+1. For
example, if the argument passed to sequence is 3, the resulting sequence is 3,10, 5, 16, 8, 4, 2, 1.
The for Statement
Python’s for statement iterates over the items of any sequence (a list or a string), in the order
that they appear in the sequence.

St.Joseph’s Institute of Technology 15


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

for val in sequence:


Body of for

Eg:

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
Python break and continue
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
The working of break statement in for loop and while loop is shown below.

St.Joseph’s Institute of Technology 16


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

Eg:
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break

The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
The working of continue statement in for and while loop is shown below.

Eg:
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

St.Joseph’s Institute of Technology 17


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

13. (i) What is an algorithm? Summarise the characteristics of a good algorithm. (8) (Apr 2019)

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.
The characteristics of a good algorithm are:
 Time - Lesser time required.
 Memory - Less memory required.
 Accuracy - Suitable or correct solution obtained.
 Sequence - Must be sequence and some instruction may be repeated in number of times or
until particular condition is met.
Generability - Used to solve single problem and more often algorithms are designed to handle a range
of input data.
(ii) Outline the algorithm for displaying the first n odd numbers. (Apr 2019)
Algorithm:
Step 1: Start
Step 2: Read the value of n
Step 3: Initialize i=0
Step 4: If i%2!=0, then goto step 4.1, else goto step 4.2
Step 4.1: Print i is odd
Step 4.2: i=i+1
Step 5: Stop
UNIT II - DATA, EXPRESSIONS, STATEMENTS
PART- A (2 Marks)
1. What is meant by interpreter?
An interpreter is a computer program that executes instructions written in a programming language. It
can eitherexecute the source code directly or translate the source code in a first step into a more
efficient representation and executes this code.
2. How will you invoke the python interactive interpreter?
The Python interpreter can be invoked by typing the command "python" without any parameter
followed by the "return" key at the shell prompt.
3. What are the commands that are used to exit from the python interpreter in UNIX and
windows?
CTRL+D is used to exit from the python interpreter in UNIX and CTRL+Z is used to exit from the
python interpreter in windows.
4. Write a snippet to display “Hello World” in python interpreter.
In script mode:
>>>print("Hello World")
Hello World
In Interactive Mode:
>>> "Hello World"
'Hello World'
5. Define a variable and write down the rules for naming a variable.
A name that refers to a value is a variable .Variable names can be arbitrarily long. They can contain
both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it
is good to begin variable names with a lowercase letter.
6. List down the basic data types in Python.
 Numbers
 String

St.Joseph’s Institute of Technology 18


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
 List
 Tuple
 Dictionary
7. Define keyword and enumerate some of the keywords in Python. (Jan-2019)
A keyword is a reserved word that is used by the compiler to parse a program. Keywords cannot be
used as variable names. Some of the keywords used in python are:
 and
 del
 from
 not
 while
 is
 continue
8. What do you mean by an operand and an operator? Illustrate your answer with relevant
example.
An operator is a symbol that specifies an operation to be performed on the operands. The data items
that an operator acts upon are called operands. The operators +, -, *, / and ** perform addition,
subtraction, multiplication, division and exponentiation.
Example: 20+32.In this example, 20 and 32 are operands and + is an operator.
9. Explain the concept of floor division.
The operation that divides two numbers and chops off the fraction part is known as floor division.
Example:>>> 5//2= 2
10. Define an expression with example.
An expression is a combination of values, variables, and operators. An expression is evaluated using
assignment operator.Example:Y= X + 17
11. Define statement and mention the difference between statement and an expression.
A statement is a unit of code that the Python interpreter can execute. The important difference is that
an expression has a value but a statement does not have a value.
12. What is meant by rule of precedence? Give the order of precedence.
The set of rules that govern the order in which expressions involving multiple operators and operands
are evaluated is known as rule of precedence. Parentheses have the highest precedence followed by
exponentiation. Multiplication and division have the next highest precedence followed by addition and
subtraction.
13. Illustrate the use of * and + operators in string with example.
The * operator performs repetition on strings and the + operator performs concatenation on strings.
Example:>>> ‘Hello*3’
Output:HelloHelloHello
>>>’Hello+World’
Output:HelloWorld
14. What is function call?
A function is a named sequence of statements that performs a computation. When you define a
function, you specify the name and the sequence of statements. Later, you can “call” the function by
name is called function call.
Example:
sum() //sum is the function name
15. What is a local variable?
A variable defined inside a function. A local variable can only be used inside its function.
Example:
deff():
s = "Me too." // local variable
print(s)
a = "I hate spam."
f()

St.Joseph’s Institute of Technology 19


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
print (a)
16. Define arguments and parameter.
A value provided to a function when the function is called. This value is assigned to the corresponding
parameter in the function. Inside the function, the arguments are assigned to variables called
parameters.
17. What do you mean by flow of execution?
 In order to ensure that a function is defined before its first use, you have to know the order in
which statements are executed, which is called the flow of execution.
 Execution always begins at the first statement of the program. Statements are executed one at a
time, in order from top to bottom.
18. What is the use of parentheses?
Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. It also makes an expression easier to read.Example: 2 + (3*4) * 7
19. What do you meant by an assignment statement?
An assignment statement creates new variables and gives them values:
>>> Message = 'And now for something completely different'
>>> n = 17
This example makes two assignments. The first assigns a string to a new variable namedMessage; the
second gives the integer 17 to n.
20. What is tuple? (or) What is a tuple? How literals of type tuples are written? Give example(Jan-
2018)
A tuple is a sequence of immutable Python objects. Tuples are sequences, like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated
values. Comma-separated values between parentheses can also be used.
Example: tup1 = ('physics', 'chemistry', 1997, 2000); tup2= ();
21. Define module.
A module allows to logically organizing the Python code. Grouping related code into a module makes
the code easier to understand and use. A module is a Python object with arbitrarily named attributes
that can bind and reference.A module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
22. Name the four types of scalar objects Python has. (Jan-2018)
int, float, bool, None
23. List down the different types of operator.
Python language supports the following types of operators:
 Arithmetic operator
 Relational operator
 Assignment operator
 Logical operator
 Bitwise operator
 Membership operator
 Identity operator
24. What is a global variable?
Global variables are the one that are defined and declared outside a function and we need to use them
inside a function.
Example:#This function uses global variable s
def f():
print(s)
# Global scope
s = "I love India"
f()
25. Define function.
A function in Python is defined by a def statement. The general syntax looks like this:

St.Joseph’s Institute of Technology 20


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

def function-name(Parameter list):


statements # the function body
The parameter list consists of zero or more parameters. Parameters are called arguments, if the
function is called. The function body consists of indented statements. The function body gets executed
every time the function is called. Parameter can be mandatory or optional. The optional parameters
(zero or more) must follow the mandatory parameters.
26. What is the purpose of using comment in python program?
Comments indicate information in a program that is meant for other programmers (or anyone reading
the source code) and has no effect on the execution of the program. In Python, we use the hash (#)
symbol to start writing a comment.
Example:#This is a comment
27. State the reasons to divide programs into functions. (Jan-2019)
Creating a new function gives the opportunity to name a group of statements, which makes program
easier to read and debug. Functions can make a program smaller by eliminating repetitive code.
Dividing a long program into functions allows to debug the parts one at a time and then assemble them
into a working whole. Well designed functions are often useful for many programs.
28. Outline the logic to swap the content of two identifiers without using third variable. (Apr 2019)
a=10
b=20
a=a+b
b=a-b
a=a-b
print(“After Swapping a=”a,” b=”,b)
29. State about Logical operators available in python language with example. (Apr 2019)
Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

PART B (16 MARKS)

1. What is the role of an interpreter? Give a detailed note on python interpreter and interactive
mode of operation. (or) Sketch the structures of interpreter and compiler. Detail the differences
between them. Explain how Python works in interactive mode and script mode with examples. (Jan
2019)
An interpreter is a computer program that executes instructions written in a programming language. It
can either
• execute the source code directly or
• translates the source code in a first step into a more efficient representation and executes this code
Python interpreter and interactive mode
With the Python interactive interpreter it is easy to check Python commands. The Python interpreter
can be invoked by typing the command "python" without any parameter followed by the "return" key
at the shell prompt:
$ python
>>>
Once the Python interpreter is started, you can issue any command at the command prompt ">>>".
For example,let us print the "Hello World" statement:
St.Joseph’s Institute of Technology 21
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
>>> print "Hello World"
Hello World
In the interactive Python interpreter the print is not necessary:
>>> "Hello World"
'Hello World'
>>> 3
3
Typing an end-of-file character (Ctrl+D on Unix, Ctrl+Z on Windows) at the primary prompt causes
the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by
typing the following command: quit().
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it
prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for
continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter
prints a welcome message stating its version number and a copyright notice before printing the first
prompt:
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this
if statement:
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"

2. Illustrate values and different standard data types with relevant examples.
VALUES
A value is one of the fundamental things – like a letter or a number – that a program manipulates. Its
types are: integer, float, boolean, strings and lists.
Example: 5 is a integer value, ”hello” is a string value
STANDARD DATATYPES
Python has 5 standard data types.
• Numbers
• String
• List
• Tuple
• Dictionary
Numbers
• Integers, floating point numbers and complex numbers falls under Python numbers category.
• They are defined as int, float and complex class in Python.
Eg.a=5
Strings
• String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings.
• Multi-line strings can be denoted using triple quotes, ''' or """.
Eg. s = "This is a string"
Lists
• List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
• Lists are mutable.ie. Values can be changed
• Lists are enclosed within the square brackets[ ].
Eg. >>> a = [1, 5.8, 'Hello World']
Tuples

St.Joseph’s Institute of Technology 22


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
• Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable.
Tuples once created cannot be modified.
• Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
• It is defined within parentheses () where items are separated by commas.
• >>> t = (5,'program', 1+3j)
Dictionary
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving
data. We must know the key to retrieve the value.
• In Python, dictionaries are defined within braces {} with each item being a pair in the form key :
value.
• Key and value can be of any type.
Eg.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
3. (a) List down the rules for naming the variable with example.
A variable is a name that refers to a value. An assignment statement creates new variables and gives
them values:
• Variable names can be arbitrarily long.
• They can contain both letters and numbers, but they have to begin with a letter. It is legal to use
uppercase letters, but it is a good idea tobegin variable names with a lowercase letter.
• The underscore character, _, can appear in a name. It is often used in names with multiplewords,
such as my_name or variable_name.
• If you give a variable an illegal name, you get a syntax error:
(b) List down the different types of operators with suitable examples.
Types of operators in Python
• Arithmetic Operators.
• Comparison Operators.
• Python Assignment Operators.
• Logical Operators or Bitwise Operators.
• Membership Operators.
• Identity Operators.
• Operator precedence.

Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction,
multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic
calculation in Python like we can use the eval function, declare variable & calculate, or call functions.

Example: For arithmetic operators we will take simple example of addition where we will add two-
digit 4+5=9
x= 4
y= 5
print(x + y)
Similarly, we can use other arithmetic operators like for multiplication(*), division(/), substraction(-),
etc.

Comparison Operators

St.Joseph’s Institute of Technology 23


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
These operators compare the values on either side of the operand and determine the relation between
them. It is also referred as relational operators. Various comparison operators are ( ==, != , <>, >,<=,
etc)

Example: For comparison operators we will compare the value of x to the value of y and print the
result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we
print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns
false.
x=4
y=5
print(('x > y is',x>y))
Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the left operand.
Various assignment operators used in Python are (+=, - = , *=, /= , etc.)
Example:
Python assignment operators is simply to assign the value, for example
num1 = 4
num2 = 5
print(("Line 1 - Value of num1 : ", num1))
print(("Line 2 - Value of num2 : ", num2))

Example of compound assignment operator


We can also use a compound assignment operator, where you can add, subtract, multiply right
operand to left and assign addition (or any other arithmetic function) to the left operand.
Step 1: Assign value to num1 and num2
Step 2: Add value of num1 and num2 (4+5=9)
Step 3: To this result add num1 to the output of Step 2 ( 9+4)
Step 4: It will print the final result as 13
num1 = 4
num2 = 5
res = num1 + num2
res += num1
print(("Line 1 - Result of + is ", res))

Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in
Python are AND, OR and NOT. For logical operators following condition are applied.
For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
Example:
Here in example we get true or false based on the value of a and b
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))

St.Joseph’s Institute of Technology 24


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples. There are two
membership operators that are used in Python. (in, not in). It gives the result based on the variable
present in specified sequence or string
Example: For example here we check whether the value of x=4 and value of y=8 is available in list or
not, by using in and not in operators.
x=4
y=8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given list")
else:
print("Line 1 - x is not available in the given list")
if ( y not in list ):
print("Line 2 - y is not available in the given list")
else:
print("Line 2 - y is available in the given list")

Identity Operators
To compare the memory location of two objects, Identity Operators are used. The two identify
operators used in Python are (is, is not).
Operator is: It returns true if two variables point the same object and false otherwise
Operator is not: It returns false if two variables point the same object and true otherwise
Example:
x = 20
y = 20
if ( x is y ):
print("x & y SAME identity")
y=30
if ( x is not y ):
print("x & y have DIFFERENT identity")

4. What do you mean by rule of precedence? List out the order of precedence and demonstrate
in detail with example. (Jan 2019)(Apr 2019)
When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. For mathematical operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules,
• Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2)
is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60,
even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4 and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To
divide by 2π, you can use parentheses or write degrees / 2 / pi.

St.Joseph’s Institute of Technology 25


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
5. What is the use of function? Explain the role of function call and function definition with
example. (or) Explain the syntax and structure of user defined functions in Python with examples. Also
discuss about parameter passing in functions.(Jan 2019)

A function is a named sequence of statements that performs a computation. When you define a
function, you specify the name and the sequence of statements. Later, you can “call” the function by
name.
Types of Function:
1. Built-in function
2. User-defined function

BUILT-IN FUNCTION
Python itself have many built-in functions. Programmers can use that function directly.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument. A function “takes” an argument and
“returns” a result. The result is called the return value.
>>> range()
>>> input()

USER-DEFINED FUCTION
Syntax for Function Definition
def functionname(parameters):
statements

Syntax for Function call


functionname( arguments)

Example
//Function definition
def add(a,b):
return a+b
//Fuction call
add(5,6)

TYPE CONVERSION FUNCTIONS


Python provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn’t round off; it chops off the
fraction part:

>>> int(3.99999)
3
>>> int(-2.3)
-2

St.Joseph’s Institute of Technology 26


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

float converts integers and strings to floating-point numbers:


>>> float(32)
32.0
>>> float('3.14159')
3.14159

Finally, str converts its argument to a string:


>>> str(32)
'32

6. What is numeric literal? Give example. (Jan 2018)


Numeric Literals are immutable. Numeric literals can belong to following four different numerical
types.
Int(signed integers)
Long(long integers)
float(floating point)
Complex(complex)
Numbers(can be both positive and negative)with no fractional part.
Eg: 100
Integers of unlimited size followed by lowercase or uppercase L
Eg: 87032845L
Real numbers with both integer and fractional part
Eg: -26.2
In the form of a+bj where a forms the real part and b forms the imaginary part of complex number.
Eg: 3.14j

7. Write a Python program to circulate the values of n variables.


// Python program to circulate the values of n variables
def circulate(list, n):
return list[n:] + list[:n]
print("Left circulatedlist=",circulate([5,6,7,8,9],3))
print("Right circulate list=",circulate([5,6,7,8,9],-3))
Output
Left circulatedlist= [8, 9, 5, 6, 7]
Right circulate list= [7, 8, 9, 5, 6]
8. Write a Python program to swap two variables.
a. Using Temporary Variable
x=5
y = 10
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print("The value of x after swapping:”,x))
print("The value of y after swapping:”,y))

b. Without using Temporary Variable:


x=5
y=10

St.Joseph’s Institute of Technology 27


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
x=x+y
y=x-y
x=x-y
print("The value of x after swapping:”,x))
print("The value of y after swapping:”,y))

c. Using Tuple Assignment


x=5
y=10
x,y=y,x
print("The value of x after swapping:”,x))
print("The value of y after swapping:”,y))

9. a) Write a Python program to check whether a given year is a leap year or not.
# To get year (integer input) from the user
year = int(input("Enter the year"))
if (( year%4 == 0) and (( year%100 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)

b) Write a Python program to convert celsius to Fahrenheit.


(Formula: celsius * 1.8 = fahrenheit –32).
celsius = 37.5
fahrenheit = (celsius * 1.8) + 32
print(“Fahrenheit value=”,fahrenheit)

c) Write a python program to calculate the sum of first n even numbers.


def sumeven(n):
s=0
for i in range(0,n+1):
if(i%2==0):
s=s+i
return s
n=int(input("Enter the n value"))
print("Sum of first %d even number is %d"%(n,sumeven(n)))
10. i) Mention the list of keywords available in Python. Compare it with variable name. (8)(Apr 2019)
Variable names and keywords
Variable names can be arbitrarily long and contain both letters and numbers, but they have
to begin with a letter. The underscore character, _, can appear in a name. It is often used in names
with multiple words, such as my_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
Eg:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
St.Joseph’s Institute of Technology 28
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python 2 has 31 keywords. In Python 3, has 33 keywords.
and del from not while
as elif global or with
assert else if pass yield
break except import print nonlocal
class exec in raise false
continue finally is return
def for lambda try

ii) What are Statement? How are they constructed from variable and expression in Python. (8) (Apr
2019)
Expressions and statements
An expression is a combination of values, variables, and operators.
Eg:
17
x
x + 17
Instructions that a Python interpreter can execute are called statements. A statement is a unit of
code that the Python interpreter can execute. Two kinds of statement: print and assignment.
Eg:
a=1+2+3+\
4+5+6+\
7+8+9
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\).

UNIT III - CONTROL FLOW, FUNCTIONS


PART- A (2 Marks)

1. Define Boolean expression with Example.


A boolean expression is an expression that is either true or false. The values true and false are called
Boolean values.
Example:
>>> 5 = = 6
False
True and False are special values that belongs to the type bool; they are not strings.

2. What are the different types of operators?


i. Arithmetic Operator (+, -, *, /, %, **, // )
ii. Relational Operator( == , !=, < >, < , > , <=, >=)
iii. Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
iv. Logical Operator (AND, OR, NOT)
v. Membership Operator (in, not in)
vi. Bitwise Operator
vii. (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary left shift), >> (binary
right shift))
viii. Identity Operator (is, is not)
St.Joseph’s Institute of Technology 29
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

3. Explain modulus operator with Example.


The modulus operator works on integers and yields the remainder when the first operand is
divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same
as for other operators:

Example:
>>> remainder = 7 % 3
>>> print remainder
1 #So 7 divided by 3 is 2 with 1 left over.

4. Explain Logical operators


There are three logical operators: and, or, and not. For Example:, x > 0 and x < 10 is true only
if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean expression, so
not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non-zero number is said to be
true in Boolean expressions.

5. Explain relational operators.


The Relational operator is a programming language construct or operator that tests or defines
some kind of relation between two entities.
i. x ==y # x is equal to y.
ii. x! = y # x is not equal to y
iii. x > y # x is greater than y
iv. x < y # x is less than y
v. x >= y # x is greater than or equal to y
vi. x <= y # x is less than or equal to y

6. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.

Example:
def bar():
pass
If the function bar() is called, it does absolutely nothing.

7. What is conditional execution?


The ability to check the condition and change the behavior of the program accordingly is called
conditional execution. Example:
If statement:
The simplest form of if statement is:
Syntax:
if Test_expression:
statement

Example:
if x > 0:
print 'x is positive'

St.Joseph’s Institute of Technology 30


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement gets
executed. If not, nothing happens.

8. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are two
possibilities and the condition determines which one to execute.
Syntax:
if Test_expression:
if Test_expression:
statement
statement
else:
statement

Example:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'

9. What are chained conditionals?


Sometimes there are more than two possibilities and we need more than two branches. One way to
express a computation like that is a chained conditional:
Syntax:
if Test_expression:
statement
elif Test_expression:
statement
else:
statement
Example:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the
number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be
one.

10. Explain flow of execution of while loop with Example. (JAN 2019)
The statements inside the while loop is executed only if the condition is evaluated to true.
Syntax:
while condition:
statements
Example:
# Program to add natural numbers upto, sum = 1+2+3+...+10
n = 10
# initialize sum and counter
sum = 0
St.Joseph’s Institute of Technology 31
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)

11. Explain ‘for loop’ with Example.


The general form of a for statement is
Syntax:
forforvariable
variablein
in sequence:
sequence:
code
codeblock
block

Example:
x=4
for i in range(0, x):
print i

12. What is a break statement?


When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
Example:
for letter in 'Python':
if letter == 'h':
break
print 'Current Letter :', letter
13. What is a continue statement?
The continue statement works somewhat like a break statement. Instead of forcing termination, it
forces the next iteration of the loop to take place, skipping any code in between.
Example:
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter

14. Compare return value and composition.


Return Value:
Return gives back or replies to the caller of the function. The return statement causes our function to
exit and hand over back a value to its caller.
Example:
def area(radius):
temp = math.pi * radius**2
return temp

Composition:
Calling one function from another is called composition.
Example:
def circle_ area(a, b, c, d):
St.Joseph’s Institute of Technology 32
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
radius = distance(a, b, c, d)
result = area(radius)
return result

15.Define Recursion with an example.(JAN 2019)


The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

16. 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”, a)

Example:
a=10
def my_global():
print(“This is global variable”, a)
17. 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 ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

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

19. What are string methods?

St.Joseph’s Institute of Technology 33


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
A method is similar to a function, it takes arguments and returns a value, but the syntax is different.
For eg: 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 = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

20. Define string immutability.


Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the string
but can change what value of the variable to a new string.
Program: Output:
a = “foo” #foofoo
# a now points to foo #foo
b=a It is observed that ‘b’ hasn’t changed even
# b now points to the same foo that a points to though ‘a’ has changed.
a=a+a
# a points to the new string “foofoo”, but b points
to the same old “foo”
print a
print b

21. Explain about string module.


The string module contains number of useful constants and classes, as well as some deprecated legacy
functions that are also available as methods on strings.

Example:
Program: Output:
import string upper => MONTY PYTHON'S FLYING
text = "Monty Python's Flying Circus" CIRCUS
print "upper", "=>", string.upper(text) lower => monty python's flying circus
print "lower", "=>", string.lower(text) split => ['Monty', "Python's", 'Flying',
print "split", "=>", string.split(text) 'Circus']
print "join", "=>", string.join(string.split(text), "+") join => Monty+Python's+Flying+Circus
print "replace", "=>", string.replace(text, "Python", replace => Monty Java's Flying Circus
"Java") find => 6 -1
print "find", "=>", string.find(text, "Python"), count => 3
string.find(text, "Java")
print "count", "=>", string.count(text, "n")

22. Write a python program to accept two numbers and find the largest among them.(AU-
JAN’18)
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if (num1 == num2):
print("The numbers are equal")

St.Joseph’s Institute of Technology 34


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
elif (num1 > num2):
print("num1 is greater")
else:
print("num2 is greater")

PART B (16 MARKS)

1. Explain in detail about the various types of operators. (AU-JAN’18)


i) Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then-

Operator Description Example

+ Addition Adds values on either side of the a + b = 30


operator

-Subtraction Subtracts right hand operand from left a – b = -10


hand operand

* Multiplication Multiplies values on either side of the a * b = 200


operator

/ Division Divides left hand operand by right hand b / a = 2


operand

% Modulus Divides left hand operand by right hand


operand and returns remainder
b%a=0

** Exponent Performs exponential power calculation a**b =10


on operators

// Floor Division The division of operands where the 9//2 = 4 and 9.0//2.0 =
result is the quotient in which the digits 4.0
after the decimal point are removed

ii) Python Comparison Operators


These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example

== If the values of two operands a == b is not true


are equal, then the condition
becomes true.

!= If values of two operands are a!=b is true


not equal, then condition
becomes true.

<> If values of two operands are a <> b is true


St.Joseph’s Institute of Technology 35
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
not equal, then condition
becomes true

> If the value of left operand is a > b is not true


greater than the value of right
operand, then condition
becomes true
< If the value of left operand is a < b is true
less than the value of right
operand, then condition
becomes true

>= If the value of left operand is a >= b is not true


greater than or equal to the
value of right operand, then
condition becomes true

<= If the value of left operand is a <= b is true


less than or equal to the value
of right operand, then
condition becomes true

(iii) Logical operators


There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true only if x is
greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that
is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean expression, so
not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non zero number is said to be
true in Boolean expressions.
(iv) Assignment operators

Operator Description Example

= Assigns values from right c = a + b assigns value of a +


side operands to left side b into c
operand.

+= Add AND It adds right operand to the c += a is equivalent to c = c +


left operand and assign the a
result to left operand

-= Subtract AND It subtracts right operand c -= a is equivalent to c = c -


from the left operand and a
assign the result to left
operand

*= Multiply AND It multiplies right operand c *= a is equivalent to c = c *


with the left operand and a
assign the result to left
operand

/= Divide AND It divides left operand with c /= a is equivalent to c = c /


St.Joseph’s Institute of Technology 36
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
the right operand and assign ac /= a is equivalent to c = c /
the result to left operand a

%= Modulus AND It takes modulus using two c %= a is equivalent to c = c


operands and assign the % a
result to left operand

**= Exponent AND Performs exponential power c **= a is equivalent to c = c


calculation on operators and ** a
assign value to the left
operand

//= Floor Division It performs floor division on c //= a is equivalent to c = c //


operators and assign value to a
the left operand

2. Explain conditional alternative and chained conditional. (AU-JAN’18,19)


The simplest form of if statement is:
Syntax:
if test_expression:
statement

Eg:
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. if statements have the same structure as function definitions: a
header followed by an indented body. Statements like this are called compound statements. There is
no limit on the number of statements that can appear in the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements .In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # need to handle negative values!

Alternative execution (if-else):


A second form of if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed. The syntax looks like this:
Syntax:
if Test_expression:
statement
else:
statement

Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed. Since the
St.Joseph’s Institute of Technology 37
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
condition must be true or false, exactly one of the alternatives will be executed. The alternatives are
called branches, because they are branches in the flow of execution.

Chained conditionals(if-elif-else):
Sometimes there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional:
Syntax:
if Test_expression:
statement
elif Test_expression:
statement
else:
statement

Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on
the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have
to be one.
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them
is true, the corresponding branch executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
3. Explain in detail about Fruitful Functions.
Return values
Some of the built-in functions we have used, such as the math functions, produce results. Calling the
function generates a value, which we usually assign to a variable or use as part of an expression.
The first example is area, which returns the area of a circle with the given radius:

Eg:
def area(radius):
temp = math.pi * radius**2
return temp

We have seen the return statement before, but in a fruitful function the return statement includes an
expression. This statement means: “Return immediately from this function and use the following
expression as a return value.” The expression can be arbitrarily complicated, so we could have written
this function more concisely:

def area(radius):
return math.pi * radius**2

On the other hand, temporary variables like temp often make debugging easier. Sometimes it is useful
to have multiple return statements, one in each branch of a conditional:
St.Joseph’s Institute of Technology 38
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

def absolute_value(x):
if x < 0:
return -x
else:
return x

4. Write a Python program to find the square root of a number.


n=int(input("Enter a number to find Square Root:"))
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
print(approx)

5. Explain RECURSION.
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain problems
can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
# take input from the user
num = int(input("Enter a number: "))
def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
print(“Factorial of n numbers is :%d” %(fact(n)))

6. Explain string slices and string immutability. (JAN 2019)


String slices
A segment of a string is called a slice . Selecting a slice is similar to selecting a character:
>>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
The operator [n:m]returns the part of the string from the “n-eth” character to the “m-eth” character,
including the first but excluding the last. If you omit the first index (before the colon), the slice starts
at the beginning of the string. If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty string, represented by two
quotation marks:
>>> fruit ='banana'
>>> fruit[3:3]

St.Joseph’s Institute of Technology 39


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
An empty string contains no characters and has length 0, but other than that, it is the same as any
other string.
String immutability.
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutate
the string but can change what value of the variable to a new string.
Eg:
a = “foo”
# a now points to foo
b=a
# b now points to the same foo that a points to
a=a+a
# a points to the new string “foofoo”, but b points to the same old “foo”
print a
print b
Output
foofoo
foo
It is observed that b hasn’t changed even though ‘a’ has changed the value.

7. Explain string functions and methods.


There are a number of useful operations that can be performed with string. One of the most useful of
these is the function split. This function takes a string (typically a line of input from the user) and
splits it into individual words.
Another useful function is lower, which converts text into lower case.
Eg:
>>> line = input(“What is your name?”)
What is your name? Timothy Alan Budd
>>> lowname = line.lower()
>>> print lowname.split()
[‘timothy’, ‘alan’, ‘budd’]
Other useful functions will search a string for a given text value, or strip leading or trailing white
space from a string. An alternative version of split takes as argument the separator string. The string is
broken into a list using the separator as a division. This can be useful, for example, for breaking a file
path name into parts:

Eg:
>>> pathname = ‘/usr/local/bin/ls’
>>> pathname.split(‘/’)
[‘usr’, ‘local’, ‘bin’, ‘ls’]

The inverse of split is the function join. The argument to join is a list of strings. The value to the left
of the dot is the separator that will be placed between each element. Often this is simply an empty
string. The values in the list are laminated along with the separator to produce the result string.

>>> lst = [‘abc’,’pdq’,’xyz’]


>>> pri
nt ‘::’.join(lst)
abc::pdq::xyz

String methods

St.Joseph’s Institute of Technology 40


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
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 = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply
the method to, word. The empty parentheses indicate that this method takes no argument. A method
call is called an invocation ; in this case, we would say that we are invoking upper on the word. As it
turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana'


>>> index = word.find('a')
>>> print index
1
In this example, we invoke find on word and pass the letter we are looking for as a parameter.
Actually, the find method is more general than our function; it can find substrings, not just characters:
>>> word.find('na')
2
It can take as a second argument the index where it should start:
>>> word.find('n', 3)
4
And as a third argument the index where it should stop:
>>> name ='bob'
>>> name.find('b', 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).

8. Explain string module.

The string module contains number of useful constants and classes, as well as some deprecated
legacy functions that are also available as methods on strings.
import string
text = "Monty Python's Flying Circus"
print "upper", "=>", string.upper(text)
print "lower", "=>", string.lower(text)
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text), "+")
print "replace", "=>", string.replace(text, "Python", "Java")
print "find", "=>", string.find(text, "Python"), string.find(text, "Java")
print "count", "=>", string.count(text, "n")
Eg: Using string methods instead of string module functions
text = "Monty Python's Flying Circus"
print "upper", "=>", text.upper()
print "lower", "=>", text.lower()
print "split", "=>", text.split()
print "join", "=>", "+".join(text.split())
print "replace", "=>", text.replace("Python", "Perl")

St.Joseph’s Institute of Technology 41


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
print "find", "=>", text.find("Python"), text.find("Perl")
print "count", "=>", text.count("n")

9. a) Write a Python program to find GCD of two numbers.


d1=int(input("Enter a number:"))
d2=int(input("Enter another number"))
rem=d1%d2
while rem!=0 :
print(rem)
d1=d2
d2=rem
rem=d1%d2
print("gcd of given numbers is : %d" %(d2))

b) Write a Python program to find the exponentiation of a number.


def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

c) Write a Python program to sum an array of numbers.


list = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
list.append(numbers)
print("Sum of elements in given list is :", sum(list))

10. a) Write a Python program to perform linear search.


data = []
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
e= int(raw_input('Enter the Element to be Search '))
pos = 0
found= False
while pos < n and not found:
if int(data[pos])==e:
found= True
else:
pos = pos+1
if found:
print('Element %d Found at Position %d ' %(e,pos+1))
else:
print('Element %d is Not Found in the Array '%(e))

St.Joseph’s Institute of Technology 42


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

b) Write a Python program to perform binary search.(JAN 2019)


data = []
n = int(input('Enter Number of Elements in the Array: '))
print('Enter the Elements in Ascending Order' )
for i in range(0, n):
x = int(input('Enter the Element %d :' %(i+1)))
data.append(x)
e= int(input('Enter the Element to be Search '))
first = 0
last = n-1
found = False
while( first<=last and not found):
mid = (first + last)/2
if int(data[mid]) == e :
found = True
else:
if e < int(data[mid]):
last = mid - 1
else:
first = mid + 1
if found:
print('Element %d Found at Position %d ' %(e,mid+1))
else:
print('Element %d is Not Found in the Array '%(e))

11. Explain with suitable examples the while loop, break statement and continue statement in
python. (AU-JAN’18)
While Loop:
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax:
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. When the
condition becomes false, program control passes to the line immediately following the loop.
Example:
# Program to add natural numbers upto , sum = 1+2+3+...+10
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Break Statement:

St.Joseph’s Institute of Technology 43


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The break statement in Python terminates the current loop and resumes execution at the next
statement, just like the traditional break found in C.
The most common use for break is when some external condition is triggered requiring a hasty exit
from a loop. The break statement can be used in both while and for loops.
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"

Continue Statement:
The continue statement in Python returns the control to the beginning of the while loop.
The continuestatement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Example1:
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
Example2:
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"

12. a) Write a python program to find the factorial of a given number with and without
recursion. (AU-JAN’18)
Without Recursion
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

St.Joseph’s Institute of Technology 44


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
With recursion
def factorial(n):
if(n <= 1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))

b) Write a python program to generate the first ‘N’ Fibonacci numbers. (Note: Fibonacci
numbers are 0, 1,1,2,3,5,8… where each number is the sum of the preceding two). (AU-JAN’18)
a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b)
while(n-2):
c=a+b
a=b
b=c
print(c)
n=n-1

UNIT IV
LISTS, TUPLES AND DICTIONARIES
PART- A (2 Marks)

1. Relate String and List? [AU - Jan 2018, Jan 2019]


String: String is a sequence of characters and it is represented within double quotes or single quotes.
Strings are immutable.
Example: s=”hello”
List:
A list is an ordered set of values, where each value is identified by an index. The values that make up
a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type and it is mutable.
Example:
b= [’a’, ’b’, ’c’, ’d’, 1, 3]

2. Solve a) [0] * 4 and b) [1, 2, 3] * 3.


a) [0] * 4
[0, 0, 0, 0]
b) [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

3. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]
list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
a) list[1:3]
[’b’, ’c’]

St.Joseph’s Institute of Technology 45


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
b) list[:4]
[’a’, ’b’, ’c’,’d’]
c) list[3:]
[’d’, ’e’, ’f’]

4. Mention any 5 list methods.


append() ,extend () ,sort(), pop(), index(), insert() and remove()

5. Write a program in Python to delete first element from a list.


def deleteHead(list):
del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]

6. Define key-value pairs.


The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a
value separated by a colon. In a dictionary, the indices are called keys, so the elements are called
key-value pairs.

Example:
animal = {"cat": 1, "dog": 2}

7. State the difference between lists and dictionary.

Lists Dictionary
 They maintain their ordering unless explicitly re-  Ordering is not guaranteed
ordered (for Example, by sorting the list).

 They can be of any type, and types can be mixed.  Key values can be of any
hashtable type (i.e. not a dict) and
types can be mixed

 They are accessed via numeric (zero based) indices  Elements are accessed using key
values.
 There is no key and value for each entry  Every entry has a key and a value

8. What is List mutability in Python? Give an Example.


Python represents all its data as objects. Some of these objects like lists and dictionaries
are mutable, i.e., their content can be changed without changing their identity. Other objects like
integers, floats, strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]

9. What is aliasing in list? Give an Example.

St.Joseph’s Institute of Technology 46


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
An object with more than one reference has more than one name, then the object is said to be
aliased. Example:: If a refers to an object and we assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True

10. Define cloning in list.


In order to modify a list and also keep a copy of the original, it is required to make a copy of the list
itself, not just the reference. This process is called cloning, to avoid the ambiguity of the word
“copy”.
Example:
li1 = [4, 8, 2, 10, 15, 18]
li2 = li1[:]
print("Original List:", li1)
print("After Cloning:", li2)

11. Explain List parameters with an Example.


Passing a list as an argument actually passes a reference to the list, not a copy of the list.
For Example, the function head takes a list as an argument and returns the first element:
def head(list):
return list[0]

Output:
>>> numbers = [1, 2, 3]
>>> head(numbers)

12. What is the benefit of using tuple assignment in Python?


It is often useful to swap the values of two variables. With conventional assignments a temporary
variable would be used.
For Example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

13. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (Jan 2019)
a={‘aa’:2, ”bb”:4}
print(a.keys()[0])

14. Write a program in Python returns a list that contains all but the first element of the given
list.
def tail(list):
return list[1:]
numbers = [1, 2, 3]
rest = tail(numbers)
print(rest)

St.Joseph’s Institute of Technology 47


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
15. Difference between list and tuple. [AU - Jan 2018]
List Tuple
 The syntax for list: listWeekDays = ['mon',  The syntax for tuple:
'tue', 'wed', 2] tupWeekDays = ('mon', 'tue', 'wed', 2)
 Tuple uses ( and ) to bind the elements  List uses [ and ] to bind the elements in the
collection.
 A tuple is a list which one cannot edit once it  List is the mutable entity. You can alter list
is created in Python code. The tuple is an data anytime in your program
immutable data structure
 Insert, pop, remove or sort elements cannot  Insert and pop operation, removing and
be done. Moreover, it is immutable data type so sorting elements in the list can be done with
there is no way to change the elements in a inbuilt functions.
tuple.

16. Define dictionary with an Example.


A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs.

Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’

17. How to return tuples as values?


A function can only return one value, but if the value is a tuple, the effect is the same as returning
multiple values. For Example, if we want to divide two integers and compute the quotient and
remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the
same time.
>>> t = divmod(7, 3)
>>> print t (2, 1)

18. Write the syntax for list comprehension.


The list comprehension starts with a '[' and ']', to help us remember that the result is going to be a
list. The basic syntax is [expression for item in list if conditional].
Example:
[x**2 for x in range(0,10)]

19. Define List Comprehension.


List comprehensions apply an arbitrary expression to items in an iterable rather than applying
function. It provides a compact way of mapping a list into another list by applying a function to each
of the elements of the list.
Example:
[x**2 for x in range(0,10)]
[x for x in range(1,20) if x%2==0 ]
[x for x in 'MATHEMATICS' if x in ['A','E','I','O','U']]

20. List two dictionary operations.


 Del -removes key-value pairs from a dictionary
 Len - returns the number of key-value pairs
St.Joseph’s Institute of Technology 48
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

21. Write a Python program to swap two variables.


x=5
y = 10
temp = x
x=y
y = temp
print('The value of x after swapping:’,x)
print('The value of y after swapping:',y)

22. How do you slice a list? [AU - Jan 2018]


The slice operator works on list as follows:
>>> t = ['a', 'b', 'c', ’d’, 'e', 'f']
>>> t[1:3] ['b', 'c']
>>> t[:4] ['a', 'b', 'c', 'd']
>>> t[3:] ['d', 'e', 'f']
If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to the
end. So if we omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
23. How to create a list in python? Illustrate the use of negative indexing of list with example.
[AU - May 2019]

List Creation:
1. days = ['mon', 2]
2. days=[]
days[0]=’mon’
days[1]=2

Negative Indexing:
Example:
>>> print(days[-1])
Output: 2

24. Demonstrate with simple code to draw the histogram in python.

PART B (16 MARKS)

1. Explain in detail about lists, list operations and list slices.


A list is an ordered set of values, where each value is identified by an index. The values that make up
a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type. There are several ways to create a new list. The simplest
is to enclose the elements in square brackets ([and]):
[10, 20, 30, 40]
["spam", "bungee", "swallow"]
The following list contains a string, a float, an integer, and (mirabile dictu) another list:
["hello", 2.0, 5, [10, 20]]
A list within another list is said to be nested. Lists that contain consecutive integers are common, so
Python provides a simple way to create them:
>>> range (1,5) [1, 2, 3, 4].

St.Joseph’s Institute of Technology 49


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
LIST OPERATIONS (JAN-2019)
The + operator concatenates lists
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c [1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST SLICES
The slice operator also works on lists:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] ['b', 'c']
>>> t[:4] ['a', 'b', 'c', 'd']
>>> t[3:] ['d', 'e', 'f']
If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to the
end. So if we omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold,
spindle or mutilate lists. A slice operator on the left side of an assignment can update multiple
elements:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t ['a', 'x', 'y', 'd', 'e', 'f,]
Like strings, lists can be indexed and sliced:
>>> list = [2, 4, "usurp", 9.0, "n"]
>>> list[2]
'usurp'
>>> list[3:]
[9.0, 'n']
Much like the slice of a string is a substring, the slice of a list is a list. However, lists differ from
strings in that we can assign new values to the items in a list:

>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0, 'n']

We can assign new values to slices of the lists, which don't even have to be the same length:

>>> list[1:4] = ["opportunistic", "elk"]


>>> list
[2, 'opportunistic', 'elk', 'n']

It's even possible to append items onto the start of lists by assigning to an empty slice:

>>> list[:0] = [3.14, 2.71]


>>> list
[3.14, 2.71, 2, 'opportunistic', 'elk', 'n']

Similarly, you can append to the end of the list by specifying an empty slice after the end:

St.Joseph’s Institute of Technology 50


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

>>> list[len(list):] = ['four', 'score']


>>> list
[3.14, 2.71, 2, 'opportunistic', 'elk', 'n', 'four', 'score']

You can also completely change the contents of a list:

>>> list[:] = ['new', 'list', 'contents']


>>> list
['new', 'list', 'contents']

The right-hand side of a list assignment statement can be any iterable type:

>>> list[:2] = ('element',('t',),[])


>>> list
['element', ('t',), [], 'contents']

With slicing you can create copy of list since slice returns a new list:

>>> original = [1, 'element', []]


>>> list_copy = original[:]
>>> list_copy
[1, 'element', []]
>>> list_copy.append('new element')
>>> list_copy
[1, 'element', [], 'new element']
>>> original
[1, 'element', []]

Note, however, that this is a shallow copy and contains references to elements from the original list,
so be careful with mutable types:

>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]

Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence
of a list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the
slice to be operated upon.

>>> list = [i for i in range(10) ]


>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[::2]
[0, 2, 4, 6, 8]
>>> list[1:7:2]
[1, 3, 5]

St.Joseph’s Institute of Technology 51


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
2. Explain in detail about list methods and list loops with examples.
Python provides methods that operate on lists. Some of the methods are
 Append()
 Extend()
 Sort()
 Pop()
For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t ['a', 'b', 'c', 'd']
Extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified. Sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t ['a', 'b', 'c', 'd', 'e']
Remove the item in the list at the index i and return it. If i is not given, remove the the last item in the
list and return it.
>>> list = [1, 2, 3, 4]

>>> a = list.pop(0)

>>> list

[2, 3, 4]

>>> a
List methods are all void; they modify the list and return None.

LIST LOOPS
Here are two functions that both generate ten million random numbers, and return the sum of the
numbers. They both work.
import random
joe = random.Random()
def sum1():
""" Build a list of random numbers, then sum them """ # Generate one random ˓→number
xs = []
for i in range(10000000):
num = joe.randrange(1000 )
xs.append(num) # Save it in our list
tot = sum(xs)
return tot
def sum2():
""" Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = joe.randrange(1000)
St.Joseph’s Institute of Technology 52
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
tot += num
return tot
print(sum1())
print(sum2())

3. Explain in detail about mutability and tuples with a Python program.


MUTABILITY
Unlike strings, lists are mutable, which means we can change their elements. Using the bracket
operator on the left side of an assignment, we can update one of the elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit [’pear’, ’apple’, ’orange’]
With the slice operator we can update several elements at once:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = [’x’, ’y’]
>>> print list [’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
We can also remove elements from a list by assigning the empty list to them:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = []
>>> print list [’a’, ’d’, ’e’, ’f’]
And we can add elements to a list by squeezing them into an empty slice at the desired location:
>>> list = [’a’, ’d’, ’f’]
>>> list[1:1] = [’b’, ’c’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’f’]
>>> list[4:4] = [’e’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]

Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you have to use
a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the
assignments. The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence
(string, list or tuple). For example, to split an email address into a user name and a domain, you could
write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
>>> print uname monty

St.Joseph’s Institute of Technology 53


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
>>> print domain python.org

4. What is tuple assignment? Explain it with an example.


It is often useful to swap the values of two variables. With conventional assignments, you have to use
a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the
assignments. The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence
(string, list or tuple). For example, to split an email address into a user name and a domain, you could
write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
>>> print uname monty
>>> print domain python.org

5. Is it possible to return tuple as values? Justify your answer with an example.


Yes, it is possible to return tuple as values. Example: Functions can return tuples as return values. For
example, we could write a function that swaps two parameters:
def swap(x, y):
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying
to encapsulate swap, which is the following tempting mistake:
def swap(x, y): # incorrect version
x, y = y, x
If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing x
inside swap makes x refer to a different value, but it has no effect on a in main. Similarly, changing y
has no effect on b. This function runs without producing an error message, but it doesn’t do what we
intended. This is an example of a semantic error.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and
remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t (2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print quot 2
>>> print rem 1

St.Joseph’s Institute of Technology 54


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Here is an example of a function that returns a tuple: def min_max(t): return min(t), max(t) max and
min are built-in functions that find the largest and smallest elements of a sequence. min_max
computes both and returns a tuple of two values.

6. What is Dictionary? Give an example [Anna Univ.2018][4m].


DICTIONARIES
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary
they can be (almost) any type. You can think of a dictionary as a mapping between a set of indices
(which are called keys) and a set of values. Each key maps to a value. The association of a key and a
value is called a key-value pair or sometimes an item. As an example, we’ll build a dictionary that
maps from English to Spanish words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in
function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print eng2sp {}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets: >>> eng2sp['one'] = 'uno' This line creates an item that maps from the key 'one' to
the value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key
and value:
>>> print eng2sp {'one': 'uno'}
This output format is also an input format. For example, you can create a new dictionary with three
items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same example on your
computer, you might get a different result. In general, the order of items in a dictionary is
unpredictable. But that’s not a problem because the elements of a dictionary are never indexed with
integer indices. Instead, you use the keys to look up the corresponding values:
>>> print eng2sp['two'] 'dos'
The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter. If the key isn’t
in the dictionary, you get an exception:
>>> print eng2sp['four'] KeyError: 'four'
The len function works on dictionaries; it returns the number of key-value pairs:

>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether something appears as a key in the
dictionary (appearing as a value is not good enough).
>>> 'one' in eng2sp True
>>> 'uno' in eng2sp False
To see whether something appears as a value in a dictionary, you can use the method values, which
returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search
algorithm, as in Section 8.6. As the list gets longer, the search time gets longer in direct proportion.
For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in
operator takes about the same amount of time no matter how many items there are in a dictionary.

St.Joseph’s Institute of Technology 55


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

7. Appraise the operations for dynamically manipulating dictionaries.[Anna Univ.2018][12m]


Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the following dictionary
contains the names of various fruits and the number of each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’: 312}
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory[’pears’]
>>> print inventory {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
Or if we’re expecting more pears soon, we might just change the value associated with pears:
>>> inventory[’pears’] = 0
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory) 4
DICTIONARY METHODS
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and values

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

8. Explain in detail about list comprehension .Give an example.


List comprehensions
List comprehensions provide a concise way to create lists. It consists of brackets containing an
expression followed by a for clause, then zero or more for or if clauses. The expressions can be
anything, i.e., all kinds of objects can be in lists. The result will be a new list resulting from
evaluating the expression in the context of the for and if clauses which follow it. The list
comprehension always returns a result list.

Syntax
The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a
list.

St.Joseph’s Institute of Technology 56


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
The basic syntax is
[ expression for item in list if conditional ]
This is equivalent to:
for item in list:
if conditional:
expression

List comprehension is a method to describe the process using which the list should be created. To do
that, the list is broken into two pieces. The first is a picture of what each element will look like, and
the second is what is done to get it.
For instance, let's say we have a list of words:

listOfWords = ["this","is","a","list","of","words"]

To take the first letter of each word and make a list out of it using list comprehension:

>>> listOfWords = ["this","is","a","list","of","words"]


>>> items = [ word[0] for word in listOfWords ]
>>> print items
['t', 'i', 'a', 'l', 'o', 'w']

List comprehension supports more than one for statement. It will evaluate the items in all of the
objects sequentially and will loop over the shorter objects if one object is longer than the rest.

>>> item = [x+y for x in 'cat' for y in 'pot']


>>> print item
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']

List comprehension supports an if statement, to only include members into the list that fulfill a certain
condition:

>>> print [x+y for x in 'cat' for y in 'pot']


['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>> print [x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ]
['cp', 'ct', 'ap', 'at']
>>> print [x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ]
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt']

9. Write a Python program for a) selection sort [Anna Univ jan 2018][8m] b) insertion sort.
Selection sort: (Jan 2019)
PROGRAM:
def selectionsort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
St.Joseph’s Institute of Technology 57
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
A[x] = A[y]
A[y] = tmp
aList = [54,26,93,17,77,31,44,55,20]
selectionsort(aList)
print(aList)

Insertion sort:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
10. Write a Python program for a) merge sort b) quick sort.
Merge sort:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)

St.Joseph’s Institute of Technology 58


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
print(alist)

Quicksort:
from random import randrange
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in xrange(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = randrange(start, end + 1)
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
def sort(lst):
quick_sort(lst, 0, len(lst) - 1)
return lst
print sort([-5, 3, -2, 3, 19, 5])
print sort([345,45,89,569,23,67,56,90,100])

11. a) Write a Python program to implement histogram.


def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])

b) Write a python program to perform linear search in a list. [Anna. Univ. Jan 2018] [8m]

Linear Search:
Linear search or sequential search is a method for finding a target value within a list. It sequentially
checks each element of the list for the target value until a match is found or until all the elements have
been searched
Algorithm:
Step1:Given a list L of n elements with values or records,L0 ... Ln-1 and key/target element K, linear
search is used to find the index/position of the target K in list L
Step2:Initialize a boolean variable found and set it to False initially
Step3:Start for loop with i ranging from 0 to the length of the list
Step4:Check if key element is equal to L[i]
Step5:if equals set found boolean variable to True print the position of the element found

St.Joseph’s Institute of Technology 59


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
break for loop
Step6:If the boolean variable found is equal to False after for loop, print that the element is not found
in the list
Python program:
lst = []
num = int(input("Enter size of list: \t"))
for n in range(num):
numbers = int(input("Enter any number: \t"))
lst.append(numbers)
x = int(input("\nEnter number to search: \t"))
found = False
for i in range(len(lst)):
if lst[i] == x:
found = True
print("\n%d found at position %d" % (x, i))
break
if not found:
print("\n%d is not in list" % x)

UNIT V
FILES, MODULES AND PACKAGES
PART- A (2 Marks)

1. What is a text file?


A text file is a file that contains printable characters and whitespace, organized in to lines separated
by newline characters. A text file is a sequence of characters stored on a permanent medium like a
hard drive, flash memory, or CD-ROM. Text file contain only text and has no special formatting
such as bold text, italic text, images, etc. Text files are identified with the .txt file extension.

2. What are the two parts in an error message?


The error message has two parts: the type of error before the colon and specification about the error
after the colon. Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero

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

4. Write a python program that counts the number of words in a file.


count.py
num_words = 0
f=open("test.txt","r")
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")

St.Joseph’s Institute of Technology 60


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
print(num_words)
test.txt
St.Josephs college of Engineering
Department of IT
Output:
7

5. Write a python program that counts the number of lines in a file.


count.py
count=0
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
for i in words:
count=count+1
print(count)
test.txt
St.Josephs college of Engineering
Department of IT
Output:
2

6. Difference between read(), readline() and readlines() methods.


read() - reads single character and return the character it read
readline() - reads only the first line of the file.
readlines() - reads all the lines and put them in 'list'(between these [ ]) and displays them with each
line ending with'\n'

7. What are the two arguments taken by the open() function?


The open function takes two arguments: First argument - name of the file and the second argument –
the mode of operation
Example:
f = open("test.dat","w")

8. 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.
Example:
f = open("test.dat","w") // f is the file object.

9. What information is displayed if we print a file object in the given program?


If we print a file object in the given program, the name of the file, mode and the location of the
object will be displayed.
Example:
f= open("test.txt","w")
print f

10. What is a pickle?

St.Joseph’s Institute of Technology 61


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any
type of object to a string suitable for storage in a database and then translate the strings back in to
objects.

11. What is an exception?


Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an
error message.
Example:
#Dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo

5. What are the error messages that are displayed for the following exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a. IndexError: list index out of range
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'

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

13. 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.
Syntax:

try:
// try block code
except:
// except block code
Example:
try:
print "Hello World"
except:
print "This is an error message!"

14. What are the two methods used in pickling?


The two methods used in pickling are
1. pickle.dump()
St.Joseph’s Institute of Technology 62
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
2. pickle.load()
To store a data structure, dump method is used and to load the data structures that are dumped, load
method is used.

15. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called _ _init_ _.py.
_ _init_ _.py can be an empty file but it is often used to perform setup needed for the package import
things, load things into path, etc.

16. What is the use of the format operator?


The format operator % takes a format string and a tuple of expressions and yields a string that
includes the expressions, formatted according to the format string.
Example:
>>> nBananas = 27
>>> "We have %d bananas." % nBananas
'We have 27 bananas.'

17. Write a Python script to display the current date and time. (AU - Jan 2018)
import datetime
print(“date and time”, datetime.datetime.now())

18. What are modules? (or) Write a note on modular design. Give example. (AU - Jan 2018,
Jan 2019)
 Modules are files containing Python definitions and statements (ex: name.py)
 Modules can contain executable statements along with function definitions.
 Each module has its own private symbol table used as the global symbol table all functions in the
module.
 Modules can import other modules.
Syntax:
import <modulename>
Example:
import os

19. What is a package?


Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Syntax:
from <mypackage> import
<modulename>
Example:
from Game.Level.start import select_difficulty

20. How do you delete a file in Python?


The remove() method is used to delete the files by supplying the name of the file to be deleted as
argument.
Syntax:
os.remove(filename)
St.Joseph’s Institute of Technology 63
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

Example:
import os
os.remove("ChangedFile.csv")
print("File Removed!")

21. How do you use command line arguments to give input to the program? (AU - May 2019)
In python, sys module provides access to any command-line arguments via sys.argv.
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.

Example:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

22. What are the different file operations?


In Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

23. How to view all the built-in exception in python.


The built-in exceptions using the local() built-in functions as follows.
Syntax:

>>> locals()['_ _builtins_ _']


This will return us a dictionary of built-in exceptions, functions and attributes.

24. What are the different file modes?


 'r' - Open a file for reading. (default)
 'w - Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
 'x' - Open a file for exclusive creation. If the file already exists, the operation fails.
 'a' - Open for appending at the end of the file without truncating it. Creates a new file if it does not
exist.
 't' - Open in text mode. (default)
 'b' - Open in binary mode.
 '+' - Open a file for updating (reading and writing)

25. What do you mean by IndexError?


IndexError is raised when index of a sequence is out of range.
Example:
>>> l=[1,2,3,4,5]
>>> print l[6]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
print l[6]
St.Joseph’s Institute of Technology 64
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
IndexError: list index out of range

26. Categorise the different types errors arises during programming. Interpret the following
python code (AU - May 2019)
>>>import os
>>>cwd = os.getcwd()
>>>print cwd
Basic types of errors:
Syntax Error:
Raised by the parser when a syntax error is encountered.
Semantic Error:
Raised by the parser when there is logical error in the program.

Here in the above given program, Syntax error occurs in the third line (print cwd)
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(cwd)?\

27. Find the syntax error in the code given:


while True print(‘Hello World’) (AU - Jan 2019)
In the above given program, colon is missing after the condition. The right way to write the above
program is
while True:
print(‘Hello World’)

PART B (16 MARKS)

1. Write a function that copies a file reading and writing up to 50 characters at a time. (or)
Explain the commands used to read and write into a file with example. (AU - Jan 2019)
def copyFile(oldFile, newFile):
f1=open(oldFile,"r")
f2=open(newFile,"w")
while True:
text=f1.read(50)
if (text==""):
break
f2.write(text)
f1.close()
f2.close()
return
copyFile("src.txt","dst.txt")

2. (a) Write a program to perform exception handling.


def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False

(b) Write a Python program to handle multiple exceptions.


St.Joseph’s Institute of Technology 65
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"

3. Write a python program to count number of lines, words and characters in a text file. (AU -
May 2019)
def wordCount():
cl=0
cw=0
cc=0
f=open("src.txt","r")
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()
wordCount()

4. Write a Python program to illustrate the use of command-line arguments.


import sys
def inputCmd():
print ("Name of the script:", sys.argv[0])
print ("Number of arguments:", len(sys.argv))
print ("The arguments are:", str(sys.argv))

Example:
Program:
import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))

St.Joseph’s Institute of Technology 66


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
Output
itlab@itlab-HP-ProDesk-400-G1-SFF:~/Desktop$ python command.py
Sample.txt:
This is an apple
This is a banana
Command:
#python file.py sample.txt
Words in the File Count
This 2
is 2
a 1
an 1
apple 1
banana 1

5. Mention the commands and their syntax for the following: get current directory, changing
directory, list, directories and files, make a new directory, renaming and removing directory.
(a)Get current directory: getcwd()
Syntax : import os
os.getcwd()
(a)Changing directory: chdir()
Syntax: os.chdir(‘C:\\Users’)
os.getcwd()
(b)List directories and files: listdir()
Syntax: os.listdir()
(c)Making a new directory: mkdir()
Syntax: os.mkdir(‘Newdir’)
(d)Renaming a directory: rename()
os.rename(‘Newdir’,’Newname’)
os.listdir()
(e)Removing a directory: remove()
os.remove(‘NewName’)

6. Write a Python program to implement stack operations using modules.


Module definition:
def getStack():
return[]
def isempty(s):
if s==[]:
return True
else:
return False
def top(s):
if isempty(s):
return None
else:
return s[len(s)-1]
def push(s,item):
St.Joseph’s Institute of Technology 67
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
s.append(item)
def pop(s):
if isempty(s):
return None
else:
item=s[len(s)-1]
del s[len(s)-1]
return item

Program to call stack :


import stack
def today():
mystack=stack.getStack()
for item in range(1,7):
stack.push(mystack,item)
print('Pushing',item,'to stack')
print ('Stack items')
while not stack.isempty(mystack):
item=stack.pop(mystack)
print('Poping',item,'from stack')

7. Write a program to illustrate multiple modules.


import wordcount,ex12,ex97
def test():
wordcount.wordCount()
def test2():
ex12.inputNumber()
def test3():
ex97.fun()
ex97.py:
def fun():
try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"
ex12.py:
def inputNumber () :
x = input ('Pick a number: ')
if x == 17 :
raise ValueError, '17 is a bad number'
return x
wordcount.py:
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")

St.Joseph’s Institute of Technology 68


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()

8. Write a Python program to dump objects to a file using pickle.


import pickle
def funMap():
cities = ["Chennai", "delhi","Mumbai","Kolkata"]
fh=open("cities.pck","w")
pickle.dump(cities,fh)
fh.close()
f=open("cities.pck","r")
cts=pickle.load(f)
print(cts)

9. Tabulate the different modes for opening a file and briefly explain the same. (16) (AU - Jan
2018, Jan 2019)
The argument mode points to a string beginning with one of the following sequences (Additional
characters may follow these sequences.):

``r'' Open text file for reading. The stream is positioned at the beginning of the file.

``r+'' Open for reading and writing. The stream is positioned at the beginning of the file.

``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.

``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of
the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of
any intervening fseek(3) or similar.

``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned
at the end of the file. Subsequent writes to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.

10. (a) Appraise the use of try block and except block in Python with example. (6) (AU - Jan
2018)
Handling Exceptions
The simplest way to handle exceptions is with a "try-except" block:
St.Joseph’s Institute of Technology 69
GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print "divide by zero"
If we want to examine the exception from code, you could have:
Toggle line numbers
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError as e:
z=e
print z

output:
integer division or modulo by zero

(b) Explain with example exceptions with argument in Python. (10) (AU - Jan 2018)
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the
problem. The contents of the argument vary by exception. You capture an exception's argument by
supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a variable
follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
Example
Following is an example for a single exception −
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.

St.Joseph’s Institute of Technology 70


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020

temp_convert("xyz");
This produces the following result −
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

11. a) Describe how exceptions are handled in python with necessary examples.(8) (AU - Jan
2019, May 2019)
Exception Handling:
When we have a code that can produce error, we can use exception handling. When runtime error occurs,
Python handles the exception avoiding program crash.
Handling a raised exception:
The part of the script that can raise an exception is defined within try block. Following try block, except
statement is given which gets executed if an exception is raised. If no errors are encountered while executing
the try block, except statements are ignored and else statement gets executed. If errors are encountered, else part
is ignored.
Type 1: try…except
try:
#Block that may or may not throw error
except:
#What to do if an error is encountered in try block?
Example:
try:
fp=fopen(‘testfile.txt’, ‘w’)
except:
print(“Error opening the file”)
Output:
CASE 1: #File opened
CASE 2: #File doesn’t open
Error opening the file
Type 2: try…except…else
try:
#Block that may or may not throw error
except <Error1>:
#What to do if Error1 is encountered in try block?
except <Error2>:
#What to do if Error2 is encountered in try block?
….
except <Errorn>:
#What to do if Errorn is encountered in try block?
else:
#What to do if there is no error?

Example:

St.Joseph’s Institute of Technology 71


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
try:
fp=fopen(‘testfile.txt’, ‘w’)
except IOError:
print(“Error opening the file”)
else:
print(“Success”)
fp.close()

Output:
CASE 1: #File opened
Success
CASE 2: #File doesn’t open
Error opening the file

Type 3: try…except…else…finally
try:
#Block that may or may not throw error
except:
#Block to handle error
else:
#What to do if there is no error?
finally:
#Always executed

Example:
try:
fp=fopen(‘testfile.txt’, ‘w’)
except:
print(“Error”)
else:
print(“Success”)
fp.close()
finally:
print(“End”)

Output:
CASE 1: #File opened
Success
End
CASE 2: #File doesn’t open
Error
End
In the above three types, a single try statement can contain multiple except statements which is useful when the
try statement can throw different types of exceptions. A generic except clause can be provided to handle any
type of exception.

St.Joseph’s Institute of Technology 72


GE8151 Problem Solving And Python Programming Common to All Branches 2019-2020
11. b) Discuss about the use of format operator in file processing.(8) (or) Explain about the file
reading and writing operations using format operator with python code.(16) (AU - Jan 2019,
May 2019)

FORMAT OPERATOR (%)


 The argument of write has to be a string, to put other values in a file convert to string, use ‘str’
Example:
>>>f1=open(“sample.txt”,“w”)
>>>f5.write(5)
TypeError
>>>f5.write((str(5))
 Use format operator, (%) , when applied to integer it becomes % modulus operator.
 When first operand is a string it becomes format operator (%)
Example:
run = 8
print(“%d”%run)
Output:
8 #the result is string ‘8’
Example:
>>>print(“India need %d runs”%3)
Output:
India need 3 runs
 If more than one format sequence, then second argument has to be a tuple.
Example:
>>>print(“India need %d runs in %d ball”%(3,1))
Output:
India need 3 runs in 1 ball
 The number of elemnts in tuple must match.
Example:
>>>print(“%d%d%d”%(1,2))
Output:
TypeError

St.Joseph’s Institute of Technology 73

Vous aimerez peut-être aussi