0% found this document useful (0 votes)
106 views20 pages

Assignment 4,5,6

The document contains questions related to Python functions, modules, packages and object oriented programming. It includes descriptive questions about defining functions, parameter passing, returning values from functions, local and global variables, default arguments, variable length arguments, built-in functions, modules, importing modules, lambda expressions, map function, matplotlib and object oriented concepts like classes, constructors, self parameter etc. It also contains 40 multiple choice questions related to these topics.

Uploaded by

12nzalte
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)
106 views20 pages

Assignment 4,5,6

The document contains questions related to Python functions, modules, packages and object oriented programming. It includes descriptive questions about defining functions, parameter passing, returning values from functions, local and global variables, default arguments, variable length arguments, built-in functions, modules, importing modules, lambda expressions, map function, matplotlib and object oriented concepts like classes, constructors, self parameter etc. It also contains 40 multiple choice questions related to these topics.

Uploaded by

12nzalte
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/ 20

4.

Python Functions, Modules and Packages


-------------------------------------------------------------------------------
Position in Question Paper Total Marks: 14
Q.1 e) 2-Marks.
Q.2 d) 4-Marks.
Q.3 d) 4-Marks.
Q.5 b) 6-Marks.
------------------------------------------------------------------------------------------------
Descriptive Question:
1. Define function.
2. How to create user-defined function in python?
3. Explain the concept of parameter passing to python function.
4. Can python function return the value? Justify your answer with example.
5. Define and explain local variables and global variables with suitable
examples.
6. Write a short note on: Functions with default arguments.
7. What is kwargs in python? Explain its use.
8. Does the python allow the nested function definitions? Justify your answer.
9. Write a python program to demonstrate variable length arguments. Also
explain that program.
10. Explain the following built in functions.
a) all() b) hasattr() c) oct() d) eval() e) issubclass ()
11. Explain any four data conversions functions in python.
12. Explain input() and print() functions in python .
13. How to create the module in python?
14. Explain from……import statement.
15. Explain python built-in module: random
16. Explain use of lambda expression with example.
17. Explain the use map function with example.
18. Write a program to create bar chart using matplotlib.

MCQ Question:
1)Which keyword is use for function?
a) define b) fun
c) def d) function
2)Which of the following items are present in the function header?
a) function name b) parameter list
c) return value d) Both A and B
3a) class b) function
c) method d) module
4)What is the output of following code. X=10; y=bin(x); print(y)
a) b10100 b) 0b1010
c) 10b100 d)1b0010
5)Identify whether the following statement is correct or not.
a) True b) False
6) If return statement is not used inside the function, the function will return:
a) None b) 0
c) Null d) Arbitary value
7) Which of these definitions correctly describes a module?
a) Denoted by triple quotes for providing the specification of certain program
elements
b) Design and implementation of specific functionality to be incorporated into a
program
c) Defines the specification of how it is to be used
d) Any program that reuses code
8) Program code making use of a given module is called a ______ of the
module.
a) Client b) Docstring
c) Interface d) Modularity
9) Which of the following isn’t true about main modules?
a) When a python file is directly executed, it is considered main module of a
program
b) Main modules may import any number of modules
c) Special name given to main modules is: __main__
d) Other main modules can import main modules
10) Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
11) What is a recursive function?
a) A function that calls other function.
b) A function which calls itself.
c) Both A and B
d) None of the above
12) In which part of memory does the system stores the parameter and local
variables of
funtion call?
a) heap b) stack
c) Uninitialized data segment d) None of the above
13) Which of the following is not an advantage of using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks)What is called when a function is
defic) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
14) Which of these definitions correctly describes a module?
a) Denoted by triple quotes for providing the specification of certain program
elements
b) Design and implementation of specific functionality to be incorporated into a
program
c) Defines the specification of how it is to be used
d) Any program that reuses code
15) Program code making use of a given module is called a ______ of the
module.
a) Client b) Docstring
c) Interface d) Modularity
16) In top-down design every module is broken into same number of
submodules.
a) True b) False
17) Which of the following is true about top-down design process?
a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed
18) All modular designs are because of a top-down design process.
a) True b) False
19) What will be the output of the following Python code?
#mod1
def change(a):
b=[x*2 for x in a]
print(b)
#mod2
def change(a):
b=[x*x for x in a]
print(b)
from mod1 import change
from mod2 import change
#main
s=[1,2,3]
change(s)
a) [2,4,6] b) [1,4,9]
c) [2,4,6][1,4,9] d) There is a name clash
20) What will be the output of the following Python code?
from math import factorial
print(math.factorial(5))
a) 120
b) Nothing is printedned inside a class?
c) Error, method factorial doesn’t exist in math module
d) Error, the statement should be: print(factorial(5))
22) What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and
finally the
built-in namespace
b) Python first searches the local namespace, then the global namespace and
finally the built-in namespace
c) Python first searches the built-in namespace, then the global namespace and
finally
the local namespace
d) Python first searches the built-in namespace, then the local namespace and
finally
the global namespace
23) Which of the following is false about “import modulename” form of
import?
a) The namespace of imported module becomes part of importing module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier
24) What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and
finally the
built-in namespace
b) Python first searches the local namespace, then the global namespace and
finally the built-in namespace
c) Python first searches the built-in namespace, then the global namespace and
finally
the local namespace
d) Python first searches the built-in namespace, then the local namespace and
finally
the global namespace
25) What will be the output of the following Python code?
1. def printMax(a, b):
2. if a > b:
3. print(a, 'is maximum')
4. elif a == b:
5. print(a, 'is equal to', b)
6. else:
7. print(b, 'is maximum')
8. printMax(3, 4)
a) 3 b) 4
c) 4 is maximum d) None of the mentioned
26) What will be the output of the following Python code?
1. x = 50
2. def func(x):
3. print('x is', x)
4. x = 2
5. print('Changed local x to', x)

6. func(x)
7. print('x is now', x)
a) x is 50, Changed local x to 2, x is now 50
b) x is 50, Changed local x to 2, x is now 2
c)x is 50, Changed local x to 2, x is now 100
d) None of the mentioned
27) What will be the output of the following Python code?
1. x = 50
2. def func():
3. global x
4. print('x is', x)
5. x = 2
6. print('Changed global x to', x)
7. func()
8. print('Value of x is', x)
a) x is 50, Changed global x to 2, Value of x is 50
b) x is 50, Changed global x to 2, Value of x is 2
c) x is 50, Changed global x to 50, Value of x is 50
d) None of the mentioned
28) What will be the output of the following Python code?
1. def maximum(x, y):
2. if x > y:
3. return x
4. elif x == y:
5. return 'The numbers are equal'
6. else:
7. return y
8.
9. print(maximum(2, 3))
a) 2 b) 3
c) The numbers are equal d) None of the mentioned
29) Which of the following functions can help us to find the version of python
that we are
currently working on?
a) sys.version b) sys.version()
c) sys.version(0) d) sys.version(1)
30) The output of the functions len(“abc”) and sys.getsizeof(“abc”) will be the
same.
a) True b) False
31) What will be the output of the following Python code, if the sys module has
already been
imported?
sys.stdout.write("hello world")
a) helloworld b) hello world10
c) hello world11 d) error

32) Which of the following functions is not defined under the sys module?
a) sys.platform b) sys.path
c) sys.readline d) sys.argv
33) The output of the function len(sys.argv) is ____________
a) Error b) 1
c) 0 d) Junk value
34) To obtain a list of all the functions defined under sys module, which of the
following
functions can be used?
a) print(sys) b) print(dir.sys)
c) print(dir[sys]) d) print(dir(sys))
35) Which of the following functions is a built-in function in python?
a) seed() b) sqrt()
c) factorial() d) print()
36) The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z
c) (x**y) % z d) (x**y)*z
37) What will be the output of the following Python code?
import sys
sys.argv[0]
a) Junk value b) ‘ ‘
c) No output d) Error
38) What will be the output of the following Python code?
import sys
eval(sys.stdin.readline())
"India"
a) India5 b) India
c) ‘India\n’ d) ‘India’
39) Which of the following is the use of id() function in python?
a) Id() returns the size of object. b) Both A and B
b) Id() returns the identity of the object d) None of the above
40) What will be the output of the following Python expression? round(4.576)
a) 4.5 b) 5
c) 4 d) 4.6

5. Object Oriented Programming in Python


-------------------------------------------------------------------------------
------------
Position in Question Paper Total Marks: 12
Q.2 d) 4-Marks.
Q.3 e) 4-Marks.
Q.4 d) 4-Marks.
-------------------------------------------------------------------------------
------------
Descriptive Question:
1. What is class? How to declare class in python?
2. State the use of parameter ‘self’ in python class.
3. Explain constructor function in python class with example.
4. Can we overload constructor function in python? Justify your answer.
5. Can we call constructor and destructor function manually in python? Justify
your
answer.
6. Write a program to demonstrate parameterized constructor in base class and
derived
class.
7. How to create abstract method in python? Explain with example.
8. Python dose not allowed method overloading. Then explain alternate ways of
achieving the similar effect of overloading.
9. Write a short note on method overriding in python.
10. Explain the use _str_() and _repr()function in Python.
MCQ Question:
1.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
2.Which of the following is not a class method?
a) Non-static
b) Static
c) Bounded
d) Unbounded
3.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
4. Special methods need to be explicitly called during object creation.
a) True b) False
5.__del__ method is used to destroy instances of a class.
a) True b) False
6.What does print(Test.__name__) display (assuming Test is the name of the
class)?
ac) Test d) __main__
7.What is hasattr(obj,name) used for?
a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute
8.What is delattr(obj,name) used for?
a) To print deleted attribute
b) To delete an attribute
c) To check if an attribute is deleted or not
d) To set an attribute
9.Is the following Python code valid?
class B(object):
def first(self):
print("First method called")
def second():
print("Second method called")
ob = B()
B.first(ob)
a) It isn’t as the object declaration isn’t right
b) It isn’t as there isn’t any __init__ method for initializing class members
c) Yes, this method of calling is called unbounded method call
d) Yes, this method of calling is called bounded method call
10. What will be the output of the following Python code?
>>> class demo():
def __repr__(self):
return '__repr__ built-in function called'
def __str__(self):
return '__str__ built-in function called'
>>> s=demo()
>>> print(s)
a) __str__ called
b) __repr__ called
c) Error
d) Nothing is printed
11. Which of the following statements is wrong about inheritance?
a) Protected members of a class can be inherited
b) The inheriting class is called a subclass
c) Private members of a class can be inherited and accessed
d) Inheritance is one of the features of OOP
12. What will be the output of the following Python code?
class A():
def disp(self):
print("A disp()")) () b) Exception is thrown

class B(A):
pass
obj = B()
obj.disp()
a) Invalid syntax for inheritance
b) Error because when object is created, argument must be passed
c) Nothing is printed
d) A disp()
13. Which of the following is not a type of inheritance?
a) Double-level
b) Multi-level
c) Single-level
d) Multiple
14. What type of inheritance is illustrated in the following Python code?
class A():
pass
class B():
pass
class C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance
15. Suppose B is a subclass of A, to invoke the __init__ method in A from B,
what is the
line of code you should write?
a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)
16. What is meant by Method Overloading?
a) Same function name with same parameters in terms of length
b) Different function names with same parameters in terms of type
c) Same function name with different parameters in terms of length and type
d) Different function name with different parameters in terms of length and type
17. Python naturally supports Method Overloading :
a)True b)False
18. Method Overloading reduces the code :
a)True b)False
19. Method Overloading can be achieved by using :
a)Formal Arguments
b)Actual Arguments
c)Default Arguments
d)All of these
20. If user haven’t pass any argument in function, to make result errorless it is
must :
a)Default arguments should be present
b)Function shouldn’t take any arguments
c)Both a and b
d)None of these
21.Which of these is not a fundamental features of OOP?

a) Encapsulation
b) Inheritance
c) Instantiation
d) Polymorphism
22. Which of the following is the most suitable definition for encapsulation?
a) Ability of a class to derive members of another class as a part of its own
definition
b) Means of bundling instance variables and methods in order to restrict access
to certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and
easily modified
23. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def display(self):
return self.__b
obj = Demo()
print(obj.a)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a
private member
c) The program runs fine and 1 is printed
d) The program has an error as you can’t name a class member using __b
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__
24. Private members of a class cannot be accessed.
a) True b) False
25. The purpose of name mangling is to avoid unintentional access of private
class members.
a) True b) False
26. Which of the following is false about protected class members?
a) They begin with one underscore
b) They can be accessed by subclasses
c) They can be accessed by name mangling method
d) They can be accessed within a class
27. Which of the following best describes polymorphism?
a) Ability of a class to derive members of another class as a part of its own
definition
b) Means of bundling instance variables and methods in order to restrict access
tocertain class members
c) Focuses on variables and passing of variables to functions
d) Allows for objects of different types and behaviour to be treated as the same
general type
28. What is the use of duck typing?
a) More restriction on the type values that can be passed to a given method
b) No restriction on the type values that can be passed to a given method
c) Less restriction on the type values that can be passed to a given method
d) Makes the program code smaller
29.What is the biggest reason for the use of polymorphism?
a) It allows the programmer to think at a more abstract level
b) There is less program code to write
c) The program will have a more elegant design and will be easier to maintain
and update
d) Program code takes up less space
30. A class in which one or more methods are only implemented to raise an
exception is
called an abstract class.
a) True b) False
31. Overriding means changing behaviour of methods of derived class methods
in the base
class.
a) True b) False
32. Which of the following statements is true?
a) A non-private method in a superclass can be overridden
b) A subclass method can be overridden by the superclass
c) A private method in a superclass can be overridden
d) Overriding isn’t possible in Python
33.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
34.When is the finally block executed?
a) when there is no exception
b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always
35. All subclasses are a subtype in object-oriented programming. Is the
statement true or
false?
a) True
b) False
c) May be
d) Can't say
36.What does single-level inheritance mean?
a) A subclass derives from a class which in turn derives from another class
b) A single superclass inherits from multiple subclasses
c) A single subclass derives from a single superclass

d) Multiple base classes inherit a single derived class


37.Which of the following statements isn’t true?
a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the
subclass
d) When invoking the constructor from a subclass, the constructor of superclass
is
automatically invoked
38. Method issubclass() checks if a class is a subclass of another class. True or
False?
a) True
b) False
c) May be
d) Can't say
39. Which of the following best describes polymorphism?
a) Ability of a class to derive members of another class as a part of its own
definition
b) Means of bundling instance variables and methods in order to restrict access
to
certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for objects of different types and behaviour to be treated as the same
general type
40.What is the biggest reason for the use of polymorphism?
a) It allows the programmer to think at a more abstract level
b) There is less program code to write
c) The program will have a more elegant design, and will be easier to maintain
and update
d) Program code takes up less space

6. File I/O Handling and Exception Handling


-------------------------------------------------------------------------------
------------
Position in Question Paper Total Marks: 12
Q.2 c) 4-Marks.
Q.3 d) 4-Marks.
Q.6 c) 6-Marks.
-------------------------------------------------------------------------------
------------
Descriptive Question:
1. Explain print() function with its arguments.
2. Explain following file related operations:
a) Opening a file b) writing into a file using write() function
c) reading from a file using readline() function
3. Explain any four file modes in python.
4. Explain seek() and tell() function for file pointer manipulation.
5. Explain following python function w.r.t Dictionary.
a) getcwd() b) mkdir() I c) chdir() d) listdir() e) exist()
6. Explain rename() and remove() function w.r.t Dictionary.
7. Explain use of try:except block with example.
8. Write a program to demonstrate try with multiple exception.
9. Explain except: block without any exception name to it.
10. Can a single except: block handle multiple exception?
11. How to manually raise an exception? Explain with example.
12. How to create user defined exception and raise it manually? Explain with a
complete
example.
MCQ Question:
1. How many except statements can a try-except block have?
a) zero
b) one
c) more than one
d) more than zero
2. Which of the following is not an exception handling keyword in Python?
a) try
b) except
c) accept
d) finally
3. Which block lets you test a block of code for errors?
a) try
b) except
c) finally
d4. What will be output for the following code?
try:
print(x)
except:
print(""An exception occurred"")
a) x
b) An exception occurred
c) Error
d) None of the above
5.What will be output for the following code?
x = ""hello""
if not type(x) is int:
raise TypeError(""Only integers are allowed"")
a) hello
b) garbage value
c) Only integers are allowed
d) Error
6. What will be output for the following code?
try:
f = open(""demofile.txt"")
f.write(""Lorum Ipsum"")
except:
print(""Something went wrong when writing to the file"")
finally:
f.close()
a) demofile.txt
b) Lorum Ipsum
c) Garbage value
d) Something went wrong when writing to the file
7. Which exception raised when a calculation exceeds maximum limit for a
numeric type?
a) StandardError
b) ArithmeticError
c) OverflowError
d) FloatingPointError
8. Which exception raised in case of failure of attribute reference or
assignment?
a) AttributeError
b) EOFError
c) ImportError
d) AssertionError
9. 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 above
10. The following Python code will result in an error if the input value is
entered as -5.
a) True
b) False
c) Can be true or false
d) Cannot say
11. What will be output for the following code?
x=10 ; y=8
assert x>y, 'X too small) None of the above

a) Assertion Error
b) 10 8
c) No output
d) 108
12. Which of the following statements is true?
a) The standard exceptions are automatically imported into Python programs
b) All raised standard exceptions must be handled in Python
c) When there is a deviation from the rules of a programming language, a
semantic
error is thrown
d) If any exception is thrown in try block, else block is executed
13. ___________exceptions are raised as a result of an error in opening a
particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError
14. An exception is ____________
a) an object
b) a special function
c) a standard module
d) a module
15. The readlines() method returns ____________
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
16. When is the finally block executed?
a) when there is no exception
b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always
17. 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
18. Which of the following blocks will be executed whether an exception is
thrown or not?
a) except
b) else
c) finally
d) assert
19. Which of the following is not a standard exception in Python?
a) NameError
b) IOError
c) AssignmentError
d) ValueError
20. What will be the output of the following Python code?
int('65.43')
a) ImportError
b) ValueError
c) TypeError
d) NameError
21. To read the next line of the file from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
22. To open a file c:\scores.txt for reading, we use _____________
a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)

c) infile = open(file = “c:\scores.txt”, “r”)


d) infile = open(file = “c:\\scores.txt”, “r”)
23. Which of the following statements are true?
a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is
created
c) When you open a file for writing, if the file exists, the existing file is
overwritten
with the new file
d) All of the mentioned
24. To read two characters from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
25. To read the remaining lines of the file from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
26. Which are the two built-in functions to read a line of text from standard
input, which by
default comes from the keyboard?
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner
d) Scanner
27. Which one of the following is not attributes of file?
a) closed
b) softspace
c) rename
d) mode
28. What is the use of tell() method in python?
a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned
29. What is the current syntax of rename() a file?
a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned
30. What is the use of seek() method in files?
a) sets the file’s current position at the offset
b) sets the file’s previous position at the offset
c) sets the file’s current position within the file
d) none of the mentioned
31. What is the use of truncate() method in file?
a) truncates the file size
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned
32. Which is/are the basic I/O connections in file?
a) Standard Input b) Standard Output
c) Standard Errors d) All of the mentioned
33. Which function is used to write a list of string in a file?
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()
34. Which function is used to close a file in python?
a) Close()
b) Stop()
c) End()
d) Closefile()
35. Which function is used to read all the characters?
a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()
36. Which of the following is not a valid mode to open a file?
a) ab
b) rw
c) r+
d) w+
37. What is the current syntax of rename() a file?
a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned
38. What will be the output of the following Python code?
f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)
a) True
b) False
c) None
d) Error
39. What will be the output of the following Python code?
def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))
a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
40. 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

You might also like