100% found this document useful (2 votes)
3K views40 pages

GE3151-Python-Unit-wise Solved Part-A Questions

The document defines algorithms and their properties. It discusses the differences between pseudocode and flowcharts. Pseudocode uses short descriptive English statements while flowcharts use diagrams. The key building blocks of algorithms are statements, states, control flow, and functions. Algorithms should be precise, unambiguous, and conclude in a finite number of steps. Pseudocode and flowcharts help represent the logic before coding but pseudocode is easier to convert to code.

Uploaded by

R.Mohan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (2 votes)
3K views40 pages

GE3151-Python-Unit-wise Solved Part-A Questions

The document defines algorithms and their properties. It discusses the differences between pseudocode and flowcharts. Pseudocode uses short descriptive English statements while flowcharts use diagrams. The key building blocks of algorithms are statements, states, control flow, and functions. Algorithms should be precise, unambiguous, and conclude in a finite number of steps. Pseudocode and flowcharts help represent the logic before coding but pseudocode is easier to convert to code.

Uploaded by

R.Mohan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


UNIT I - ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
1. Define Algorithm.
 Sequence of instructions for solving a problem or a step by step procedure for solving a
problem.
 An algorithm is a set of instructions designed to perform a specific task. This can be a simple
process, such as multiplying two numbers, or a complex operation, such as playing a
compressed video file
Example: Algorithm to print "Good Morning"
Step1: Start the program.
Step2: Display the message "Good Morning" to the user.
Step3: Stop the program.

2. Distinguish between pseudo code and flowchart.


S.No Pseudo code Flowchart
1. Short, readable, formally styled Diagrammatic representation of the logic of the
English languages of an algorithm. algorithm.
2. Knowledge about the programming No basic knowledge about programming is
language is needed. needed.
3. Beginners find it difficult to Beginners find it easy to understand.
understand.
4. Understanding the flow of data and Understanding the flow of data and control is
control is difficult. easy.
5. Keywords is used in pseudo code like No keywords are used in flowchart.
BEGIN, END,IF, THEN, ENDIF, etc.
6. Easier to convert into source code as Cannot be easily converted to the source code
pseudo code relatively maps to the as flowchart is a diagrammatic representation.
syntax.

3. What are the building blocks of algorithm?


Building blocks of an algorithm are,
Statement: a single action in a computer.
State: Transition from one process to another within a specified condition within a timeframe is
state.
Control flow: Process of executing the individual statements in the given order is called control
flow. Control flow types include Sequence, Selection and iteration.
Functions: A subprogram which consists of the block of code that performs a particular task.

Page 1 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

4. State the properties of algorithm.


Algorithm should be ,
 written in simple English
 each and every instruction should be precise and unambiguous
 Instructions in an algorithm should not be repeated infinitely
 Algorithm should conclude after a finite number of steps
 Algorithm should have an end point
 Results should be derived only after the algorithm terminates.

5. State the Qualities of an algorithm.


The Qualities of an algorithm are,
Time – To execute a program, the computer system takes some amount of time. The lesser is the
time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The
lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem,
some of these may provide more accurate results than others, and such algorithms may be
suitable.

6. What is meant by problem solving?


 It is the systematic approach to solve the problem and create number of solutions. Starts with
the problem specification and ends with a correct program.
Example:
Finding greatest of two numbers includes , different logic for comparing two numbers as
defining the variables as a & b , logics include a>b or a<b or a%b == a or a%b ==b or any
logic can be defined and finally the program is implemented.

7. What is called control flow?


 The process of executing the individual statements in a given order is called the control flow.
The control can be executed in three ways,
1. Sequence 2. Selection 3. Iteration.

8. What are the benefits of using functions.


 Reduction in line of code
 Code reuse and Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

Page 2 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

9. Define a flowchart.
 Flow chart is defined as graphical representation of the logic for problem solving.
 The purpose of flowchart is making the logic of the program clear in a visual representation.
 A flowchart is a type of diagram that represents a workflow or process.
 The flowchart shows the steps as boxes of various kinds, and their order by connecting the
boxes with arrows. This diagrammatic representation illustrates a solution model to a given
problem.

10. What are the symbols used in a flowchart?

11. Rules for drawing a flowchart.


1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow

lines may leave the decision symbol.


5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.


Page 3 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

7. Intersection of flow lines should be avoided.


12. What are the advantages of flowchart?
1. Communication: - Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: -With the help of flowchart, problem can be analyzed in more effective way.
3. Proper documentation: - Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part.
13. What are the disadvantages of flowchart?
1. Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may require re-drawing
completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
4. Cost: For large application the time and cost of flowchart drawing becomes costly.
14. What is a psuedocode and write its properties.
 Pseudo code consists of short, readable and formally styled English languages used for
explain an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to understand the general
working of the program, because it is not based on any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
 Pseudo code can’t be compiled and executed.
 There is no standard syntax for pseudo code.
15. what are the guidelines for writing the psuedocode?
 Write one statement per line
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent
16. What are the keywords in pseudocode?
The following gives common keywords used in pseudocodes.

Page 4 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

1. //: This keyword used to represent a comment.


2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
17. List the advantages and disadvantages of pseudocode.

Advantages:

to flowchart.

with converting a flowchart to programming language.


Disadvantages:

rds for writing pseudo codes.

compared to flowchart.
18. What is a programming language?
A programming language is a set of symbols and rules for instructing a computer to perform specific
task. Each programming language has a flow of execution and a unique syntax to be followed.
It categorizes as, High level language, low level language and assembly language.
19. Differentiate high level, low level and assembly level languages.

Page 5 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

20. What are the simple strategies for developing an algorithm?


Simple strategies for developing an algorithm include Iteration and Recursion
Iteration: Sequence of statements executed repeatedly until a specified condition is satisfied is
iteration.
Recursion: A function that calls itself again and again until a specified condition is satisfied is called
recursion.

21. List down the problem solving techniques.


The problem solving techniques are
Algorithm
Flowchart
Psuedocode
22. What are the steps in algorithmic problem solving?

Low level/ Machine level Assembly level language High level language
language
Programs are written only in Programs are wirtten in Programs are written using
0s and 1s ie. binary will be mnuemonics like ADD A,B English words and symbols.
understood by the computer.
There is no conversion The Assembler converts the The compiler and the
required. assembly level language to the interpreter does the conversion
machine language. of the high level languages to
the machine language.
Execution is faster as there is Execution time is fast Takes more execution time
no translation needed. compared to the high level than the assembly level
language but slow compared language and the low level
to the low level language as language.
translation is required.
Debugging is difficult and Debugging is easy when Debugging can be done faster
consumes more time to debug. compared to low level then the other two languages.
language , but not easy as high
level language.
It is translation free. Translation is required Translation is required
It is machine dependent. Machine Dependent Machine Independent
Hard to learn and find errors. Medium difficulty with Easy to learn and debug , but
respect to learning when less efficient as translation
compared to low level takes more time.
language
The steps are ,
Page 6 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

 Understanding the problem,


 Decide on computational means,
 Design an algorithm
 Prove correctness
 Analyze the algorithm
 Code the algorithm
23. Write an algorithm to accept two numbers and compute the SUM.

Step1: Start the program


Step2: Get the inputs from the user and assign them to variables a and b.
Step3: Calculate the value for variable SUM , using SUM = a+b
Step4: display the output stored in the variable , SUM
Step5: Stop the program.
24. Name the four types of scalar objects Python has.
The commonly used scalar types in Python are
int - Any integer like 10, -20
float - floating point number , 10.5, 21.3
complex - numbers with real part and imaginary part, 3+4j
bool - True or False with values 1 or 0.
str - a sequence of characters
bytes - sequence of unsigned 8 bit entiites.
25. Differentiate Compiler and Interpreter.

Compiler Interpreter
Compiler takes entire program as input. Interpreter takes single instruction as input.
Intermediate object code is generated. No intermediate object code is generated.
Conditional control statements executes faster. Conditional control statements executes
slower.
Memory requirement is more. Memory requirement is less.
Program need not be compiled every time. Every time a high level program is converted
into a low level program.
Errors are displayed after entire program is Error are displayed after every instuction.
checked.
Ex: C Compiler Ex: Python.

16 Mark questions:
1. Write an algorithm and program to find minimum in a list.

Page 7 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

2.Discuss in detail about symbols used in flowchart and also summarize the advantage and
disadvantage of flowchart.
3. Discuss in detail Towers of Hanoi Problem
4. Explain in detail about Building Blocks of Algorithm
5. Explain in detail about the steps involved in Algorithmic problem solving.
6.Explain in detail about the simple strategies for developing an algorithm.
7. Write the algorithm, flowchart and pseudocode for inserting a card in a list of sorted cards.
8. Write the algorithm and flowchart and pseudocode for guessing an integer in a range.

Page 8 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT II DATA, EXPRESSIONS, STATEMENTS

PART – A (2 MARKS)

1. Name the four types of Scalar objects.(D/J-18)


A scalar is a type that can have a single value such as 5, 3.14, or ‘Bob’.
The commonly used scalar types in Python are:
Int : Any integer
Float : Floating point number
Complex : Numbers with an optional imaginary component
Bool : True or false
Str : A sequence of characters
Bytes : A sequence of unsigned entities for manipulating binary data.
None : Null or NIL equivalent
2. What is a tuple? How literals of type tuple are written? Give
example.(D/J-18).
A tuple is created by surrounding objects with ()'s and separating the items
with commas (,). An empty tuple is empty ()'s. An interesting question is
how Python tells an expression from a 1-tuple. A 1-element tuple has a
single comma: (1,). An expression lacks the comma: (1). A pleasant
consequence of this is that an extra comma at the end of every tuple is legal;
for example, (9, 10, 56, ).
Examples:
xy= (2, 3)
personal= ('John',14,5*12+6)
singleton= ("hello",)
The elements of a tuple do not have to be the same type. A tuple can be a
mixture of any Python data types, including other tuples
3. Outline the logic to swap the contents of two identifiers without using
third variable.(A/M-19)
Logic:
a=int(input(“Enter the value of a”))
b=int (input(“Enter the value of b”))
a=a+b
b=a-b
a=a-b
print(a,b)

4. State about Logical operators available in python language with


example. (A/M -19)
In Python, the primary logical operators are AND, OR, and NOT.
A boolean expression or valid expression evaluates to one of two states True
or False. Python provides the boolean type that can be either set to False or
True. Many functions and operations return boolean objects.
AND OR NOT
1 1 1 1 1 1 1 0
1 0 0 1 0 1 0 1
0 1 0 0 1 1
0 0 0 0 0 0

5. What are keywords? Give examples.(D/J-2019)


Keywords are the reserved words in Python. We cannot use a keyword as
variable name, function name or any other identifier.

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


6. State the reason to divide the program into functions.(D/J-2019)
Function are used for divide a large code into module, due to this we can
easily debug and maintain the code. For example if we write a
calculator programs at that time we can write every logic in a separate
function (For addition sum(), for subtraction sub()). Any function can be
called many times.
7. Define assignment statement.
A statement that assigns a value to a name (variable). To the left of
the assignment operator, =, is a name. To the right of the assignment
operator is an expression which is evaluated by the Python interpreter and
then assigned to the name.

8. Define Identifiers in Python.


A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to
9)
9. What is the comment statement in python?

A comment is text that doesn't affect the outcome of a code, it is just a piece
of text to let someone know what you have done in a program or what is
being done in a block of code. In python we use # special character to start
the comment. Lets take few examples to understand the usage.
# This is just a comment. Anything written here is ignored by Python

10.Define variables in python.


In Python, variables are a storage placeholder for texts and numbers. It must
have a name so that you are able to find it again. The variable is always
assigned with the equal sign, followed by the value of the variable.

11.Explain Input and output statements in python.


In Python, we have the input() function to allow this. The syntax for input
() is input([prompt]) where prompt is the string we wish to display on the
screen.
Ex . : a = int(input(“Enter the value of a”))
We use the print() function to output data to the standard output device
(screen).
print(a)
12.List the data types in python.

13.What are the operators in Python?


Arithmetic Operators
Relational Operators
Assignment Operators
Bitwise Operators
Logical Operators
Membership Operators
Identity Operators
14.Define functions in python?
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()

15. Give the syntax for variable length arguments.


The special syntax, *args and **kwargs in function definitions is used to
pass a variable number of arguments to a function. The single asterisk form (
*args ) is used to pass a non-keyworded, variable-length argument list, and
the double asterisk form is used to pass a keyworded, variable-length
argument list Syntax for a function with non-keyword variable arguments is
this –
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite return [expression].
16.Point out the difference between recursive and iterative technique.
• Recursive approach: In recursive approach the function calls itself until
the condition is met. And it is slower than iteration, which means it uses
more memory than iteration. Recursion is like a selection structure, and
which makes code smaller and clean. And a function partially defined by
itself. Here tracing the code will be more difficult in the case large programs.
• Iterative approach: Iterative approach is a repetition process until the
condition fails, here loops are used such as for, while etc. Here code may be
longer but it is faster than recursive. And it consumes less memory
compared to recursive approach. If the loop condition is always true in such
cases it will be an infinite loop
17.What are the various operators in python.
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
18.Compose the importance of indentation in python.
Python programs get structured through indentation, i.e. code blocks are
defined by their indentation. In Python language, indentation is used to
determine the structure instead of using braces or keywords. Here,
indentation is meaningful to the interpreter. It is more than only clarity. The
reader will be comfortable enough to go through it and understand the
meaning. Proper code indentation will make it.
19.What is meant by interpreter?
An interpreter is a computer program that executes instructions written in a
programming language. It can either execute the source code directly or
translate the source code in a first step into a more efficient representation
and executes this code.

20.How will you invoke the python interpreter?


The Python interpreter can be invoked by typing the command "python"
without any parameter followed by the "return" key at the shell prompt.
21.What is meant by interactive mode of the interpreter?
Interactive mode is a command line shell which gives immediate feedback
for each statement, while running previously fed statements in active
memory. As new lines are fed into the interpreter, the fed program is
evaluated both in part and in whole.
22.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'
23.What is a value? What are the different types of 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.
24.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.
25.Define keyword and enumerate some of the keywords in Python.
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.
26.Define statement and what are its types?
A statement is an instruction that the Python interpreter can execute. There
are two types of statements: print and assignment statement.
27.What do you meant by an assignment statement?
An assignment statement creates new variables and gives them values: Eg 1:
Message = 'And now for something completely different' Eg 2: n = 17
28. What is tuple?
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);
29.What is an expression?
An expression is a combination of values, variables, and operators. An
expression is evaluated using assignment operator. Examples: Y=x + 17
30.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.
31.What is the order in which operations are evaluated?
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.
32.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
33.What is the symbol for comment? Give an example.
# is the symbol for comments in Python. Example: # compute the percentage
of the hour that has elapsed
34.What is function call?
A function is a named sequence of statements that performs a computation.
When we define a function, we specify the name and the sequence of
statements. Later, we can “call” the function by its name called as function
call.
35.Identify the parts of a function in the given example.
>>> betty = type("32")
>>> print betty
The name of the function is type, and it displays the type of a value or
variable. The value or variable, which is called the argument of the function,
is enclosed in parentheses. The argument is 32. The function returns the
result called return value. The return value is stored in betty.
36.Define a local variable and global variable?
A variable defined inside a function. A local variable can only be used inside
its function.
A variable defined outside a function. A global variable can be used
anywhere inside a program.

37.What is the output of the following?


a. float(32)
b. float("3.14159")
Output:
a. 32.0 - The float function converts integers to floating-point numbers.
b. 3.14159 - The float function converts strings to floating-point numbers.
38.What do you mean by flow of execution?
In order to ensure that a function is defined before its first use, we 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.
39.Give the syntax of function definition.
def NAME( LIST OF PARAMETERS ): STATEMENTS
40.Explain the concept of floor division.
The operation that divides two numbers and chops off the fraction part is
known as floor division.
41.What is type conversion? Give example.
Automatic method to convert between data types is called type conversion.
For mathematical operators, if any one operand is a float, the other is
automatically converted to float.
Eg: >>> minute = 59
>>> minute / 60.0 0.983333333333
42.Write a math function to perform √2 / 2.
>>> math.sqrt(2) / 2.0 0.707106781187 22.
43.What is meant by traceback?
A list of the functions that tells us what program file the error occurred in,
and what line, and what functions were executing at the time. It also shows
the line of code that caused the error.

PART – B (16 MARKS)

1. Sketch the structures of interpreter and compiler. Detail the difference


between them. Explain how python works in interactive mode and script
mode with examples.( D/J -19)
2. Summarize the precedence of mathematical operators in python.( D/J -19)
3. Explain the syntax and structure of user defined functions in Python with
examples. Also discuss about parameter passing in functions.( D/J -19)
4. Write a python function to swap the values of two variables.( D/J -19)
5. Describe about the concept of precedence and associativity of operators with
example.(A/M-19)
6. Mention the list of keywords available in Python. Compare it with variable
name.(A/M-19)
7. What are statements? How are they constructed from variable and
expressions in Python? (A/M-19)
8. What is a numeric literal? Give examples.(D/J-18)
9. Appraise the arithmetic operators in Python with an example. (D/J-18)
10.Outline the operator precedence of arithmetic operators in Python. (D/J-18)
11.Write a Python program to exchange the value of two variables. (D/J-18)
12.Write a Python using function to find the sum of first “n” even numbers and
print the result. (D/J-18).
13.Explain various types of operators used in Python.
14.Explain Values & types supported in Python.
15.What are the different function prototypes? Explain it with suitable example.
16.What are the different types of arguments available in python.
17.Explain in detail the different ways of importing a module in python.
18. Write a python program to circulate values of n variables.
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


UNIT III - CONTROL FLOW, FUNCTIONS
PART- A (2 Marks)

1. What a python program to accept two inputs, find the greatest and print the result ?
2. State the reasons to divide programs into functions.
3. Present the flow of execution for a WHILE statement.
4. Comment with an example on the use of local and global variables with the same identifier
name.
5. State about Logical Operators available in Python programming language.
6. 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.
Eg : >>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings:

7. What are the different types of operators?


 Arithmetic Operator (+, -, *, /, %, **, // )
 Relational operator ( == , !=, <>, < , > , <=, >=)
 Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
 Logical Operator (AND, OR, NOT)
 Membership Operator (in, not in)
 Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary left
shift), >> (binary right shift))
 Identity(is, is not)

8. 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:
Eg:
>>> remainder = 7 % 3
>>> print(remainder)
1
So 7 divided by 3 is 2 with 1 left over.

9. Explain relational operators.

Page 1 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

The == operator is one of the relational operators; the others are:


x! = y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

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

11. What is conditional execution?


The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
Syntax:
if:
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.

12. 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.
Example:
if x%2 == 0:
print("x is even")
else:
print("x is odd")

13. What are chained conditionals?

Page 2 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

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

14. Explain while loop with example.


Example:
def countdown(n):
while (n > 0):
print(n)
n = n-1
print("Blastoff!")
More formally, here is the flow of execution for a while statement:
1.Evaluate the condition, yielding True or False.
2. If the condition is false, exit and continue execution at the next statement.
3. If the condition is true, execute the body and then go back to step 1

15. Explain ‘for loop’ with example.


The general form of a for statement is
Syntax:
for variable in sequence:
code block

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

16. What is a break statement?

Page 3 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

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:
while True:
line = raw_input('>')
if (line == "done"):
break
print(line)
print("Done ! ")

17. 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 num in range(2,10):
if (num%2==0):
print(“Found an even number”, num)
continue
print(“Found a number”, num)

18. 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(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result

19. What is recursion?

Page 4 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

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))

20. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a
variable on the top of the script or module, the variable is called global variable. The variables
that are defined inside a class or function is called local variable.
Example:
def my_local():
a=10
print(“This is local variable”)

Example:
a=10
def my_global():
print(“This is global variable”)

21. Compare string and string slices.


A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg:
>>> s ='Monty Python'
>>> print(s[0:5])
Monty
>>> print(s[6:12])
Python

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

Page 5 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

23. Mention a few string functions.


captilize() – to capitalize first character of string
count(sub) – to count number of occurrences of sub in string
lower() – to convert a string to lower case
split() – to get a list of words in string
isalpha() – to check whether the string contains only English alphabets or not.

24. What are string methods?


 A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters:
 Instead of the function syntax upper(word), it uses the method syntax word.upper() .
>>> word = 'banana'
>>> new_word = word.upper()
>>> print(new_word)
BANANA

25. 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.
Eg:
import string

26. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
Eg:
def bar():
pass
If the function bar() is called, it does absolutely nothing.

Page 6 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

UNIT III - CONTROL FLOW, FUNCTIONS


PART- B (16 Marks)
1. Discuss in details about various Looping Statements in Python with suitable example.
2. Explain briefly about various Iterative Statements in Python with suitable example.
3. Discuss in details about various Conditional Statements in Python with suitable example.
4. Explain briefly about various Decision Making Statements in Python with examples.
5. Explain with an example while loop, continue statement and break statement in Python.
6. Python Strings are immutable. Justify your answer with an example.
7. Write a python program to perform Binary Search. Trace it with a set of input values.
8. Write a python program to perform Linear Search. Trace it with a set of input values.
9. Discuss in detail about Recursion. Write a program to find the factorial of a given number
using recursion.
10. Write a python program to find the factorial of a given number with recursion and without
using recursion.
11. Discuss about various string operations and methods with necessary examples.
12. Discuss in details about various functions' argument types with suitable examples.
13. Explain about each function prototype with necessary illustrative programs.
14. Write a python program to print first "N" numbers in Fibonacci Series.
15. Discuss in detail about List Comprehension with example.
16. Discuss in detail about various operators in python with example.

Page 7 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


UNIT IV - COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
PART- A (2 Marks)

1. What is a list?
 A list is an ordered set of values, where each value is identified by an index.
 Values in the list are called elements / items. It can be written as a list of comma-separated
items (values) between square brackets [ ].
 Items in the lists can be of different data types and List is a mutable type.

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


>>> [0] * 4
[0, 0, 0, 0]

>>>[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)list[:4] c) list[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
>>> list[:4]
[’a’, ’b’, ’c’, ’d’]
>>> list[3:]
[’d’, ’e’, ’f’]

4. Mention any 5 list methods.


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

5. State the difference between lists and dictionary.


List is a mutable type meaning that it can be modified whereas dictionary is immutable and is a key
value store. Dictionary is not ordered and it requires that the keys are hashable whereas list can store
a sequence of objects in a certain order.

6. 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:

Page 1 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

>>> numbers = [17, 123]


>>> numbers[1] = 5
>>> print numbers [17, 5]

7. What is aliasing in list? Give an example.


Creating a copy of a list is called aliasing. When you create a copy both list will be having the same
memory location. Changes in one list will affect another list. Aliasing refers to having different
names for same list values.
Example:
>>> a = [1, 2, 3]
>>> b=a
>>> b is a
>>> True
>>> a[0]=5
>>> print(a)
[5,2,3]
>>> print(b)
[5,2,3]

8. Define cloning in list.


To avoid the disadvantages of copying we are using cloning. creating a copy of a same list of
elements with two different memory locations is called cloning. Changes in one list will not affect
locations of another list. Cloning is a process of making a copy of the list without modifying the
original list. The following are the three ways to clone a list
1. Slicing
2. list()method
3. copy()method
Example:
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False

9. Explain List parameters with an example.


In python, arguments are passed by reference.
If any changes are done in the parameter which refers within the function, then the changes
also reflects back in the calling function.
Page 2 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

When a list to a function is passed, the function gets a reference to the list.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change the
same list that the argument is referencing.
Example
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
output
[2,3,4,5]

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


 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.
 It is often useful to swap the values of two variables.

11. Define key-value pairs.


 An element in dictionary has a key: value pair. All elements in dictionary are placed inside
the curly braces i.e. { }.
 Elements in Dictionaries are accessed via keys and not by their position. The values of a
dictionary can be any data type. Keys must be immutable data type (numbers, strings, tuple).
 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.

12. Define dictionary with an example.


 Dictionary is an unordered collection of elements. An element in dictionary has a key: value
pair. All elements in dictionary are placed inside the curly braces i.e. { }.
 Elements in Dictionaries are accessed via keys and not by their position. The values of a
dictionary can be any data type.
 Keys must be immutable data type (numbers, strings, tuple).
Example:
>>> a = {1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}

Page 3 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

13. How to return tuples as values?


A Tuple is a comma separated sequence of items. It is created with or without ( ). A function
can return one value. if you want to return more than one value from a function. we can use tuple
as return value.
Example:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enterb value:"))
r,q = div(a,b)
print("reminder:",r)
print("quotient:",q)

14. List two dictionary operations.


i. del - removes key-value pairs from a dictionary
ii. len() - returns the number of key-value pairs

15. Define dictionary methods with an example.


 A method is similar to a function—it takes arguments and returns a value— but the syntax is
different.
>>> a = {1: 'ONE', 2: 'two', 3: 'three'}
>>> a.keys()
dict_keys([1, 2, 3])
>>> a.values()
dict_values(['ONE', 'two', 'three'])

16. Define List Comprehension.


 List comprehensions provide a concise way to apply operations on a list. It creates a new list
in which each element is the result of applying a given operation in a list.
 It consists of brackets containing an expression followed by a “for” clause, then a list. The list
comprehension always returns a result list.
Syntax:
list = [ expression for item in list if conditional ]
Example:
>>> L = [x**2 for x in range(0,5)]
>>> print(L)
[0, 1, 4, 9, 16]

Page 4 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

17. What are list operations?


i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Updating
vi. Membership
vii. Comparison

18. How to create a list in python? Illustrate the use of negative indexing of list with example.
 List is an ordered sequence of items. Values in the list are called elements / items. It can be
written as a list of comma-separated items (values) between square brackets [ ]. Items in the
lists can be of different data types.
Example:
>>> a = [1,2,3]
>>> print(a)
[1,2,3]
 Negative Indexing
Python supports negative indexing for a sequence types like list. The last item on the list
takes the -1 index and second to the last item has the -2 index and so on.
>>> a = [1,2,3]
>>> print(a[-1])
3
>>> print(a[-2])
2

19. Compare list, tuple and dictionary.

20. What are the different ways to create a list?


my_list = []
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4]
my_list = [0 for i in range(50)]

21. What is mutability?


 Lists are mutable (can be changed). Mutability is the ability for certain types of data to be
changed without entirely recreating it.
 An item can be changed in a list by accessing it directly as part of the assignment statement.

Page 5 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

 Using the indexing operator (square brackets [ ]) on the left side of an assignment, one of the
list items can be updated.

22. Define Tuple.


 A tuple is same as list, except that the set of elements is enclosed in parentheses instead of
square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
 But tuple can be converted into list and list can be converted in to tuple.

23. Define list slicing.


 List slicing is an operation that extracts a subset of elements from an list and packages them
as another list.
Syntax: Listname [ start : stop : steps ]
>>> a=[9,8,7,6,5,4]
>>> a[0:6:2]
[9, 7, 5]

24. What are the benefits of tuple?


i. Tuples are faster than lists.
ii. If the user wants to protect the data from accidental changes, tuple can be used.
iii. Tuples can be used as keys in dictionaries, while lists can't.

PART B (16 Marks)


1. Explain in detail about list, list operations and list slices.
2. Explain in detail about list methods and list loops with examples.
3. Explain in detail about mutability and tuples with a Python Program.
4. What is tuple assignment? Explain it with an example.
5. Is it possible to return tuple as values? Justify your answer with an example.
6. Explain in detail about dictionaries operations and methods.
7. Write a python program to implement insertion sort, selection sort, merge sort and histogram.
8. Demonstrate with code the various operations that can be performed on tuples.
i. What is dictionary in Python? Give examples.
ii. Appraise the operations for dynamically manipulating dictionaries.
9. i. write a short note on cloning and aliasing.
ii. Write a short note on Advanced list processing.

Page 6 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q & A

10. Explain the following:


i. List Slicing & List Mutability
ii. List Accessing Methods & List Comprehension
11. Outline the algorithm and write a python program to sort the numbers in ascending order using
merge sort.
12. Describe Built in functions with
i. Tuples
ii. List
iii. Dictionaries
13. Explain in detail about List as argument and tuple as return value with an example.

Page 7 of 7
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


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

1. What is a text file?


 A text file is a type of digital, non-executable file that contains letters, numbers, symbols
and/or a combination. It enables the creation and storage of text without any special
formatting such as bold text, italic text, images, etc.
 A text file is a file that contains printable characters and whitespace, organized in to lines
separated by newline characters.
 Text files are also known as flat files or ASCII files.

2. Write a python program that writes “Hello world” into a file.


f =open("example.txt","w") # open() is used to open a new file in WRITE Mode
f.write("hello world") # write() - accepts a string which is to be written on the file
f.close() # close() is used to flush the content in file and to close it.

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


f = open("test.txt","r") # open() is used to open a new file in READ Mode
content = f.read() # read() retrieves all characters in the file
words = content.split() # split() is a string function, used to split the content into words
wc = len(words) # len() gives no. of words in the list
print("No. of Words : ", wc)

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


The open function takes two arguments :
1. Name of the file
2. Mode of operation.
Example: f = open("test.dat","w")

5. What is a file object?


 A File object holds information about a raw file in the harddisk. A File object is NOT the
actual file. It does not contain the data that the file holds.
 It is an object that holds methods that affect a particular file or directory. It works as an
interface between a program and the functions of the operating system that do the actual
file manipulation.
 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.

Page 1 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

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


fp = open("test.txt","w")
print(fp)
Output:
<_io.TextIOWrapper name='test.txt' mode='w' encoding='cp1252'>

i. Name of the File Pointer Class


ii. Name of the file
iii. Access mode
iv. Encoding Scheme

7. What is an Exception?
 Even if a program is syntactically correct, it may cause an error when an attempt is made
to execute it. Errors detected during execution time are called Exceptions and are not
unconditionally fatal.
 Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
 For example, dividing by zero creates an exception:
print(55/0)
Output:
ZeroDivisionError: integer division or modulo

8. 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
Answer:
a. IndexError: list index out of range
b. KeyError: 'variablename' is not defined
c. IOError: [Errno 2] No such file or directory: 'filename'

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


 The string printed as the exception error type, is the name of the built-in exception that
occurred. Standard exception names are built-in identifiers. The rest of the line provides
detail based on the type of exception and what caused it.
 The error message has two parts:
i. The type of error before the colon
ii. Detailed information about the error after the colon.
Example: SyntaxError: invalid syntax
Page 2 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

10. Define Exception Handling. Give its general syntax structure.


 Exception handling is the process of responding to the runtime error occurred during
computation – anomalous or exceptional conditions requiring special processing – often
disrupting the normal flow of program execution.
 An exception occurs when an unexpected event happens that requires special processing.
Examples include a user providing abnormal input, a file system error being encountered
when trying to read or write a file, or a program attempting to divide by zero.
Syntax:
try:
<< Block of Normal Code >>
except <<Exception_Class>>:
<< Block of Exception handling statement >>
finally:
<< Block of final Statements >>

11. How do you handle the exception when you try to open a non-existent file?
filename = input("Enter the file name : ")
try:
f = open (filename, "r")
except IOError:
print("There is no file named " , filename)

12. 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.
 If there are more no. of except blocks, system searches for the best match and executes the
respective exception handling statements in that block.

13. 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:
i. The exception type
ii. Specific information about the error.
 Example:
raise NameError("Error Message")

Page 3 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

14. What is a pickle?


 Python pickle module is used for serializing and de-serializing a Python object structure.
 Any object in Python can be pickled so that it can be saved on disk. What pickle does is
that it “serializes” the object first before writing it to file. Pickling is a way to convert a
python object (list, dict, etc.) into a character stream.
 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.

15. What are the two methods used in pickling?


The two methods used in pickling are pickle.dump() and pickle.load().
i. dump() - To store a data structure
ii. load() - To load the data structures that are dumped

16. What is the use of the format operator?


 Python uses C-style string formatting to create new, formatted strings.
 The % operator is used to format a set of variables enclosed in a "tuple" (a fixed size list),
together with a format string, which contains normal text together with "argument
specifiers", special symbols like "%s" and "%d".
 Example:
name = "John"
print( " Hello %s ! " % name )
Output:
Hello John !

17. What do you mean a module?


 A module is a file that contains one or more related functions grouped together. To reuse
the functions of a given module, we need to import the module.
 To create a module just save the code, you want in a file with the file extension .py
 Once a module is created, it can be used after importing it.
Syntax:
import <modulename>

18. What is a package?


 A package is basically a directory with Python files and a file with the name __init__.py.
This means that every directory inside of the Python path, which contains a file named
__init__.py, will be treated as a package by Python. It's possible to put several modules
into a Package.
Page 4 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

 Packages are namespaces that contain multiple packages and modules themselves. They
are simply directories.
Syntax:
from <mypackage> import <modulename>

19. What is the special file that each package in Python must contain?
 Each package in Python must contain a special file called __init__.py
 Files name __init__.py are used to mark directories on disk as Python package
directories.
 The __init__.py file is usually empty, but can be used to export selected portions of the
package under more convenient name, hold convenience functions, etc.

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.
 This method is defined in OS module in Python Library.
Syntax: os.remove(filename)

21. How do you use command line arguments to give input to the program?
 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.

22. Write a Python Script to display to current date and time.


import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

23. Write a note on Modular Design.


 In modular programming, modularity refers to the compartmentalization and interrelation
of the parts of a software package.
 In software design, modularity refers to a logical partitioning of the "software design" that
allows complex software to be manageable for the purpose of implementation and
maintenance.
 A modular design can be characterized by functional partitioning into discrete scalable,
reusable modules; rigorous use of well-defined modular interfaces; and making use of
industry standards for interfaces.
Page 5 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

24. Tabulate the different modes of accessing a file.

Mode Modes & Description


Opens a file for reading only. The file pointer is placed at the beginning of the file. This
r
is the default mode.
Opens a file for reading only in binary format. The file pointer is placed at the beginning
rb
of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the beginning of the
r+
file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
w
exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
wb
file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
w+
the file does not exist, creates a new file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file exists. That
a is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.

25. Why do you need exceptions and exception handling mechanism?


 The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling.
 Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them.

26. What is File Buffering?


 A buffer stores a chunk of data from the file stream (File Pointer) until it is consumed, at
which point more data is brought into the buffer.
 The reason that is good practice to use buffers is that interacting with the raw stream
might have high latency i.e. considerable time is taken to fetch data from it and also to
write to it.
 In the built-in open() function, there is an optional argument, called buffering. This
argument is used to specify the file's desired buffer size i.e.
1: line buffered 0: unbuffered

Page 6 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

27. Differentiate Absolute Path and Relative Path.


 A string like cwd that identifies a file is called a path.
 A relative path starts from the current directory; an absolute path starts from the
topmost directory in the file system.
 The paths we have seen so far are simple filenames, so they are relative to the current
directory. To find the absolute path to a file, you can use os.path.abspath.

28. Write short note on isfile() and isdir() function in python.


isfile() - used to check whether the specified path is an existing regular file or not.
Parameter: path: A path-like object representing a file system path.

isdir() - used to check whether the specified path is an existing directory or not. This method
follows symbolic link, that means if the specified path is a symbolic link pointing to a
directory then the method will return True.

29. Name some of built-in Exception classes in Python.


S.
Exception Cause of Error
No
1 ImportError Raised when the imported module is not found.
2 IndexError Raised when index of a sequence is out of range.
3 KeyError Raised when a key is not found in a dictionary.
4 NameError Raised when a variable is not found in local or global scope.
5 SyntaxError Raised by parser when syntax error is encountered.

30. What is the use of finally block in exception handling?


The try statement in Python can have an optional finally clause. This clause is executed no
matter what, and is generally used to release external resources.
For example:
 we may be connected to a remote data center through the network or working with a file or
working with a Graphical User Interface (GUI).
 In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution.

Page 7 of 8
Saranathan College of Engineering, Tiruchirappalli - 12
GE8151 - Problem Solving and Python Programming - Unit V - 2 Marks Q & A

UNIT V - FILES, MODULES AND PACKAGES


PART- B (16 Marks)
1. Discuss in detail about File Operations in Python. Write a Python program to demonstrate the
file I/O operations.
2. Tabulate different modes of opening a file in python and explain the same.
3. Explain with an example exceptions with arguments in python.
4. Explain the commands used to perform READ and WRITE operations in python with
suitable example.
5. Discuss about the uses of format operators in file processing.
6. Describe how the exceptions are handled in python with necessary example.
7. Write a python program to read a file and display the following:
i. No. of Vowels
ii. No. of Consonants
iii. No. of Digits
iv. No. of Words
8. Explain briefly about Modules and Packages with an example.
9. Write a python program for the following:
i. To display no. of words in the given file.
ii. To copy a file.
10. Discuss in detail about Command-line Arguments in Python. Write a python program to get
command-line arguments and perform arithmetic addition.

Page 8 of 8
Saranathan College of Engineering, Tiruchirappalli - 12

You might also like