Interview questions and answers

Ques: How are the functions help() and dir() different?
Ans: These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions.

help :
  • It will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc.
  • To view the help for a keyword, topics, you just need to type, help("<keyword>")
dir :
  • Without arguments, it will return list of names in the current local scope. 
  • With an argument, it will return a list of valid attributes for that object.
Ques: Which statement of Python is used whenever a statement is required syntactically but the program needs no action?
Ans: pass is no-operation / action statement in Python.
If we want to get data from a model and even if the requested data does not exist, we want to continue with other tasks. In such a scenario, use try-except block with pass statement in the except block. Ex:
obj = None
try :
      obj = ModelName.objects.get(pk=112)
except :
      pass

Ques: What is a Python module?
Ans: A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name .
A module can be imported by other modules in one of the two ways. They are
  • import
  • from module-name import
Ques: Name the File-related modules in Python?
Ans: Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil.
  • os and os.path – modules include functions for accessing the filesystem
  • shutil – module enables you to copy and delete the files.
Ques: Explain the shortest way to open a text file and display its contents?
Ans: The shortest way to open a text file is by using “with” command as follows:
with open("file-name", "r") as fp:
fileData = fp.read()
#to print the contents of the file print(fileData)

Ques: How do you create a dictionary which can preserve the order of pairs?
Ans: We know that regular Python dictionaries iterate over <key, value> pairs in an arbitrary order, hence they do not preserve the insertion order of <key, value> pairs.
Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the same interface like the general dictionaries but it traverse through keys and values in an ordered manner depending on when a key was first inserted.
Ex:
from collections import OrderedDict
d = OrderDict([('Company-id':1),('Company-Name':'ABC')])
d.items() # displays the output as: [('Company-id':1),('Company-Name':'ABC')]

Ques: When does a dictionary is used instead of a list?
Ans: Dictionaries are best suited when the data is labelled, i.e., the data is a record with field names.
Lists are better option to store collections of un-labelled items say all the files and sub directories in a folder.
Generally search operation on dictionary object is faster than searching a list object.

Ques: What is the use of enumerate() in Python?
Ans: Using enumerate() function we can iterate through the sequence and retrieve the index position and its corresponding value at the same time.
for i,v in enumerate([‘abc’,’123’,’xyz’]):
     print(i,v)
     # 0 abc
     # 1 123
     # 2 xyz

Ques: How many kinds of sequences are supported by Python? What are they?
Ans: Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and buffer. where xrange is deprecated in python 3.5.X.

Ques: Is Python object oriented? what is object oriented programming?
Ans : Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.

Ques: How instance variables are different from class variables?
Ans: Instance variables are the variables in an object that have values that are local to that object. Two objects of the same class maintain distinct values for their variables. These variables are accessed with “object-name.instancevariable-name”.

Class variables are the variables of class. All the objects of the same class will share value of “Class variables. They are accessed with their class name alone as “class- name.classvariable-name”. If you change the value of a class variable in one object, its new value is visible among all other objects of the same class. In the Java world, a variable that is declared as static is a class variable.

Ques: What is the reason for the try-except-else to exist?
Ans: A try block allows you to handle a expected error. The except block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.

The else-clause runs when there is no exception but before the finally-clause. That is its primary purpose.

The most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.

   n = Input("enter a number")
   try:
       recip = 1 / n
   except ZeroDivisionError:
       logging.info('Infinite result')
   else:
       logging.info('Finite result')

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?