Python interview questions

Python quiz questions

  • 1.

    Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in a parallel way.

    Answer:

    Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.

    There are reasons to use Python's threading package. If you want to run some things simultaneously, and efficiency is not a concern, then it's totally fine and convenient. Or if you are running code that needs to wait for something (like some IO) then it could make a lot of sense. But the threading library won't let you use extra CPU cores.

    Multi-threading can be outsourced to the operating system (by doing multi-processing), some external application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls (eg: you could have your Python code call a C function that does the expensive multi-threaded stuff).

    View
  • 2.

    Looking at the below code, write down the final values of A0, A1, ...An.

    A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
    A1 = range(10)
    A2 = sorted([i for i in A1 if i in A0])
    A3 = sorted([A0[s] for s in A0])
    A4 = [i for i in A1 if i in A3]
    A5 = {i:i*i for i in A1}
    A6 = [[i,i*i] for i in A1]
    

    If you dont know what zip is don't stress out. No sane employer will expect you to memorize the standard library. Here is the output of help(zip).

    zip(...)
        zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
        Return a list of tuples, where each tuple contains the i-th element
        from each of the argument sequences.  The returned list is truncated
        in length to the length of the shortest argument sequence.
    

    If that doesn't make sense then take a few minutes to figure it out however you choose to.

    Answer:

    A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
    A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
    A2 = []
    A3 = [1, 2, 3, 4, 5]
    A4 = [1, 2, 3, 4, 5]
    A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
    A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

    View
  • 3.

    Fill in the missing code:

    def print_directory_contents(sPath):
        """
        This function takes the name of a directory 
        and prints out the paths files within that 
        directory as well as any files contained in 
        contained directories. 
        This function is similar to os.walk. Please don't
        use os.walk in your answer. We are interested in your 
        ability to work with nested structures. 
        """
        fill_this_in
    

    Answer:

    def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)
    

    Pay Special Attention

    • Be consistent with your naming conventions. If there is a naming convention evident in any sample code, stick to it. Even if it is not the naming convention you usually use
    • Recursive functions need to recurse and terminate. Make sure you understand how this happens so that you avoid bottomless callstacks
    • We use the os module for interacting with the operating system in a way that is cross platform. You could say sChildPath = sPath + '/' + sChild but that wouldn't work on windows
    • Familiarity with base packages is really worthwhile, but don't break your head trying to memorize everything, Google is your friend in the workplace!
    • Ask questions if you don't understand what the code is supposed to do
    • KISS! Keep it Simple, Stupid!
    View
  • 4.

    What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer

    Answer:

    Here are a few key points:

    • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

    • Python is dynamically typed, this means that you don't need to state the types of variables when you declare them or anything like that. You can do things like x=111and then x="I'm a string" without error

    • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++'s publicprivate), the justification for this point is given as "we are all adults here"

    • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects

    • Writing Python code is quick but running it is often slower than compiled languages. Fortunately, Python allows the inclusion of C based extensions so bottlenecks can be optimised away and often are. The numpy package is a good example of this, it's really quite quick because a lot of the number crunching it does isn't actually done by Python

    • Python finds use in many spheres - web applications, automation, scientific modelling, big data applications and many more. It's also often used as "glue" code to get other languages and components to play nice.

    • Python makes difficult things easy so programmers can focus on overriding algorithms and structures rather than nitty-gritty low level details.

    View
  • 5.

    Explain how Memcached should not be used in your Python project?

    Answer:

    •  Memcached common misuse is to use it as a data store, and not as a cache
    •  Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
    •  Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
    •  Memcached does not offer any form of security either in encryption or authentication

    View
  • 6.

    Explain what is Dogpile effect? How can you prevent this effect?

    Answer:

    Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.

    View
  • 7.

    Explain how you can minimize the Memcached server outages in your Python Development?

    Answer:

    •  When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
    •  Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
    •  Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
    •  Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached

    View
  • 8.

    You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server?

    Answer:

    The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.

    View
  • 9.

    Explain database connection in Python Flask?

    Answer:

    Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command.  So you need to install sqlite3 command in order to create or initiate the database in Flask.

    Flask allows to request database in three ways

    • before_request() : They are called before a request and pass no arguments
    • after_request() : They are called after a request and pass the response that will be sent to the client
    • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed.  They are not allowed to modify the request, and their values are ignored.
    View
  • 10.

    Is Flask an MVC model and if yes give an example showing MVC pattern for your application?

    Answer:

    Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example

    from flask import Flask

    app = Flask(_name_)

    @app.route(“/”)

    Def hello():

    return “Hello World”

    app.run(debug = True)

    In this code your,
    • Configuration part will be

    from flask import Flask

    app = Flask(_name_)

    • View part will be

    @app.route(“/”)

    Def hello():

    return “Hello World”

    • While you model or main part will be

    app.run(debug = True)

    View
  • 11.

    Explain how you can access sessions in Flask?

    Answer:

    A session basically allows you to remember information from one request to another.  In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

    View
  • 12.

    Explain what is the common way for the Flask script to work?

    Answer:

    The common way for the flask script to work is

    • Either it should be the import path for your application
    • Or the path to a Python file
    View
  • 13.

    Mention what is Flask-WTF and what are their features?

    Answer:

    Flask-WTF offers simple integration with WTForms.  Features include for Flask WTF are

    • Integration with wtforms
    • Secure form with csrf token
    • Global csrf protection
    • Internationalization integration
    • Recaptcha supporting
    • File upload that works with Flask Uploads
    View
  • 14.

    Mention what is the difference between Django, Pyramid, and Flask?

    Answer:

    Flask is a “microframework” primarily build for a small application with simpler requirements.  In flask, you have to use external libraries.  Flask is ready to use.

    Pyramid are build for larger applications.  It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

    Like Pyramid, Django can also used for larger applications.  It includes an ORM.

    View
  • 15.

    Explain what is Flask & its benefits?

    Answer:

    Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.

    Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries.  It makes the framework light while there is little dependency to update and less security bugs.

    View
  • 16.

    Mention the use of the split function in Python?

    Answer:

    The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

    View
  • 17.

    Mention five benefits of using Python?

    Answer:

    • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
    • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
    • Provide easy readability due to use of square brackets
    • Easy-to-learn for beginners
    • Having the built-in data types saves programming time and effort from declaring variables
    View
  • 18.

    Mention the use of // operator in Python?

    Answer:

    It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

    View
  • 19.

    Explain how can you access a module written in Python from C?

    Answer:

    You can access a module written in Python from C by following method,

    Module =  =PyImport_ImportModule(“<modulename>”);

    View
  • 20.

    Explain how can you generate random numbers in Python?

    Answer:

    To generate random numbers in Python, you need to import command as

    import random

    random.random()

    This returns a random floating point number in the range [0,1)

    View

© 2017 QuizBucket.org