Problem Solving and Python Programming - GE3151 - Important Questions With 2 Marks Answer - Unit 2 - Data Types Expressions Statements
Problem Solving and Python Programming - GE3151 - Important Questions With 2 Marks Answer - Unit 2 - Data Types Expressions Statements
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.
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
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 1 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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.
9. 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.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 2 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 3 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 4 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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.
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
29. Give the python code to find the minimum among the list of 10 numbers. (May 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:
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 5 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
if i > maxNum:
maxNum = i
print('Maximum Element of the Given List is %d' %(int(maxNum)))
30. How will you analysis the efficiency of an algorithm? (Nov / Dec 2019)
Time efficiency, indicating how fast the algorithm runs.
Space efficiency, indicating how much extra memory it uses
31. How do algorithm, flowchart and pseudo code use for problem solving? (Nov / Dec 2019)
Algorithm: A process or set of rules to be followed in calculations or other problem – solving operations,
especially by a computer
Flowchart: Flowchart is diagrammatic representation of the algorithm.
Pseudo code: In Pseudo code normal English language is translated into the programming languages to be
worked on.
All are tools for problem solving independent of programming language. Difference is only in the way of
representing the solution.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 6 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
Greek mathematician Eratosthenes. The algorithm to find all the prime numbers less than or equal to a
given integer n: (10) (Nov / Dec 2019)
1) Create a list of integers from two to n: 2,3,4,…, n
2) Start with a counter i set to 2, i.e. the first prime number
3) Starting from i+1, count up by I and remove those numbers from the list, i.e. 2*i,3*i, 4*i,..
4) Find the first number of the list following i. This is the next prime number.
5) Set i to the number found in the previous step.
6) Repeat steps 3 and 4 until i is greater than n. (As an improvement: It’s enough to go to the square root
of n)
7) All the numbers, which are still in the list, are prime numbers.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 7 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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()
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?
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 8 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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()
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 9 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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 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
30. Compare Interpreter and Compiler (Nov / Dec 2019)
Compiler: A Compiler is a program which translates the source code written in a high level language in
to object code which is in machine language program. Compiler reads the whole program written in high
level language and translates it to machine language. If any error is found, it display error message on the
screen.
Interpreter: Interpreter translates the high level language program in line by line manner. The interpreter
translates a high level language statement in a source program to a machine code and executes it
immediately before translating the next statement. When an error is found the execution of the program is
halted and error message is displayed on the screen
31. Write a python program to circulate the values of n variables (Nov / Dec 2019)
no_of_terms = int(input("Enter number of values : "))
list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 10 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
print(list1)
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)
2. Illustrate values and different standard data types with relevant examples.
3. Define variables. List down the rules for naming the variable with example.
4. List down the different types of operators and their function with suitable example.
5. What are the two modes of operation in python? Analyze the differences between them.
6. What do you mean by rule of precedence? List out the order of precedence and demonstrate in detail with
example.
7. Elaborate on tuple assignment.
8. What is the use of function? Explain the role of function call and function definition with example. (or)
Outline about function definition and call with example. Why are function needed? (May 2019)
9. Describe flow of execution of function with an example.
10. Write a Python program to circulate the values of n variables.
11. Write a python program to swap two variables.
12. Write a python program to check whether a given year is a leap year or not.
13. Write a python program to convert celsius to fahrenheit .
(Formula: celsius * 1.8 = fahrenheit –32).
14. a) What is a numeric literal? Give examples. (4) (Jan-2018)
b) Appraise the arithmetic operators in Python with an example. (12) (Jan-2018)
15. a) Outline the operator precedence of arithmetic operators in Python. (6) (Jan-2018)
b) Write a Python program to exchange the value of two variables. (4) (Jan-2018)
c) Write a Python program using function to find a sum of first ‘N’even numbers and print the
result.(6)(Jan 2018)
16. a) Mention the list of keywords available in Python. Compare it with variable name. (8)(May 2019)
b) What are Statement? How are they constructed from variable and expression in Python. (8) (May 2019)
17. (a) Write a python program to rotate a list by right n times with and without slicing technique (4 + 4)
(Nov / Dec 2019)
(b) Discuss about keyword arguments and default arguments in python with example. (4 + 4) (Nov / Dec
2019)
18. (a) Write a python program to print the maximum among ‘n’ randomly generate ‘d’ numbers by storing
them in a list (10) (Nov / Dec 2019)
19. (b) Evaluate the following expressions in python (6) (Nov / Dec 2019)
i) 24 // 6 % 3
ii) float(4 + int(2.39) % 2)
iii) 2 ** 2 ** 3
UNIT III - CONTROL FLOW, FUNCTIONS, STRINGS
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. The following examples use the operator “==” which compares two operands and produces True if
they are equal and False otherwise:
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?
Arithmetic Operator (+, -, *, /, %, **, // )
Relational operator ( == , !=, <>, < , > , <=, >=)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 11 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 12 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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:
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.
8. 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:
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.
9. 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.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 13 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 14 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
Program: Output:
import string upper => MONTY PYTHON'S
text = "Monty Python's Flying Circus" FLYING CIRCUS
print "upper", "=>", string.upper(text) lower => monty python's flying
print "lower", "=>", string.lower(text) circus
print "split", "=>", string.split(text) split => ['Monty', "Python's",
print "join", "=>", string.join(string.split(text), "+") 'Flying', 'Circus']
print "replace", "=>", string.replace(text, "Python", "Java") join =>
print "find", "=>", string.find(text, "Python"), string.find(text, Monty+Python's+Flying+Circus
"Java") replace => Monty Java's Flying
print "count", "=>", string.count(text, "n") Circus
find => 6 -1
count => 3
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”)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 15 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
BANANA
19. Write a Python program to accept two numbers, multiply them and print the result. (Jan-2018)
print(“Enter two numbers”)
val1=int(input())
val2=int(input())
prod=val1*val2
print(“The product of the two numbers is:”,prod)
20. Write a Python program to accept two numbers, find the greatest and print the result. (Jan-2018)
print(“Enter two numbers”)
val1=int(input())
val2=int(input())
if (val1>val2):
largest=val1
else:
largest=val2
print(“Largest of two numbers is:”,largest)
21. 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.
22. What is range() function?
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions:
Example:
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
This function does not store all the values in memory, it would be inefficient. So it remembers the start,
stop, step size and generates the next number on the go.
23. Define Fruitful Function.
The functions that return values, is called fruitful functions. The first example is area, which returns the area
of a circle with the given radius:
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 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.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 16 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
26. Do loop statements have else clauses? When will it be executed? (Nov / Dec 2019)
Loop statements may have an else clause, it is executed when the loop terminates through exhaustion of the
list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a
break statement.
27. Write a program to display a set of strings using range( ) function (Nov / Dec 2019)
for i in range(len(a)):
print(i,a[i])
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 17 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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:] .
>>> 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 Dictionary is immutable and is a key
can be modified. value store.
List can store a sequence of objects in a Dictionary is not ordered and it requires
certain order. that the keys are hashable.
Example: list1=[1,’a’,’apple’] Example: dict1={‘a’:1, ‘b’:2}
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 18 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 19 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
>>> deleteHead(numbers)
>>> print numbers [2, 3]
13. 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
14. 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.
15. 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’
16. 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 you 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)
17. List two dictionary operations.
Del -removes key-value pairs from a dictionary
Len - returns the number of key-value pairs
18. 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. For
example, the keys method takes a dictionary and returns a list of the keys that appear, but instead of the
function syntax keys(dictionary_name), method syntax dictionary_name.keys() is used.
Example:>>> eng2sp.keys() [’one’, ’three’, ’two’]
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.
20. 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: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
21. Write the syntax for list comprehension.
The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a list.
The basic syntax is[ expression for item in list if conditional ].
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 20 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
Example:
new_list = []
for i in old_list:
if filter(i):
new_list.append(expressions(i))
22. How list differs from tuple. (Jan-2018)
List Tuple
List is a mutable type meaning that it can be Tuple is an immutable type
modified. meaning that it cannot be modified.
Syntax: list=[] Syntax: tuple=()
Example: list1=[1,’a’] Example: tuple1=(1,’a’)
23. How to slice a list in Python. (Jan-2018)
The values stored in a list can be accessed using slicing operator, the colon (:) with indexes starting at 0 in
the beginning of the list and end with -1.
Example:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
24. Write python program for swapping two numbers using tuple assignment?
a=10
b=20
a,b=b,a
print(“After swapping a=%d,b=%d”%(a,b))
25. What is list loop?
In Python lists are considered a type of iterable . An iterable is a data type that can return its elements
separately, i.e., one at a time.
Syntax: for <item> in <iterable>:
<body>
Example:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
print("Hi "+ name +"!")
26. What is mapping?
A list as a relationship between indices and elements. This relationship is called a mapping; each index
“maps to” one of the elements.The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
27. 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])
28. How to create a list in python? Illustrate the use of negative indexing of list with example.
(May 2019)
List Creation:
days = ['mon', 2]
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 21 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
days=[]
days[0]=’mon’
days[1]=2
Negative Indexing:
Example:
>>> print(days[-1])
Output: 2
29. Demonstrate with simple code to draw the histogram in python. (May 2019)
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Output:
**
***
******
*****
30. How will you update list items? Give one example. (Nov / Dec 2019)
Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the
list items
fruit = ["banana","apple","cherry"]
print(fruit)
['banana', 'apple', 'cherry']
fruit[0] = "pear"
fruit[-1] = "orange"
print(fruit)
['pear', 'apple', 'orange']
31. Can function return tuples? If yes Give examples. (Nov / Dec 2019)
Function can return tuples as return values.
def circle_Info(r):
#Return circumference and area and tuple
c = 2 * 3.14 * r
a = 3.14 * r * r
return(c,a)
print(circle_Info(10))
Output
(62.800000000000004, 314.0)
PART B (16 MARKS)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 22 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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
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.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 23 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
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.
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
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'
10. 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
11. 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.
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 24 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
try:
// try block code
except:
// except blcok code
Example:
try:
print "Hello World"
except:
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.'
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 25 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 26 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
'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)
24. 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 ']
Here in the above given program, Syntax error occurs in the third line (print cwd)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 27 of 28
www.BrainKart.com
4931_Grace College of Engineering, Thoothukudi
28. How to use command line arguments in python? (Nov / Dec 2019)
Access to the command line parameters using the sys module. len(sys, argv) contains the number of
arguments. To print all of the arguments str(sys,argv)
29. Write method to rename and delete files ( Nov / Dec 2019)
os.rename(current_file_name, new_file_name)
os.remove(file_name)
GE3151-PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes Page 28 of 28
All 1st semester Subjects
Professional English - I - HS3152 – Click Here
Matrices and Calculus - MA3151 – Click Here
Engineering Physics - PH3151 – Click Here
Engineering Chemistry - CY3151 – Click Here
Problem Solving and Python Programming - GE3151 – Click Here
Problem Solving and Python Programming Laboratory - GE3171 – Click Here
Physics and Chemistry Laboratory - BS3171 – Click Here