Cat 2 QN Bank
Cat 2 QN Bank
UNIT-3
PART-A
Ans:c)YTHON
str1="6/4"
print("str1")
A. 1
B. 6/4
C. 1.5
D. str1
Ans : D.str1
str1="python"
A. print(str1[2])
B. str1[1]="x"
C. print(str1[0:9])
D. Both (b) and (c)
Ans:b.str1[1]=”x”
A. String is immutable.
B. capitalize() function in string is used to return a string by converting the whole given string
into uppercase.
C. lower() function in string is used to return a string by converting the whole given string
into lowercase.
D. None of these.
Ans: b.
5. What will be the output of below Python code?
str1="Information"
print(str1[2:8])
A. format
B. formatio
C. orma
D. ormat
Ans:A
str1="Aplication"
str2=str1.replace('a','A')
print(str2)
A. application
B. Application
C. ApplicAtion
D. application
Ans:C
str1="poWer"
str1.upper()
print(str1)
A. POWER
B. Power
C. power
D. power
Ans:D
8. What will following Python code return?
str1="Stack of books"
print(len(str1))
A. 13
B. 14
C. 15
D. 16
Ans: B
True
False
Ans:True
sv = “csiplearninghub.com”
a. List
b. String
c. Dictionary
d. None of the above
Ans. b. String
11.In split(), if no delimiter is specified, then by default it splits the string on which characters
(a) whitespace(b) comma (c) newline (d) colon
Ans. a.whitespace
12.Which data structure does not allow duplicate values
(a) List (b) Tuple (c) Dictionary (d) Set
Ans.(d) Set
13. print((0,10,20)<(0,30,40)) will print
(a) True (b) False (c) Equal (d) Error
Ans.a. True
14.Match the following:
1) Tuple a) [1]
2) List b) 1,
3) Dictionary c) ‘1’
4) String d) {‘one’:1}
(a)1-a,2-c, 3-d, 4-b (b) 1-d, 2-c, 3- b, 4- a (c) 1-b, 2-a, 3-d, 4 -c
Ans. (c) 1-b, 2-a, 3-d, 4 -c
15. Match the following:
1) slicing a) Dictionary
2) Key Error b) List
3) Syntax c) No proper problem
4) Semantic d) No proper programming language
clarity
PART-B
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We
can’t
mutate the string but can change what value of the variable to a new string.
Program: Output:
a = “foo” #foofoo
# a now points to #foo
foo b=a It is observed that ‘b’ hasn’t changed
# b now points to the same foo that a even though ‘a’ has changed.
points to a=a+a
# a points to the new string “foofoo”, but b
points to the same old “foo”
print a
print
b
3.Mention a few string functions.
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
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:
Program: Output:
import string upper => MONTY PYTHON'S
text = "Monty Python's Flying Circus" print FLYING CIRCUS
"upper", "=>", string.upper(text) print "lower", lower => monty python's flying circus
"=>", string.lower(text) print "split", "=>", split => ['Monty', "Python's", 'Flying', 'Circus']
string.split(text) join => Monty+Python's+Flying+Circus
print "join", "=>", replace => Monty Java's Flying Circus
string.join(string.split(text), find => 6 -1 count => 3
"+")
print "replace", "=>",
string.replace(text, "Python", "Java")
print "find", "=>", string.find(text,
"Python"), string.find(text, "Java")
print "count", "=>", string.count(text, "n")
6.What is the purpose of pass statement?
PART-C
❖ Strings
❖ String slices
❖ Immutability
❖ String functions and methods
❖ String module
Strings:
String is defined as sequence of characters represented in quotation marks (either single quotes
( „ ) or double quotes ( “).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 ton-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Python will get the input at run time by default as a string.
String slices:
A part of a string is called string slices.
The process of extracting a sub string from a string is called slicing.
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: Subsets of strings can
be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the string and
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
For example:
>>> greeting= ‘Eswari college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t change an existing string. The
best we can do is creating a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting 'Jello,
world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator
9. String modules:
❖ Once we import a module, we can reference or use to any of its functions or variables in
our code.
❖ There is large number of standard modules also available in python.
❖ Standard modules can be imported the same way as we import our user-defined
modules.
10. Syntax:
import module_name
This module contains a number of functions to process standard Python strings. In recent versions,
most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes
Syntax: import string
11. Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes to be
used in string module.
12. Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercas
e)
print(string.ascii_uppercas
e)
print(string.digits)
13. Python String Module Classes
Python string module contains two classes – Formatter and Template.
14. Formatter
It behaves exactly same as str.format() function. This class becomes useful if you want to subclass it
and define your own format string syntax.
Syntax: from string import Formatter
15. Template
This class is used to create a string template for simpler string substitutions
Syntax: from string import Template
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789
print(string.digits) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK
print(string.printable) LMNOPQRSTUVWXYZ!"#$%&'()*+,-
print(string.capwords("happy ./:;<=>?@[\]^_`{|}~ Happy
birthday")) print(string.hexdigits) Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
PART A
1. Which of the following creates a tuple?
A. tuple1=("a","b")
B. tuple1[2]=("a","b")
C. tuple1=(5)*2
D. None of the above
(Ans : A)
3. tuple1=(2,4,3)
Tuple2=tuple1*2
print(tuple1),
The Output of the Code is
A. (4,8,6)
B. (2,4,3,2,4,3)
C. (2,2,4,4,3,3)
D. Error
(Ans B)
4. What is the output when we execute list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
(Ans A)
7. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40) (Ans C)
PART B
1.List any three mutable data types. Give example for mutability.
Example for mutable data types are: List, Set and Dictionary
Example 1:>>> numbers = [42,123]
>>> numbers [1] = 5
>>> numbers
Output: [42,5]
2.What is the use of tuple assignment?
It is often useful to swap the values of two variables. With conventional assignments, we have to use a
temporary variable. For example, to swap a and b:
Example:>>> temp = a
>>> a = b
>>> b = temp
3.What is a histogram?
⮚ A histogram is a visual representation of the Distribution of a Quantitative variable.
⮚ Appearance is similar to a vertical bar graph, but used mainly for continuous distribution
⮚ It approximates the distribution of variable being studied.
⮚ It approximates the distribution of variable being studied
4.Analyse the appropriate method in tuple to return more than one value from a function with
example.
When we need to return more than one value from a function, it is preferable to group together
multiple values and return them together.
Example:
defmax_min(vals):
x =max(vals)
y = min(vals)
return (x,y)
vals = (99,98,90,97,89,86,93,82)
max_marks, min_marks) =max_min(vals)
print(“Highest marks =”, max_marks)
print(“Lowest marks =”, min_marks)
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
PART C
1. Define dictionary data type in Python. Discuss about the various operations and methods
performed in a dictionary
Definition:
A Dictionary is a collection of items are separated by commas, enclosed in curly braces {}. A dictionary
contains a collection of indices, which are called keys, and a collection of values. Each key is associated
with a single value. The association of a key and a value is called a key value pair or sometimes an item.
A dictionary represents a mapping from keys to values
DICTIONARY OPERATIONS
Dictionaries are mutable datatypes in python. The following operations are possible on dictionaries:
17. Updating a dictionary
Example:
#Dictionary updation
d={'name':'John','age':27}
print(d)
d['age']=30
print(d)
d['address']='brazil'
print(d)
Output:
{'name': 'John', 'age':27}
{'name': 'John', 'age':30}
{'name': 'John', 'age': 30, 'address': 'brazil'}
Deleting elements from dictionary
The elementscan be removedor deletedfrom a dictionaryby usingpop(),popitem(),clear(),del keyword
pop(): Removes an element from the dictionary for which the key is provided popitem(): Removes or
deletes and returns an arbitary element from the dictionary. clear(): Removes all the elements from the
dictionary at once.
del: Deletes the entire dictionary
Example:
#Dictionary Deletion
cubes={1:1,2:8,3:27,4:64,5:125,6:216}
print(cubes)
print("deletion using pop()",cubes.pop(6))
print("deletion using popitem()",cubes.popitem())
print("deletion using clear()",cubes.clear())
del cubes
print(cubes)
When the value of age is changed, the interpreter searches for key “age” in the dictionary and changes its
value. When d[“address”] is executed, the interpreter does not find the key “address” in the dictionary,
hence a new key:value pair is added The elements of the dictionary are accessed by using keys of the
dictionary. The elements of the dictionary are accessed by association not by index. The elements of the
dictionary can also be accessed using get()
Example using keys:
d1={1:1,2:8,3:27,4:64,5:125}
For example to access the value 64 form the dictionary, d1[4] will get the value 64
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
deletion using pop() 216
deletion using popitem() (5, 125)
deletion using clear()None NameError: name 'cubes' is not defined
Traversal:
Traversal in dictionary is done on the basis of keys. For traversal, for loop is used which iterates over the
keys in the dictionary and prints the corresponding values using keys
#Dictionary traversal
cubes={1:1,2:8,3:27,4:64,5:125} for i in cubes:
print(i,cubes[i])
Output:
11
28
327
464
5125
Membership
Using the membership operators in and not in, whether a key is present in the dictionary or not can be
tested. If the key is present in the dictionary the in operator returns True Other False. The not operator
returns True if the key is not present in the dictionary, False otherwise
Example:
#Dictionary membership cubes={1:1,2:8,3:27,4:64,5:125} print(1 in cubes)
print(27 in cubes)
print(27 not in cubes)
Output:
True
False
True
2.Write code snippets in Python to perform the following
a. Accessing elements of a tuple
b. Slicing elements of a tuple
c. Deleting elements of a tuple
Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed
via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their
elements are usually homogeneous and are accessed by iterating over the list.
Accessing Tuple
Tuple1 = tuple("Geeks")
print("\nFirst element of Tuple: ")
print(Tuple1[0])
# Tuple unpacking
Tuple1 = ("Geeks", "For", "Geeks")
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
Output:
First element of Tuple:
G
Values after unpacking:
Geeks
For
Geeks
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets deleted by
the use of del() method.
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
1. Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also
be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to
fetch a set of elements.
# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')
# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])
# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])
# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])
Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
Where func is the function on which each element in the iterable gets cumulatively applied to, and initial
is the optional value that gets placed before the elements of the iterable in the calculation, and serves as a
default when the iterable is empty.
Example:
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
defcustom_sum(first, second):
return first + second
result = reduce(custom_sum, numbers)
print(result)
4.Explain tuple assignment with example.
TUPLE ASSIGNMENT:
Tuple assignment allows the assignment of values to a tuple of variables on the left side of the assignment
from the tuple of values on the right side of the assignment. The number ofvariables in the tuple on the left
of the assignment must match the number of elements in thetuple on the right of the assignment. The left
side is a tuple of variables; the right side is a tupleof expressions. Each value is assigned to its respective
variable. All the expressions on the rightof expressions. Each value is assigned to its respective variable.
All the expressions on the right
Example
>>> a=("aaa",101,"cse") #tuplepacking>>> (name,no,dept)=a #tupleunpacking>>> a
('aaa', 101, 'cse')
>>>name 'aaa'
>>>no 101
>>>dept 'cse'
With the help of tuple assignment, the variables name, no, dept are assigned in one-line statement.
Example
Swapping of two values using tuple assignment
#Example for swapping two values using tuple assignment a=10
b=20
print("Before swapping",a,b)
a,b=b,a
print("After swapping",a,b)
Output:
Before swapping 10 20
After swapping 20 10
In the above example, the values of two variables are swapped without using third variable, using tuple
assignment
5.Define list cloning and explain various methods of cloning in detail
List cloning:
Cloning creates a new list with same values under another name. Cloning is the process ofmaking a copy
of the list without modifying the original list. The changes will not affect theoriginal copy but reflected
only in the duplicate copy
Various methods of cloning:
1. Cloning by assignment:
This is done by assigning one list to another list. This creates a new reference to the original list
#Cloning by assignment
a=[1,2,3] b=a print(b)
Output:
[1, 2, 3]
2.Cloning by slicing
A clone of the list is created by slicing using [:]
#Cloning by Slicing
a=[1,2,3] b=a[:]
print(a)
b[0]=10 print(b)
print(a)
Output:
[1, 2, 3]
[10, 2, 3]
[1, 2, 3]
3.Clone bylist()
A clone of the list is created by using the list() constructor.
a=[1,2,3]
b=list(a)
print(a)
print(b)
b[0]=10
print(a)
print(b)
Output:
[1, 2,3]
[1, 2,3]
[10, 2, 3]
6.Explain the following methods in list with example
insert(), pop(), extend(), append(), remove() (5)
# Python code to demonstrate the working of
# del and pop()
# initializing list
lis = [2, 1, 3, 5, 4, 3, 8]
4. remove() :- This function is used to delete the first occurrence of number mentioned in its arguments.
filter_none
edit
play_arrow
brightness_4
filter_none
edit
play_arrow
brightness_4
# Python code to demonstrate the working of
# sort() and reverse()
# initializing list
lis = [2, 1, 3, 5, 3, 8]
The series of numbers are 7,3,43,2,56,41,34,67,14,57,19. The given series should be sorted in the
ascending order by following the method of selection sort. Build the Python code.
The series of numbers are 7,3,43,2,56,41,34,67,14,57,19. The given series should be sorted in the
ascending order by following the method of selection sort. Build the Python code.
# Python program for implementation of Selection
# Sort
import sys
A = [7,3,43,2,56,41,34,67,14,57,19]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
8.Sketch a program that has a dictionary of states and their codes. Add another state in the pre-defined
dictionary, print all the items in the dictionary, and try to print code for a state that does not exist. Set a
default value prior to printing.
>>> city_population = {"New York City":8550405, "Los Angeles":3971883, "Toronto":2731571,
"Chicago":2720546, "Houston":2296224, "Montreal":1704694, "Calgary":1239220, "Vancouver":631486,
"Boston":667137}
If we want to get the population of one of those cities, all we have to do is to use the name of the city as an
index:
>>> city_population["New York City"]
8550405
>>> city_population["Toronto"]
2731571
>>> city_population["Boston"]
667137
What happens, if we try to access a key, i.e. a city, which is not contained in the dictionary? We raise a
KeyError:
>>> city_population["Detroit"]
Traceback (most recent call last):
File "<stdin>", line 1, in
KeyError: 'Detroit'
>>>
If you look at the way, we have defined our dictionary, you might get the impression that we have an
ordering in our dictionary, i.e. the first one "New York City", the second one "Los Angeles" and so on.
But be aware of the fact that there is no ordering in dictionaries. That's the reason, why the output of the
city dictionary, doesn't reflect the "original ordering":
>>> city_population
{'Toronto': 2615060, 'Ottawa': 883391, 'Los Angeles': 3792621, 'Chicago': 2695598, 'New York City':
8175133, 'Boston': 62600, 'Washington': 632323, 'Montreal': 11854442}
Therefore it is neither possible to access an element of the dictionary by a number, like we did with lists:
>>> city_population[0]
Traceback (most recent call last):
File "<stdin>", line 1, in
KeyError: 0
UNIT 5
PART A
1. The Mode used to read contents from the file is
(a) w (b) c (c) read (d) reading (Ans : b)
2. If a file contains an image which mode is used to read the content
(a) b (b) r (c)x (d) i (Ans : a)
3. read() method returns the whole text in a file (True /False) (Ans : True)
4. Which mode opens a file for both appending and reading in binary format
(a) b (b) a (c) ab (d) ab+ (Ans : d)
5. The method that returns the current position within the file is
(a) seek() (b) tell (c) curr() (d)cur_pos()(Ans : b)
6. The method used to clear the buffer is
(a) flush (b) atty() (c) close() (d) seek()(Ans : a)
7.The GUI tool in python is
(a)tkinter (b) anaconda (c) spider (e) Gnome (Ans : a)
8.Which region of tkinter is used to draw images
(a) Layout (b) Frames (c) Sheet (d) Canvas (Ans : d)
9.Which of the following statement is not associated with exception handling in python
(a) try (b) except (c) finally (d)catch (Ans : d)
10. 200/0 this statement leads to
(a) none (b)syntax error (c) ZeroDivisionError (d) ZeroDivisionException (Ans : c)
11.Which keyword is used to generate an exception?
(a) throw (b) raise (c) generate (d)try(Ans : b)
12.Match the following:
1) Comprehension a) Dictionary
2) Key-value pair b) Exception Handling
3) Try except block c) Tkinter
4) Python GUI d) List
PART B
1. Identify the need for finally statement in exception handling
The finally block is a place to put any code that must execute, whether the try-block raised
an exception or not.
2. Differentiate syntax errors from exceptions
Syntax error occurs when there is mistake in the syntax of code like missing :,misspelled
keywords etc.,
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
3. Create a program to write the content “Joy of Learning Python “ to file named
“file1”
fp=open("samp1.txt","w")
fp.write("Joy of Learning Python ")
fp.close()
PART C
1. Create a python program to random access a file using tell() and seek() functions.
fp=open("example.txt","w")
fp.write("This file is an example for random file access")
print("The current file position is",fp.tell())
print("Change the file position to beginning offile",fp.seek(0))
print("The current file position is",fp.tell())
print("Change the file position to end of file",fp.seek(0,2))
print("The current file position is",fp.tell())
fp=open("example.txt","r")
print(fp.read(23))
print("The current file position is",fp.tell())
print("Change the file position to beginning offile",fp.seek(0))
print("The current file position is",fp.tell())
print("The file position is moved 6 bytes from beginning",fp.seek(6,0))
print("to read 5 bytes from current position",fp.read(5))
print("The current file position is",fp.tell())
print("The file position is moved",fp.seek(6))
print(fp.read())
print("The current file position is",fp.tell())
fp.close()
2. Explain how Exception Handling is done in python.
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try statement
(second print statement in our case). The second print statement tries to access the fourth element
of the list which is not there and this throws an exception. This exception is then caught by the
except statement.
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block
of code for a special kind of error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
2. Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
3. Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished
Example
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
These except blocks may declare what kind of exceptions they handle. When the interpreter finds
a matching exception, it executes that except block.
>>> a,b=1,0
>>> try:
print(a/b)
print("This won't be printed")
print('10'+10)
except TypeError:
print("You added values of incompatible types")
except ZeroDivisionError:
print("You divided by 0")
9. How GUI package is imported in Python? Explain the button, packing widgets
and canvas widgets in GUI.
Python offers multiple options for developing GUI (Graphical User Interface). Out of
all the GUI methods, tkinter is most commonly used method. It is a standard
Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter
outputs the fastest and easiest way to create the GUI applications. Creating a GUI
using tkinter is an easy task.
‘ ‘ – Space
‘\t’ – Horizontal tab
‘\n’ – Newline
‘\v’ – Vertical tab
‘\f’ – Feed
‘\r’ – Carriage return
Syntax :
string.isspace()
Parameters:
isspace() does not take any parameters
Returns :
1.True- If all characters in the string are whitespace characters.
2.False- If the string contains 1 or more non-whitespace characters.