Python Interview Question and Answers part2


  1. Who created the Python programming language?
Python programming language was created by Guido van Rossum.

  1. What is Python?
Python is an open source language that is getting a lot of attention from the market.
1) Created by: Guido van Rossum nearly 11 years ago
2) Python is an interpreted, high-level programming language, pure object-oriented and powerful server-side scripting language for the Web.
3) Python is a good prototype language. In just a few minutes, you can develop prototypes that would take you several hours in other languages.

  1. When do you use list vs. tuple vs. Dictionary Vs. Set?
The main difference between lists and tuples are, lists are mutable whereas tuples are not. You can always convert a tuple type object to a list type object.

>>> p = (1,2,3,4)
>>> type(p)
<type 'tuple'>
>>> q=list(p)
>>> type(q)
<type 'list'>
>>> 

List and Tuple are both ordered containers. If you want an ordered container of constant elements use tuple as tuples are immutable objects.

Dictionaries are hash table's (so to speak) in Python. Dictionary is a powerful object  in python. Whenever you need to associate a key and value pair, it is advisable to use dictionary object.

4.      What is Python?
Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

5.      Why can't I use an assignment in an expression?
Many people used to C or Perl complain that they want to use this C idiom:
while (line = readline(f)) {
...do something with line...
}
where in Python you're forced to write this:
while True:
line = f.readline()
if not line:
break
...do something with line...
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:
 if (x = 0) {
...error handling...
} else {
...code that only works for nonzero x...
}
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.
There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution:
line = f.readline()
while line:
...do something with line...
line = f.readline()
The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop.
The best approach is to use iterators, making it possible to loop through objects using for statement.
For example, in the current version of Python file objects support the iterator protocol, so you can now write simply:
for line in f:
... do something with line...

6.      Is there a tool to help find bugs or perform static analysis?
Yes.
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code
complexity and style.
Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.

7.      How do you set a global variable in a function?
Did you do something like this?
x = 1 # make a global
def f():
print x # try to print the global
...
for j in range(100):
if q>3:
x=4
Any variable assigned in a function is local to that function. unless it is specifically declared global.
Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the print x attempts to print an uninitialized local variable and will trigger a
NameError.
The solution is to insert an explicit global declaration at the start of the function:
def f():
   global x
print x # try to print the global
...
for j in range(100):
  if q>3:
    x=4
In this case, all references to x are interpreted as references to the x from the module namespace.

8.      What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is
assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is
ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.
Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

9.      How do I share global variables across modules?
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1

main.py:
import config
import mod
print config.x
Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

10.  How can I pass optional or keyword parameters from one function to another?
Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:
def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
g(x, *tup, **kwargs)
In the unlikely case that you care about Python versions older than 2.0, use 'apply':
def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
apply(g, (x,)+tup, kwargs)

11.  How do you make a higher order function in Python?
You have two choices: you can use nested scopes or you can use callable objects. For ex, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b.
Using nested scopes:
def linear(a,b):
  def result(x):
     return a*x + b
  return result
Or using a callable object:
class linear:
   def __init__(self, a, b):
      self.a, self.b = a,b
  def __call__(self, x):
      return self.a * x + self.b
In both cases:
 taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer
code. However, note that a collection of callables can share their signature via inheritance:
class exponential(linear):
  # __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
Object can encapsulate state for several methods:
class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set
Here inc(), dec() and reset() act like functions which share the same counting variable.

12.  How do I copy an object in Python?
In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. Some objects can be copied more easily. Dictionaries have a copy() method:
newdict = olddict.copy()
Sequences can be copied by slicing:
new_l = l[:]

13.  How can I find the methods or attributes of an object?
For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

Comments