smallseo.info

python interview questions

Top python frequently asked interview questions

Calling an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?


Source: (StackOverflow)

How can I make a chain of function decorators in Python?

How can I make two decorators in Python that would do the following?

@makebold
@makeitalic
def say():
   return "Hello"

which should return

"<b><i>Hello</i></b>"

I'm not trying to make HTML this way in a real application, just trying to understand how decorators and decorator chaining works.


Source: (StackOverflow)

What does `if __name__ == "__main__":` do?

What does the if __name__ == "__main__": do?

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
    while 1:
        lock.acquire()
        time.sleep(sleeptime)
        lock.release()
        time.sleep(sleeptime)
if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

Source: (StackOverflow)

Parse String to Float or Int

In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222? Or parse the string "31" to an integer, 31?

I just want to know how to parse a float string to a float, and (separately) an int string to an int.


Source: (StackOverflow)

How can I represent an 'Enum' in Python?

I'm mainly a C# developer, but I'm currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?


Source: (StackOverflow)

How can I merge two Python dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)


Source: (StackOverflow)

Finding the index of an item given a list containing it in Python

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?


Source: (StackOverflow)

Does Python have a string contains substring method?

I'm looking for a string.contains or string.indexof method in Python.

I want to do:

if not somestring.contains("blah"):
   continue

Source: (StackOverflow)

Accessing the index in Python for loops

Does anyone know how to access the index itself for a list like this:

ints = [8, 23, 45, 12, 78]

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?


Source: (StackOverflow)

Is there a way to run Python on Android?

We are working on an S60 version and this platform has a nice Python API.

However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together?


Source: (StackOverflow)

Using global variables in a function other than the one that created them

If I create a global variable in one function, how can I use that variable in another function?
Do I need to store the global variable in a local variable of the function which needs its access?


Source: (StackOverflow)

How do I install pip on Windows?

pip is a replacement for easy_install. But I will install pip using easy_install on Windows. Is there a better way?


Source: (StackOverflow)

Sort a Python dictionary by value

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.


Source: (StackOverflow)

"Least Astonishment" in Python: The Mutable Default Argument

Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:

def foo(a=[]):
    a.append(5)
    return a

Python novices would expect this function to always return a list with only one element: [5]. The result is instead very different, and very astonishing (for a novice):

>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()

A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)

Edit:

Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:

>>> def a():
...     print "a executed"
...     return []
... 
>>>            
>>> def b(x=a()):
...     x.append(5)
...     print x
... 
a executed
>>> b()
[5]
>>> b()
[5, 5]

To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?

Doing the binding inside the function would mean that x is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the def line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.

The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.


Source: (StackOverflow)

Catch multiple exceptions in one line (except block)

I know that I can do:

try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

I can also do this:

try:
    # do something that may fail
except IDontLikeYourFaceException:
    # put on makeup or smile
except YouAreTooShortException:
    # stand on a ladder

But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:

try:
    # do something that may fail
except IDontLIkeYouException:
    # say please
except YouAreBeingMeanException:
    # say please

Is there any way that I can do something like this (since the action to take in both exceptions is to say please):

try:
    # do something that may fail
except IDontLIkeYouException, YouAreBeingMeanException:
    # say please

Now this really won't work, as it matches the syntax for:

try:
    # do something that may fail
except Exception, e:
    # say please

So, my effort to catch the two distinct exceptions doesn't exactly come through.

Is there a way to do this?


Source: (StackOverflow)