GE3151 Problem Solving and Python Programming Two Mark Questions 1
GE3151 Problem Solving and Python Programming Two Mark Questions 1
com
UNIT I - COMPUTATIONAL THINKING AND 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. There are 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.
www.EnggTree.com
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. Write the algorithm to calculate the average of three numbers and display it.
Step 1: Start
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
8. 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.
The language of 0s and 1s is It is low level programming High level languages are English
called as machine language. language in which like statements and programs.
the sequence of 0s and 1s
The machine language is are replaced by Written in these languages are
system independent because mnemonic (ni-monic) needed to be translated into
there are different set of binary codes. machine language before to their
instruction for different types Typical instruction for execution using a system software
of computer systems addition and subtraction compiler.
18. 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.
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 condition) Iterative approach involves four steps:
and recursive case are specified. initialization, condition, execution and updation.
Recursion is slower than iteration due to overhead of Iteration is faster.
maintaining stack.
Recursion takes more memory than iteration due to Iteration takes less memory.
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.
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
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
Algorithm is the approach / idea to solve some problem. A program is a set of instructions for the computer to
follow.
It does not have a specific syntax like any of the It is exact code written for problem following all the
programming languages rules (syntax) of the programming language.
28. List the Symbols used in drawing the flowcart. (May 2019)
Flowcharts are usually drawn using some standard symbols
Terminator
Process
Decision
Connector
Data
Delay
Arrow
www.EnggTree.com
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.
www.EnggTree.com
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. (May 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. (May 2019)
Logical operators are and, or, not operators.
6. Explain while loop with example.(or)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:
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-else:
www.EnggTree.com
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:
Example:
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 condition must be true or
false, exactly one of the alternatives will be executed.
Return gives back or replies to the caller of the Calling one function from another is called
function. The return statement causes your function to composition.
exit and handback a value to its caller. Example:
Example: def circle_area(xc, yc, xp, yp):
def area(radius): radius = distance(xc, yc, xp, yp)
temp = math.pi * radius**2 result = area(radius)
return temp return result
www.EnggTree.com
15. Explain global and local scope. (or) Comment with an example on the use of local and global variable with
the same identifier name. (May 2019)
The scope of a variable refers to the places that you 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”)
16. 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
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
def area(radius):
temp = 3.14159 * radius**2
return temp
In a fruitful function the return statement includes a return value. This statement means: Return immediately from
this function and use the following expression as a return value.
24. What is dead code?
Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead
code.
25. 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
www.EnggTree.com
UNIT IV
LISTS, TUPLES, DICTIONARIES
PART- A (2 Marks)
1. What is a list?(Jan-2018)
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.
2. Relate String and List? (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]
3. 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]
4. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
www.EnggTree.com
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
>>> list[:4]
[’a’, ’b’, ’c’, ’d’]
>>> list[3:]
[’d’, ’e’, ’f’]
5. Mention any 5 list methods.
append()
extend ()
sort()
pop()
index()
insert
remove()
6. State the difference between lists and dictionary.
Lists Dictionary
List is a mutable type meaning that it can Dictionary is immutable and is a key value
be modified. store.
List can store a sequence of objects in a Dictionary is not ordered and it requires
certain order. that the keys are hashtable.
Example: list1=[1,’a’,’apple’] Example: dict1={‘a’:1, ‘b’:2}
7. What is List mutability in Python? Give an example.
1. Explain in detail about lists, list operations and list slices. (Jan-2019)
2. Discuss 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 and its operations.(or)What is a dictionary in Python?Give example.(4)
(Jan-2018)
7. Describe in detail about dictionary methods.(or) What is Dictionary? Give an example. (4) (May 2019)
8. Explain in detail about list comprehension .Give an example.
9. Write a Python program for www.EnggTree.com
a) selection sort (8) (Jan-2018)
b) Insertion sort.
UNIT V
FILES, MODULES, 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.
2. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
f.write("hello world")
f.close()
3. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
4. What are the two arguments taken by the open() function?
The open function takes two arguments : name of the file and the mode of operation.
Example: f = open("test.dat","w")
5. 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.
www.EnggTree.com
6. What information is displayed if we print a file object in the given program?
f= open("test.txt","w")
print f
The name of the file, mode and the location of the object will be displayed.
7. 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
8. 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
9. 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
Syntax:
try:
// try block code
except:
// except blcok code
Example:
try:
print "Hello World"
except:
www.EnggTree.com
print "This is an error message!"
12. 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.
13. What is a pickle?
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.
14. 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.'
Here in the above given program, Syntax error occurs in the third line (print cwd)
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. (Jan 2019)
2. (a). Write a program to perform exception handling.
(b). Write a Python program to handle multiple exceptions.
www.EnggTree.com
3. Write a python program to count number of lines, words and characters in a text file. (May 2019)
4. Write a Python program to illustrate the use of command-line arguments.
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.
6. Write a Python program to implement stack operations using modules.
7. Write a program to illustrate multiple modules.
8. Write a Python program to dump objects to a file using pickle.
9. Tabulate the different modes for opening a file and briefly explain the same. (Jan-2018) (Jan 2019)
10. (a). Appraise the use of try block and except block in Python with example. (6) (Jan-2018)
(b). Explain with example exceptions with argument in Python. (10) (Jan-2018)
11. a) Describe how exceptions are handled in python with necessary examples.(8) (Jan 2019, May 2019)
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) (Jan 2019, May 2019)