Python QB Solution
Python QB Solution
Python QB Solution
MCQ
a) Lists
b) Dictionary
c) Tuples
d) Class
Answer: d
2. What will be the output of the following Python code? 1. >>>str="hello" 2. >>>str[:2] 3. >>>
a) he
b) lo
c) olleh
d) hello
Answer: a Explanation: We are printing only the 1st two bytes of string and hence the answer is
“he”
a) list
b) dictionary
c) array
d) tuple
Answer: a Explanation: List data type can store any values within it
c) ‘3\’
d) ”’That’s okay”’
a) 85.0
b) 85.1
c) 95.0
d) 95.1
a)Boolean
b) Integer
c) Float
d) Complex
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by float(‘inf’)
a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
Answer: d
a) 81
b) 12
c) 0.75
d) 7
Answer: d
a) 4
b) 7
c) 2
d) 0
Answer: b
Explanation: The order of precedence is: %, +. Hence the expression above, on simplification results
in 4 + 3 = 7. Hence the result is 7.
a) (1.0, 4.0)
b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)
Answer: a
Explanation: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
a) 8
b) 8.0
c) 8.3
d) 8.33
Answer: b
Explanation: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence the
result of this expression is 8.0.
a) yes
b) no
c) machine dependent
Answer: a yes
a) 31 characters
b) 63 characters
c) 79 characters
b) 1st_string
c) foo
d) _
Answer: b
15. Which of the following is not a keyword?
a) eval
b) assert
c) nonlocal
d) pass
Answer: a
Explanation: eval can be used as a variable.
16. Which of the following is an invalid statement?
a) abc = 1,000,000
d) a_b_c = 1,000,000
Answer: b
Explanation: Spaces are not allowed in variable names.
17. What will be the output of the following Python expression if x=15 and y=12? x & y
a) b1101
b) 0b1101
c) 12
d) 1101
Answer: c)
Explanation: The symbol ‘&’ represents bitwise AND. This gives 1 if both the bits are equal to 1, else
it gives 0. The binary form of 15 is 1111 and that of 12 is 1100. Hence on performing the bitwise AND
operation, we get 1100, which is equal to 12
18. What will be the output of the following Python expression? 0x35 | 0x75
a) 115
b) 116
c) 117
d) 118
Answer: c
Explanation: The binary value of 0x35 is 110101 and that of 0x75 is 1110101. On OR-ing these two
values we get the output as: 1110101, which is equal to 117. Hence the result of the above
expression is 117.
19. What will be the value of the following Python expression? bin(10-2)+bin(12^4)
a) 0b10000
b) 0b10001000
c) 0b1000b1000
d) 0b10000b1000
Answer: d
Explanation: The output of bin(10-2) = 0b1000 and that of bin(12^4) is ob1000. Hence the output of
the above expression is: 0b10000b1000.
a)101
b)-101
c)100
d)-100
View Answer
Answer: b
Explanation: Suppose we have an expression ~A. This is evaluated as: -A – 1. Therefore,
the expression ~100 is evaluated as -100 – 1, which is equal to -101.
Chapter 1 short
Appropriate List is useful for insertion and Tuple is useful for readonly operations
3
for deletion operations. like accessing elements.
Methods List provides many in-built Tuples have less in-built methods.
5
methods.
Error prone List operations are more error Tuples operations are safe.
6
prone.
5.What is pep 8?
The Python memory manager manages chunks of memory called “Blocks”. A collection of
blocks of the same size makes up the “Pool”. Pools are created on Arenas, chunks of
256kB memory allocated on heap=64 pools. If the objects get destroyed,
the memory manager fills this space with a new object of the same size
7. What are python modules? Name some commonly used built-in modules in Python?
A module allows you to logically organize your 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 you can bind and reference. Complex() math()
8. What are local variables and global variables in Python?
One of the most distinctive features of Python is its use of indentation to mark blocks of
code. ... In most other programming languages, indentation is used only to help make the
code look pretty. But in Python, it is required for indicating what block of code a statement
belongs to
Lists
• Python lists are very flexible and can hold arbitrary data.
Arrays
• Python arrays are just a thin wrapper on C arrays.
The principal built-in types are numerics, sequences, mappings, classes, instances
and exceptions.
Some collection classes are mutable. The methods that add, subtract, or rearrange
their members in place, and don’t return a specific item, never return the collection
instance itself but None
LONG ANSWER
1.Explain the different string formats available in Python with examples
2. Discuss the int(), float(), str(), chr() and complex() type conversion functions with examples
1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies
the base in which string is if data type is string.
2. float() : This function is used to convert any data type to a floating point
number
3.str() : Used to convert integer into a string.
4.complex(real,imag) : : This function converts real numbers to
complex(real,imag) number.
5.chr(number) : : This function converts number to its corresponding ASCII
character.
# Convert ASCII value to characters
a = chr(76)
b = chr(77)
print(a)
print(b)
Another example
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
3.Discuss the ord(), hex(), oct(), complex() and float() type conversion functions with examples.
4. Describe the is and is not operators and type() function. Also, discuss why Python is called as
dynamic and strongly typed language.
Ans-‘is’ operator – Evaluates to true if the variables on either side of the operator point to
the same object and false otherwise.
if (type(x) is int):
print("true")
else:
print("false")
‘is not’ operator – Evaluates to false if the variables on either side of the operator
point to the same object and true otherwise.
Python is strongly typed as the interpreter keeps track of all variables types. It's also very
dynamic as it rarely uses what it knows to limit variable usage. In Python, it's the
program's responsibility to use built-in functions like isinstance() and issubclass() to test
variable types and correct usage. Python tries to stay out of your way while giving you all
you need to implement strong type checking.
People often use the term strongly-typed language to refer to a language that is both
statically typed (types are associated with a variable declaration -- or, more generally, the
compiler can tell which type a variable refers to, for example through type inference,
without executing the program) and strongly-typed (restrictive about how types can be
intermingled).
Python is a dynamic, high level, free open source and interpreted programming
language. It supports object-oriented programming as well as procedural oriented
programming.
In Python, we don’t need to declare the type of variable because it is a dynamically typed
language.
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in python language and anybody can learn python basics in a few
hours or days. It is also a developer-friendly language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it
from the given download link below click on the Download Python keyword.
Download Python
Since it is open-source, this means that source code is also available to the public.
So you can download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need
to remember the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++
language and also we can compile that code in C/C++ language.
7. Python is Portable language:
Python language is also a portable language. For example, if we have python code
for windows and if we want to run this code on other platforms such as Linux, Unix,
and Mac then we do not need to change it, we can run this code on any platform.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with
other languages like c, c++, etc.
List Tuple
Appropriate List is useful for insertion and Tuple is useful for readonly
3 for deletion operations. operations like accessing
elements.
Methods List provides many in-built Tuples have less in-built methods.
5
methods.
Error prone List operations are more Tuples operations are safe.
6
error prone.
Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming. This article is aimed at
providing the information about certain conversion functions.
1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies
the base in which string is if data type is string.
2. float() : This function is used to convert any data type to a floating point
number
3. ord() : This function is used to convert a character to integer.
▪ Explicit Conversion
▪ Implicit Conversion
In Explicit Type Conversion, users convert the data type of the
item to needed data type. We use the predefined roles such as
int(), float(), str(), etc to execute explicit type conversion.
This procedure does not require any user participation. Let us see
an instance where Python boosts the conversion of a lower data
type (integer) to the greater data type (floats) to prevent data
loss.
8. What are operators in Python? Describe specifically about identity membership operator?
In Python are used to determine whether a value is of a certain class or type. They
are usually used to determine the type of data a certain variable contains.
There are different identity operators such as
1. ‘is’ operator – Evaluates to true if the variables on either side of the operator
point to the same object and false otherwise.
‘is not’ operator – Evaluates to false if the variables on either side of the operator point to
the same object and true otherwise.
CHAPTER – 2
Mcq
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
Answer: d
Explanation: The loop does not terminate as new elements are being added to the list in each
iteration.
5. What will be the output of the following Python code? i = 1 while True: if i%2 == 0: break print(i) i
+= 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Answer: d
Explanation: The loop does not terminate since i is never an even number.
6. What will be the output of the following Python code? True = False while True: print(True) break
a) True
b) False
c) None
Answer: d
7) 4. What will be the output of the following Python code? x = "abcdef" i = "i" while i in x: print(i,
end=" ")
a) no output
b) i i i i i i …
c) a b c d e f
d) abcdef
8) . What will be the output of the following Python code? x = "abcdef" i = "i" while i in x: print(i,
end=" ")
a) no output
b) i i i i i i …
c) a b c d e f
d) abcdef
9)What will be the output of the following Python code? for i in range(int(2.0)): print(i)
a) 0.0 1.0
b) 0 1
c) error
10)What will be the output of the following Python code snippet? for i in [1, 2, 3, 4][::-1]: print (i)
a) 1 2 3 4
b) 4 3 2 1
c) error
11. What will be the output of the following Python code snippet? for i in
''.join(reversed(list('abcd'))): print (i)
a) a b c d
b) d c b a
c) error
12.What will be the output of the following Python code? for i in range(5): if i == 5: break else:
print(i) else: print("Here")
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
c) 0 1 2 3 4
d) 1 2 3 4 5
Answer: a Explanation: The else part is executed if control doesn’t break out of the loop.
13. What will be the output of the following Python code? x = (i for i in range(3)) for i in x: print(i) for
i in x: print(i)
a) 0 1 2
b) error
c) 0 1 2 0 1 2
Answer: a
14. What will be the output of the following Python code snippet? a = [0, 1, 2, 3] for a[-1] in a:
print(a[-1])
a) 0 1 2 3
b) 0 1 2 2
c) 3 3 3 3
d) error V
Answer: b
15. What will be the output of the following Python statement? 1. >>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
Answer: c
a) 0xA0xB0xC
b) Error
c) 0x22
d) 33
Answer: d
a) error
b) u
c) t
d) y
Answer:
a) __345.355
b) ___345.355
c) ____345.355
d) _____345.354
Answer: b
19.What will be the output of the following Python code? print('*', "abcdef".center(7), '*')
a) * abcdef *
b) * abcdef *
c) *abcdef *
d) * abcdef*
Answer: b
20. What will be the output of the following Python code? print("abcdef".center(7, '1'))
a) 1abcdef
b) abcdef1
c) abcdef
d) error
Answer: a
21) What will be the output of the following Python code? advertisement
print("xyyzxyzxzxyy".count('yy', 2))
a) 2
b) 0
c) 1
Answer: c
22) . What will be the output of the following Python code? elements = [0, 1, 2] def incr(x): return
x+1 print(list(map(incr, elements)))
a) [1, 2, 3]
b) [0, 1, 2]
c) error
Answer: a
23.What will be the output of the following Python code? x = ['ab', 'cd'] print(list(map(list, x)))
a) [‘ab’, ‘cd’]
b) [2, 2]
c) [‘2’, ‘2’]
Answer:
24) In _______________ copy, the base address of the objects are copied. In _______________
copy, the base address of the objects are not copied.
a) deep. Shallow
b) memberwise, shallow
c) shallow, deep
d) deep, memberwise
Answer:C
a) 1 2 3 4 5
b) [5,4,3,2,1]
Answer: c
Short answer
1. What are functions in Python?
A lambda function can take any number of arguments, but can only
have one expression.
self represents the instance of the class. By using the “self” keyword we can access
the attributes and methods of the class in python. It binds the attributes with the given
arguments.
5. How does break, continue and pass work?
• Pass. Let's start with something relatively easy (but not straightforward). Nothing
happens when pass is executed. ...
• Break. The break statement allows you to leave a for or while loop prematurely. ...
• Continue. The continue statement ignores the rest of the statements inside a loop,
and continues with the next iteration.
To write a comment in Python, simply put the hash mark # before your
desired comment:
# This is a comment
The dir function returns a list of all the attributes within in an object - these could be
either data values or methods, and the list includes private and magic methods. The help
function works by formatting all of the docstrings from the object with other data into a
hopefully useful help page.
14. . What is a dictionary in Python?
16. What does this mean: *args, **kwargs? And why would we use it?
Kwargs allow you to pass keyword arguments to a function. They are
used when you are not sure of the number of keyword arguments that will be passed in
the function. Kwargs can be used for unpacking dictionary key, value pairs.
This is done using the double asterisk notation ( ** ).
The len() function returns the number of items in an object. When the object is a string,
the len() function returns the number of characters in the string.
18. What are negative indexes and why are they used?
Negative indexes are a way to allow you to index into a list, tuple or other indexable
container relative to the end of the container, rather than the start. They are use d
because they are more efficient and are considered by much more readable.
import module_name
When import is used, it searches for the module initially in the local scope by calling
__import__() function. The value returned by the function are then reflected in the
output of the initial code.
import math
print(math.pi)
Output:
3.141592653589793
A Python library is a reusable chunk of code that you may want to include in your
programs/ projects. Compared to languages like C++ or C, a Python libraries do not pertain
to any specific context in Python. Here, a 'library' loosely describes a collection of core
modules
• Pandas. ...
• Keras. ...
• SciKit-Learn. ...
• PyTorch. ...
• TensorFlow. ..
The best way to share global variables across modules across a single program
is to create a config module. Just import the config module in all modules of your
application; the module then becomes available as a global name
CHAPTER-2 LONG ANSWER
1. Illustrate the different types of control flow statements available in Python with
flowcharts.
1. if-else
2. Nested if-else
3. for
4. while
5. break
6. Continue
if-else
If-else is used for decision making; when code statements satisfy the condition, then
it will return non-zero values as true, or else zero or NONE value as false, by the
Python interpreter.
Syntax
1. if(<condition>):
2. Statement 1
3. ...
4. else:
5. Statement 2
6. ...
Example
Syntax
1. if (<condition 1>):
2. Statement 1
3. ...
4. elif (<condition 2>):
5. Statement 2
6. ...
7. else
8. Statement 3
9. ...
Remember there is no condition statement associated with else part of these flow
control statements. It will execute ig statements only in the case that of all conditions
are false.
Example
Syntax
Check In[14] and In[16]. The continue statement is used to stop for loop, in case
there is an else block missed.
while loop
A while loop is used in python to iterate over the block of expression which matches
to true. Non-zero values are True and zero and negative values are False, as
interpreted in Python.
Syntax
1. while(<condition>):
2. statement 1..
Check In[4] and In[7]. In[7]. If the user wants to add a number of his choice, then
use: n = int(input("Enter number: ")) instead of n=20. Also, check-in In[3] for a
while..else loop.
Break statement
The Python Break statement is used to break a loop in a certain condition. It
terminates the loop. Also, we can use it inside the loop then it will first terminate the
innermost loop.
Syntax
I. break
Example
Continue Statement
A continue statement won’t continue the loop, it executes statements until the
condition matches True.
Syntax
I. continue
1. while(<condition>):
2. statement 1...
3. if(<condition>):
4. continue
5. ...Statement of while loop
6.
7. ...Statements outside while loop
Example
One more additional Flow statement is PASS.
PASS
In Python, pass, and comment both are quite similar. The pass contains a Null value.
The Python interpreter ignores the comment statement, but it’s not possible to ignore
a pass statement. There is nothing is going to execute when a pass is used. It is
used as a Place Holder in a loop or a function.
Example
It executes nothing.
2. Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score is out of range, print an
error. If the score is between 0.0 and 1.0, print a grade using the following table
score =
input("Enter
Score: ")
s = float(score)
x = 'Error'
if s >= 0.9:
x = 'A'
elif s >=0.8:
x='B'
elif s >=0.7:
x='C'
elif s >= 0.6:
x='D'
elif s < .6:
x ='F'
else:
x ="Out of Range"
print (x)
3. Write a program to display the fibonacci sequences up to nth term where n is provided by the
user.
4.Write a
program to
repeatedly
check for the
largest
number until
the user
enters “done”
largest =
None
smallest = None
while True:
try:
num = raw_input("Enter a number: ")
if num == 'done':
break;
n = int(num)
largest = num if largest < num or largest == None else
largest
smallest = num if smallest > num or smallest == None else
smallest
except:
print "Invalid input"
6. Explain the need for continue and break statements. Write a program to check whether a
number is prime or not. Prompt the user for input
num = int(input("enter a number: "))
if num % i == 0:
print("not prime number")
break
else:
print("prime number")
7. Describe the syntax for the following functions and explain with an example. a) abs() b) max() c)
divmod() d) pow() e) len()
• When the object is a string, the len() function returns the number of
characters in the string.
a = 1
b = 5
c = 6
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
9.Find the area and perimeter of a circle using functions. Prompt the user for input.
def areaperi(rad) :
return area,pr
area,perimeter = areaperi(radius)
10. Write a Python program using functions to find the value of nPr and nCr without using inbuilt
factorial() function
import math;
print("Enter 'x' for exit.");
nval = input("Enter value of n: ");
if nval == 'x':
exit();
else:
rval = input("Enter value of r: ");
n = int(nval);
r = int(rval);
npr = math.factorial(n)/math.factorial(n-r);
ncr = npr/math.factorial(r);
print("ncR =",ncr);
print("nPr =",npr);
11.Write a program to print the sum of the following series 1 + 1/2 + 1/3 +. …. + 1/n
def sum(n):
i=1
s = 0.0
for i in range(1, n+1):
s = s + 1/i;
return s;
# Driver Code
n=5
print("Sum is", round(sum(n), 6))
12. Write a function which receives a variable number of strings as arguments. Find unique
characters in each string
def is_unique_1(string):
14. Write Pythonic code to multiply two matrices using nested loops and also perform transpose
of the resultant matrix.
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
for r in result:
print(r)
Output
The result:
[84, 90, 96]
[201, 216, 231]
[318, 342, 366]
15. Write Python program to sort words in a sentence in decreasing order of their length. Display
the sorted words along with their length
16. Write Pythonic code to create a function called most_frequent that takes a string and prints
the letters in decreasing order of frequency. Use dictionaries.
def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
Returning:
a) infile.read
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer: b Explanation: read function is used to read all the lines in a file.
2. Which are the two built-in functions to read a line of text from standard input, which by default
comes from the keyboard?
d) Scanner View
Answer: a
Explanation: Python provides two built-in functions to read a line of text from standard input, which
by default comes from the keyboard. These functions are: raw_input and input
a) closed
b) softspace
c) rename
d) mode
Answer: c
Explanation: rename is not the attribute of file rest all are files attributes
Answer: a
Explanation: Sets the file’s current position at the offset. The method seek() sets the file’s current
position at the offset.
Answer: a
Explanation: The method truncate() truncates the file size. Following is the syntax for truncate()
method: fileObject.truncate( [ size ])
Answer: a
Answer: a Explanation: It will look for the pattern at the beginning and return None if it isn’t found.
d) ‘are’
9. The character Dot (that is, ‘.’) in the default mode, matches any character other than
_____________
a) caret
b) ampersand
c) percentage symbol
d) newline
Answer: d
Explanation: The character Dot (that is, ‘,’) in the default mode, matches any character other than
newline. If DOTALL flag is used, then it matches any character other than newline.
10. The expression a{5} will match _____________ characters with the previous regular expression.
a) 5 or less
b) exactly 5
c) 5 or more
d) exactly 4
Answer: b
Explanation: The character {m} is used to match exactly m characters to the previous regular
expression. Hence the expression a{5} will match exactly 5 characters and not less than that.
11. ________ matches the start of the string. ________ matches the end of the string
. a) ‘^’, ‘$’
b) ‘$’, ‘^’
c) ‘$’, ‘?’
d) ‘?’, ‘^’ Answer: a Explanation: ‘^’ (carat) matches the start of the string. ‘$’ (dollar sign) matches
the end of the string.
12.What will be the output of the following Python function? re.findall("hello world", "hello", 1) a)
[“hello”] b) [ ] c) hello d) hello world View Answer Answer: b Explanation: The function findall returns
the word matched if and only if both the pattern and the string match completely, that is, they are
exactly the same.
13. . What will be the output of the following Python code? re.sub('morning', 'evening', 'good
morning')
a)‘good evening’
b)‘good’
c)‘morning’
d)‘evening’
View Answer
Answer:a
Explanation: The code shown above first searches for the pattern ‘morning’ in the string
‘good morning’ and then replaces this pattern with ‘evening’. Hence the output of this code
is: ‘good evening’.
14. What will be the output of the following Python code? re.split('[a-c]', '0a3B6', re.I)
a) Error
b) [‘a’, ‘B’]
c) [‘0’, ‘3B6’]
d) [‘a’]
Answer: c Explanation: The function re.split() splits the string on the basis of the pattern given in the
parenthesis. Since we have used the flag e.I (that is, re.IGNORECASE), the output is: [‘0’, ‘3B6’].
15. 4. Which of the following pattern matching modifiers permits whitespace and comments inside
the regular expression?
a) re.L
b) re.S
c) re.U d) re.X
Answer: d Explanation: The modifier re.X allows whitespace and comments inside the regular
expressions.
16. Which of the following special characters matches a pattern only at the end of the
string? a) \B b) \X c) \Z d) \A
Ans- c) \Z
17. Which of the following special characters represents a comment (that is, the contents
of the parenthesis are simply ignores)? a) (?:…) b) (?=…) c) (?!…) d) (?#…)
Ans- d) (?#...)
18. _____ represents an entity in the real world with its identity and behaviour. a) A
method b) An object c) A class d) An operation
19. What is setattr() used for? a) To access the attribute of the object b) To set an attribute
c) To check if an attribute exists or not d) To delete an attribute
20. The assignment of more than one function to a particular operator is _______ a)
Operator over-assignment b) Operator overriding c) Operator overloading d) Operator
instance
21. What are the methods which begin and end with two underscore characters called? a)
Special methods b) In-built methods c) User-defined methods d) Additional methods
Ans- c) Instantiation
24. Methods of a class that provide access to private members of the class are called as
______ and ______ a) getters/setters b) __repr__/__str__ c) user-defined functions/in-
built functions d) __init__/__del__
Ans- a)getters/setters
25. How many except statements can a try-except block have? a) zero b) one c) more than
one d) more than zero
26. When will the else part of try-except-else be executed? a) always b) when an exception
occurs c) when no exception occurs d) when an exception occurs in to except block
27. Can one block of except statements handle multiple exception? a) yes, like except
TypeError, SyntaxError [,…] b) yes, like except [TypeError, SyntaxError] c) no d) none of the
mentioned
28. What happens when ‘1’ == 1 is executed? a) we get a True b) we get a False c) an
TypeError occurs d) a ValueError occurs
29. What will be the output of the following Python code?g = (i for i in range(5))type(g)a)
class <’loop’> b) class <‘iteration’>c) class <’range’> d) class <’generator’>
30. What will be the output of the following Python code? lst = [1, 2, 3] lst[3] a) NameError
b) ValueError c) IndexError d) TypeError
Ans- c) IndexError
Short Answer
1.Explain split(), sub(), subn() methods of “re” module in Python.
Sub()
Subn()
re.subn (pattern, repl, string, count=0, flags=0)
This function is similar to sub() in all ways except the way in which
it provides the output. It returns a tuple with count of total of all the
replacements as well as the new string.
2. What are Python packages?
A module allows you to logically organize your 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 you can bind and reference.
3.How can files be deleted in Python?
In Python, you can use the os. remove() method to remove files, and the os. rmdir()
method to delete an empty folder. If you want to delete a folder with all of its files
4. Does Python have OOps concepts?
In Python, Polymorphism allows us to define methods in the child class with the same
name as defined in their parent class. As we know, a child class inherits all the methods
from the parent class.
This object is the base for all classes, it holds the built-in properties and
methods which are default for all classes.
Syntax
object()
LONG ANSWER
CHAPTER-3 {LONG}
1.Write Python Program to Reverse Each Word in “secret_societies.txt” file
2. Write Python Program to Count the Occurrences of Each Word and Also Count the Number of
Words in a “quotes.txt” File.
3. Write Python Program to Find the Longest Word in a File. Get the File Name from User.
def longest_words(filename):
words = infile.read().split()
print(longest_words('about.txt'))
The output of the above program is:-
re.match()
re.match() function will search the regular expression pattern and return the
first occurrence. This method checks for a match only at the beginning of the
string. So, if a match is found in the first line, it returns the match object. But if a
match is found in some other line, it returns null.
For example, consider the following code. The expression "w+" and "\W" will
match the words starting with letter 'g' and thereafter, anything which is not
started with 'g' is not identified. To check match for each element in the list or
string, we run the forloop.
In order to use search() function, you need to import re first and then execute
the code. The search() function takes the "pattern" and "text" to scan from our
main string
For example here we look for two literal strings "Software testing" "guru99", in a
text string "Software Testing is fun". For "software testing" we found the match
hence it returns the output as "found a match", while for word "guru99" we
could not found in string hence it returns the output as "No match".
re.findall()
findall() module is used to search for “all” occurrences that match a given
pattern. In contrast, search() module will only return the first occurrence that
matches the specified pattern. findall() will iterate over all the lines of the file
and will return all non-overlapping matches of pattern in a single step.
For example, here we have a list of e-mail addresses, and we want all the e-mail
addresses to be fetched out from the list, we use the re.findall method. It will
find all the e-mail addresses from the list.
5. Consider a line “From stephen.marquard\@uct.ac.za Sat Jan 5 09:14:16 2008” in the
file email.txt. Write Pythonic code to read the file and extract email address from the
lines starting from the word “From”. Use regular expressions to match email address.
import re
hand = open('email.txt')
for line in hand:
line = line.rstrip()
if re.search('^From:.+@', line):
print(line)
o/p:- From: [email protected]
6. Describe the need for catching exceptions using try and except statements
Ans-
example
try:
a = 10
b = 0
except:
o/p:
9.Given three Points (x1, y1), (x2, y2) and (x3, y3), write a Python program to check if they are
Collinear.
o/p:
15. Write Pythonic code to overload “+”, “-” and “*” operators by providing the methods __add__,
__sub__ and __mul__.
16.Write Pythonic code to create a function named move_rectangle() that takes an object of
Rectangle class and two numbers named dx and dy. It should change the location of the Rectangle
by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner
Copying an object is often an alternative to aliasing. The copy module contains a function
called copy that can duplicate any object:
>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0
>>> import copy
>>> p2 = copy.copy(p1)
p1 and p2 contain the same data, but they are not the same Point.
>>> print_point(p1)
(3.0, 4.0)
>>> print_point(p2)
(3.0, 4.0)
>>> p1 is p2
False
>>> p1 == p2
False
The is operator indicates that p1 and p2 are not the same object, which is what we expected.
But you might have expected == to yield True because these points contain the same data. In
that case, you will be disappointed to learn that for instances, the default behavior of
the == operator is the same as the is operator; it checks object identity, not object
equivalence. This behavior can be changed—we’ll see how later.
If you use copy.copy to duplicate a Rectangle, you will find that it copies the Rectangle
object but not the embedded Point.
This operation is called a shallow copy because it copies the object and any references it
contains, but not the embedded objects.
For most applications, this is not what you want. In this example,
invoking grow_rectangle on one of the Rectangles would not affect the other, but
invoking move_rectangle on either would affect both! This behavior is confusing and error-
prone.
Fortunately, the copy module contains a method named deepcopy that copies not only the
object but also the objects it refers to, and the objects they refer to, and so on. You will not be
surprised to learn that this operation is called a deep copy.
17.What is Exception? Explain Exception as control flow mechanism with suitable example.
Ex-
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
o/p-