0% found this document useful (0 votes)
189 views35 pages

Cat 2 QN Bank

1. The document contains questions and answers related to strings in Python. It discusses string indexing, slicing, immutability, functions, methods and the string module. 2. Strings are immutable in Python, which means a string's value cannot be modified after it is created. String operations include indexing, slicing, concatenation, repetition, and membership testing. 3. Common string methods include capitalize(), lower(), count(), split(), join(), replace(), find(), and lstrip() and rstrip() to remove leading and trailing whitespace. The string module contains useful constants and functions to manipulate strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views35 pages

Cat 2 QN Bank

1. The document contains questions and answers related to strings in Python. It discusses string indexing, slicing, immutability, functions, methods and the string module. 2. Strings are immutable in Python, which means a string's value cannot be modified after it is created. String operations include indexing, slicing, concatenation, repetition, and membership testing. 3. Common string methods include capitalize(), lower(), count(), split(), join(), replace(), find(), and lstrip() and rstrip() to remove leading and trailing whitespace. The string module contains useful constants and functions to manipulate strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

CAT-2 POSSIBLE QNS AND ANSWERS

UNIT-3

PART-A

1. In a string str= ”PYTHON”, when printing str[ 1:19], it returns


a) error (b) PYTHON(c) YTHON (d) YTHONPYTHONPYTHONPY

Ans:c)YTHON

2.  What will be the output of above Python code?

str1="6/4"

print("str1")

A. 1
B. 6/4
C. 1.5
D. str1
Ans : D.str1

3. Which of the following will result in an error?

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”

4. Which of the following is False?

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

6.  What will be the output of below Python code?

str1="Aplication"

str2=str1.replace('a','A')

print(str2)

A. application
B. Application
C. ApplicAtion
D. application
Ans:C

7.  What will be the output of below Python code?

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

9. Strings are immutable in Python, which means a string cannot be modified.

 True
 False

Ans:True

a. 10. Following is an example of ___________________

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

(a)1-b,2-a,3-c,4-d b) 1-b, 2-a, 3- d ,4- c c) 1-b,2-c,3-a,4-d


Ans b) 1-b, 2-a, 3- d ,4- c

PART-B

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

2. Define string immutability.

Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We
can’t
mutate the string but can change what value of the variable to a new string.
Program: Output:
a = “foo” #foofoo
# a now points to #foo
foo b=a It is observed that ‘b’ hasn’t changed
# 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.

s.captilize() – Capitalizes first character of string s.count(sub) – Count number of occurrences of


sub in string
s.lower() – converts a string to lower case s.split() – returns a list of words in string

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

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

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.
7.Identify the use of lstrip() and rstrip() method in strings.
rstrip(): It returns the new string with trailing whitespace removed. It's easier to remember as removing the white
spaces from a “right” side of a string. 
lstrip(): It returns the new string with leading whitespace removed, or removing whitespaces from the “left” side of
the string.

PART-C

1.Explain in detail about the strings and its operations.


Strings:

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

 Python does not supportcharacterdatatype.Astringofsize1canbetreatedas


characters.
1. single quotes (' ')

2. double quotes (" ")


3. triple quotes(“”” “”””)
2. Opera
tions on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership

>>>a=”HELLO” ❖ Positive indexing helps in accessing the


indexing string from the beginning
>>>print(a[0])
>>>H ❖ Negative subscript helps in accessing the
string from the end.
>>>print(a[-1])
>>>O

Print[0:4] –HELL The Slice[start : stop] operator extracts sub string


Slicing: from the strings.
Print[ :3] – HEL
A segment of a string is called a slice.
Print[0: ]-HELLO

a= The + operator joins the text on both sides of


Concatenation “save” the operator.
b=“earth

>>>print(a+b)
saveearth
a= “Easwari ” The * operator repeats the string on the left hand
Repetitions: side times the value on right hand side.
>>>print(3*a)
Easwari Easwari
Easwari
Membership: >>> s="good morning" Using membership operators to check a particular
>>>"m" in character is in string or not. Returns true if
s True present
>>> "a" not in s
True

2.With an example, explain about the string slices.

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

working their way from -1 at the end.


Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.

3. Default value of start is 0,


- Stop is last index of list
- And for step default is 1
4. For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] #
Prints string starting from 3rd character print str * 2 # Prints string two
times
print str + "TEST" # Prints concatenated string
5.
6. Output:
Hello World! H
llo
llo World!
Hello World!Hello World! Hello
World!TEST
7. Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Print[0:4] –HELL The Slice[n : m] operator extracts sub string from
Slicing: the strings.
Print[ :3] – HEL
a=”HELLO” A segment of a string is called a slice.
Print[0: ]-HELLO

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

Operations Example output


element assignment a="PYTHON" TypeError: 'str' object does not
a[0]='x' support element assignment

element deletion a=”PYTHON” TypeError: 'str' object doesn't


del a[0] support element deletion
delete a string a=”PYTHON” NameError: name 'my_string' is
del a not defined
print(a
)

3.Explain in detail about the string built in functions and methods:


A method is a function that “belongs to” an object.

1. Syntax to access the method Stringname.method()


a=”happy birthday”
here, a is the string name.

Syntax example description


1 a.capitalize() >>>a.capitalize() capitalize only the
' Happybirthday‟ first
letter in a string
2 a.upper() >>> a.upper() change string t uppe
'HAPPY BIRTHDAY‟ case o r
3 a.lower() >>> a.lower() change string t lowe
' happy birthday‟ case o r
4 a.title() >>> a.title() change string to title case
' Happy Birthday ' i.e. first characters of all
the words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercas
'HAPPY BIRTHDAY' characters e
uppercas
to and e
viceversa
6 a.split() >>> a.split() returns a list of
['happy', 'birthday'] words
separated by space
7 a.center(width,”fillchar”) >>>a.center(19,”*”) pads the string with the
'***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number
1 of
occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') 'wishyou with new substrings
happy birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>>a="-" with the elements of an
>>>a.join(b iterable.
) 'h-a-p-p-y' (Here “a” is the iterable)

11 a.isupper() >>> a.isupper() checks whether all the case-


False based characters (letters) of
the string are
uppercase.

12 a.islower() >>> a.islower() checks whether all the case-


True based characters (letters) of
the string are
lowercase.

13 a.isalpha() >>> a.isalpha() checks whether the string


False consists of
alphabetic
characters only.
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of
whitespace
only.
17 a.istitle() >>> a.istitle() checks whether string is
False title cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether
True string
starts with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring,
0 if it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>‟ „ character in the string
23 max(a) max(a) Return the maximum
>>>‟y‟ character in the string

8. 4. Explain about the string modules.

9. String modules:

❖ A module is a file containing Python definitions, functions, statements.


❖ Standard library of Python is extended as modules.
❖ To use these modules in a program, programmer needs to import the module.

❖ 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

16. Escape sequences in string

Escape Description example


Sequence
\ new line >>> print("hai \nhello")
n hai
hello

\ prints Backslash (\) >>> print("hai\\hello")


\ hai\hello
\ prints Single quote (') >>> print("'")
' '
\ prints Double quote (") >>>print("\"")
" "
\ prints tab sapace >>>print(“hai\thello”)
t hai hello
\ ASCII Bell (BEL) >>>print(“\a”)
a
5. Generate the code that prompts the user to enter an alphabet. Print all the words in the list that starts
with that alphabet. (5)

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

UNIT IV: LIST, TUPLE AND DICTIONARIES

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)

2. Choose the correct option with respect to Python.

A. Both tuples and lists are immutable.


B. Tuples are immutable while lists are mutable.
C. Both tuples and lists are mutable.
D. Tuples are mutable while lists are immutable.
(Ans B)

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)

5.Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?


a) Error
b) None
c) 25
d) 2
Ans (C)

6. What will be the output of below Python code?


Tup1=(“CSE”,”IT”,”ECE”)
Print(tup1[-3,0])
A. ("CSE")
B. ()
C. (“ECE”)
D. Error as slicing is not possible in tuple.
(Ans B)

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)

8. Which of the following statements create a dictionary?


a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned (Ans D)

9.Identify the output of the code


a=[1,2,3,4,5,6]
Print (a[1:4:2])
a)[2,4]
b)[2,4,6]
c)[5,6]
d)error (Ans a)

10) The method used to compare two dictionaries is


(a) cmp (b)compare (c) comp (d) com (Ans A)
Match the following:
1) %s
2) %g a) Integer formatting
3) %d b) String formatting
c) Float formatting

a) 1-a,2-c, 3-b b) 1-b, 2-a, 3- c c) 1-b, 2-c, 3-a(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)

5.What are the Keywords for the hist() function:


range: lower and upper range of the bins
normed: “= True” means you get a probability distribution instead of just raw number
counts histtype: ʻbarʼ= traditional stype, ʻstepʼ= a line plot.
Weights: this is an array of values that must have the same size as the number of bins label =
“whatever you want to call these data points/lines”.
plt.legend()and python will make your legend
6.Give an example for list comprehension.
The function shown below takes a list of strings, maps the string method capitalize to the elements,
and returns a new list of strings:
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
7.What is aliasing? Give example.
An object with more than one reference has more than one name, so we say that the object is
aliased.
If the aliased object is mutable, changes made with one alias affect the other. Example:
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
Output: True
8.Define Membership operation with example.
The operators in and not in operators are the membership operators in python. The in
operatoris used to test whether a element is present in a list. It returns True if the element is present
in the list otherwise False. The not in operator is used to test if the element is not present in the list.
It returns True if the element is not present in the list, False otherwise
>>> list1=[1,2,3,"hello"]
>>> 1 in list1
True
>>> "Hello" in list1
False
9.Define List comprehension with example.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an
existing list.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

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

Tuple after sequence of Element is reversed:


('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')

Printing elements between Range 4-9:


('S', 'F', 'O', 'R', 'G')
3.Illustrate the concept of Functional Programming to use list comprehension with suitable
examples.Map, Reduce and Filter Methods
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to
write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and
branching.
Essentially, these three functions allow you to apply a function across a number of iterables, in one full
swoop. map and filter come built-in with Python (in the __builtins__ module) and require no importing.
reduce, however, needs to be imported as it resides in the functools module.
Map method
The map () function in python has the following syntax:
map(func, *iterables)
Where func is the function on which each element in iterables (as many as they are) would be applied on.
Notice the asterisk(*) on iterables? It means there can be as many iterables as possible, in so far func has
that exact number as required input arguments.
my_pets = ['alfred', 'tabitha', 'william', 'arla’]
pets = list(map(str.upper, my_pets))
print(pets)
Output:
['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA’]
filter Method
While map() passes each element in the iterable through a function and returns the result of all elements
having passed through the function, filter(), first of all, requires the function to return boolean values (true
or false) and then passes each element in the iterable through the function, "filtering" away those that are
false. It has the following syntax:
filter(func, iterable)
The func argument is required to return a boolean type. If it doesn't, filter simply returns the iterable
passed to it. Also, as only one iterable is required, it's implicit that func must only take one argument.
filter passes each element in the iterable through func and returns only the ones that evaluate to true. I
mean, it's right there in the name -- a "filter".
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]
Example :
defis_A_student(score):
return score > 75
over_75 = list(filter(is_A_student, scores))
print(over_75)
Output:
[90, 76, 88, 81]
Reduce method
reduce applies a function of two arguments cumulatively to the elements of an iterable, optionally starting
with an initial argument. It has the following syntax:
reduce(func, iterable[, initial])

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]

# using del to delete elements from pos. 2 to 5


# deletes 3,5,4
del lis[2 : 5]

# displaying list after deleting


print ("List elements after deleting are : ",end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")

# using pop() to delete element at pos 2


# deletes 3
lis.pop(2)

# displaying list after popping


print ("List elements after popping are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
Output:

List elements after deleting are : 2 1 3 8


List elements after popping are : 2 1 8
3. insert(a, x) :- This function inserts an element at the position mentioned in its arguments. It takes 2
arguments, position and element to be added at respective position.

4. remove() :- This function is used to delete the first occurrence of number mentioned in its arguments.

filter_none
edit
play_arrow
brightness_4

print(lis[i], end=" ")


Output:
List elements after inserting 4 are : 2 1 3 4 5 3 8
List elements after removing are : 2 1 4 5 3 8
5. sort() :- This function sorts the list in increasing order.

6. reverse() :- This function reverses the elements of list.

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]

# using sort() to sort the list


lis.sort()

# displaying list after sorting


print ("List elements after sorting are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")
# using clear() to delete all lis1 contents
lis1.clear()

# displaying list after clearing


print ("List elements after clearing are : ", end="")
for i in range(0, len(lis1)):
print(lis1[i], end=" ")
Output:

List elements after extending are : 2 1 3 5 6 4 3


List elements after clearing are :

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

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),
Output:
Sorted array:
2 3 7 14 19....

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

a)1-a,2-c, 3-b,4-d b)1-d, 2-a, 3- b,4-c c) 1-b, 2-d, 3-a,4-a(Ans:b)


13.Match the following:

1) write a) To read a file


2) read a) To write a file
3) append b) To add data to the existing file

(a)1-a,2-c, 3-b b) 1-b, 2-a, 3- c c) 1-b, 2-c, 3-a(Ans:b)

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

4. Compare Sequential and Random access files


1.Sequential Access: In this way of accessing the files, the contents of the file are accessed
in a sequential order. For example in a text file the lines are read one after another.
2.Direct/Random Access: Random access mechanism reads the contents of the file from
any point of the file. It is also called direct access because the desired contents are accessed
directly by specifying the address.
5. What is the need for opening a file in append() mode
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
6. How a button widget is created in tkinter
button = g.bu(text='Press me.')
7. Mention how seek() method is used to random access a file
seek(): The method changes the current file position.
Syntax: fileobject.seek(offset[,from])
The offset argument indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved. If from is set to 0, it
means use the beginning of the file as the reference position and 1 means use the current
position as the reference position and if it is set to 2 then the end of the file would be taken
as the reference position. If the second argument is omitted, it also means use the beginning
of the file as the reference position.
8. How tell pointer is used in random access a file?
tell(): The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file. Syntax:
fileobject.tell()
9. Give examples of format sequences
%c,%s,%i,%d
10. How to delete a file ?
import os
os.remove("demofile.txt")
11.How to read and write files in Python?
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file.
If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.
3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-
written. The handle is positioned at the beginning of the file. Creates the file if the file does not
exists
For eg
f= open("guru99.txt","w")
12. Illustrate try-except-else.

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

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.

● The try block lets you test a block of code for errors.


● The except block lets you handle the error.
● The else block lets you execute code when there is no error.
● The finally block lets you execute code, regardless of the result of the try- and
except blocks.
Example:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

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

3.Write a python program to split words in a file


with open("employee_data.txt",'r') as data_file:
for line in data_file:
data = line.split()
print(data)

4. Write a python program to copy content of one file to another


with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
5. Create a Python Program to Read a String from the User and Append it into a File
fname = input("Enter file name: ")
file3=open(fname,"a")
c=input("Enter string to append: \n");
file3.write("\n")
file3.write(c)
file3.close()
print("Contents of appended file:");
file4=open(fname,'r')
line1=file4.readline()
while(line1!=""):
print(line1)
line1=file4.readline()
file4.close()

6. Explain how an exception can be raised manually in python with example


An exception can be raised forcefully by using the raise clause in Python. It is useful in that
scenario where we need to raise an exception to stop the execution of the program.
The syntax to use the raise statement is given below.
raise Exception_class,<value>    
1. To raise an exception, the raise statement is used. The exception class name follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores
the value of the exception.
4. We can pass the value to an exception to specify the exception type.

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

7.Illustrate a simple program with tkinter


from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()

8.Explain how to handle multiple exceptions in python with an example code


It is possible to have multiple except blocks for one try block. When the interpreter encounters an
exception, it checks the except blocks associated with that try block.

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.

from tkinter import *


master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Create a file named as xyz.txt that contains a string ’This /n is easier /r and more useful’. Read the string
using Python code by avoiding the whitespace characters and also write any string with 17 characters.
In Python, isspace() is a built-in method used for string handling. The isspace() methods returns “True” if
all characters in the string are whitespace characters, Otherwise, It returns “False”.
This function is used to check if the argument contains all whitespace characters such as :

‘ ‘ – 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.

# Python implementation to count whitespace characters in a string


# Given string
# Initialising the counter to 0
string = 'My name is Ayush'
count=0
# Iterating the string and checking for whitespace characters
# Incrementing the counter if a whitespace character is found
# Finally printing the count
for a in string:
if (a.isspace()) == True:
count+=1
print(count)

string = 'My name is \n\n\n\n\nAyush'


count = 0
for a in string:
if (a.isspace()) == True:
count+=1
print(count)
Output:
3
8

You might also like