by BehindJava

Python Interview Questions Part 3

Home » python » Python Interview Questions Part 3

In this tutorial we are going to see important Python Interview Questions.

Q. What is a namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

A namespace is a collection of names. It maps names to corresponding objects. When different namespaces contain objects with the same names, this avoids any name collisions. Internally, a namespace is implemented as a Python dictionary.

On starting the interpreter, it creates a namespace for as long as we don’t exit. We have local namespaces, global namespaces, and a built-in namespace.

Q. Explain the differences between local and global namespaces.

Local namespaces are created within a function. when that function is called. Global name spaces are created when the program starts.

Q. Name the four main types of namespaces in Python?

Global, Local, Module and Class namespaces.

Q. When would you use triple quotes as a delimiter?

Triple quotes ”"" or ’” are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.

Q. How to use GUI that comes with Python to test your code?

That is just an editor and a graphical version of the interactive shell. You write or load code and run it, or type it into the shell. There is no automated testing.

Q. How does the Python version numbering scheme work?

Python versions are numbered A.B.C or A.B.

  • A is the major version number. It is only incremented for major changes in the language.
  • B is the minor version number, incremented for less earth-shattering changes.
  • C is the micro-level. It is incremented for each bug fix release.
  • Not all releases are bug fix releases.

In the run-up to a new major release, ‘A’ series of development releases are made denoted as alpha, beta, or release candidate.

  • Alphas are early releases in which interfaces aren’t finalized yet; it’s not unexpected to see an interface change between two alpha releases.
  • Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs.
  • Alpha, beta and release candidate versions have an additional suffix.
  • The suffix for an alpha version is “aN” for some small number N,
  • The suffix for a beta version is “bN” for some small number N,
  • And the suffix for a release candidate version is “cN” for some small number N.

In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0.

You may also find version numbers with a ”+” suffix, e.g. “2.2+“. These are unreleased versions, built directly from the subversion trunk. In practice, after a final minor release is made, the subversion trunk is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”.

Q. Where is math.py (socket.py, regex.py, etc.) source file?

If you can’t find a source file for a module, it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like mathmodule.c, somewhere in a C source directory (not on the Python Path). There are (at least) three kinds of modules in Python:

  • Modules written in Python (.py);
  • Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
  • Modules written in C and linked with the interpreter; to get a list of these, type;
  • Import sys print sys.builtinmodulenames;

Q. How do I make a Python script executable on UNIX?

You need to do two things:

  • The script file’s mode must be executable and the first line must begin with ”#!” followed by the path of the Python interpreter.
  • The first is done by executing chmod +x scriptfile or perhaps chmod 755 ‘script’ file.
  • The second can be done in a number of ways.
  • The most straightforward way is to write:

    #!/usr/local/bin/python

    as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the “env” program. Almost all UNIX variants support the following, assuming the python interpreter is in a directory on the users $PATH:

    #! /usr/bin/env python

    Don’t do this for CGI scripts. The $PATH variable for CGI scripts is often minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user’s environment is so full that the /usr/bin/env program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):

    #! /bin/sh
    """:"
    exec python $0 ${1+"$@"}
    """
    The minor disadvantage is that this defines the script's __doc__string. However, you can fix that by adding:
    __doc__ = """…Whatever…"""

    Q. Why do not my signal handlers work?

The most common problem is that the signal handler is declared with the wrong argument list. It is called as:

  • handler (signum, frame)

So it should be declared with two arguments:

  • def handler(signum, frame):

Q. How do I find undefined g++ symbols _builtinnew or _purevirtual?

To dynamically load g++ extension modules, you must: Recompile Python Re-link it using g++ (change LINKCC in the python Modules Makefile) Link your extension module using g++ (e.g., “g++ -shared -o mymodule.so mymodule.o”).

Q. How do I send mail from a Python script? Use the standard library module smtplib. Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.

import sys, smtplib
fromaddr = raw_input("From: ")
toaddrs = raw_input("To: ").split(',')
print "Enter message, end with ^D:"
msg = "
while 1:
    line = sys.stdin.readline()
    if not line:
        break

msg = msg + line

# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A UNIX-only alternative uses send mail. The location of the send mail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The send mail manual page will help you out. Here's some sample code:

SENDMAIL = "/usr/sbin/sendmail" # sendmail location
import os
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.comn")
p.write("Subject: testn")
p.write("n") # blank line separating headers from body
p.write("Some textn")
p.write("some more textn")
sts = p.close()
if sts != 0:
    print ("Sendmail exit status", sts)

Q. How can I mimic CGI form submission (METHOD=POST)? I would like to retrieve web pages that are the result of posting a form.

Yes. Here is a simple example that uses httplib:

#!/usr/local/bin/python
import httplib, sys, time

### build the query string
qs = "First=Josephine&MI=Q&Last=Public"

### connect and send the server a path
httpobj = httplib.HTTP('www.some-server.out-there', 80)
httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')

### now generate the rest of the HTTP headers…
httpobj.putheader('Accept', '*/*')
httpobj.putheader('Connection', 'Keep-Alive')
httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
httpobj.putheader('Content-length', '%d' % len(qs))
httpobj.endheaders()
httpobj.send(qs)

### find out what the server said in response…
reply, msg, hdrs = httpobj.getreply()
if reply != 200:
sys.stdout.write(httpobj.getfile().read())
Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name="Guy Steele, Jr.":

from urllib import quote
x = quote("Guy Steele, Jr.")
print(x)
'Guy%20Steele,%20Jr.'
 query_string = "name="+x
 query_string
'name=Guy%20Steele,%20Jr.'

Q. Why is that none of my threads are not running? How can I make it work?

As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.

A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:

import threading, time
def thread_task(name, n):
for i in range(n): print name, i
for i in range(10)

Q. What Are The Implementation In Python Program?

Python program can be implemented by two ways

  1. Interactive Mode (Submit statement by statement explicitly)
  2. Batch Mode (Writing all statements and submit all statements).

In Interactive mode python command shell is required. It is available in installation of python cell.

In Interactive mode is not suitable for developing the projects & Applications

Interactive mode is used for predefined function and programs. Example:

X=1000
Y=2000
X+Y
3000
Quit(X+Y)
X, Y is not find.

Interactive mode is unfit for looping purpose.

Interactive Mode:

The concept of submitting one by one python statements explicitly in the python interpreter is known as “Interactive Mode”

In Order to submit the one by one python statements explicitly to the python interpreter we use python command line shell.

Python command line shell is present in python software We can open the python command line shell by executing python command on command prompt or terminal Example:

c:/users/mindmajix>python
3+4
7

'mindmajix'*3
'mindmajix mindmajix mindmajix'

x=1000
y=2000
x+y
3000
Quit
x+y
c:/users/sailu>python
Error: name 'X' not defined

Batch Mode:

In the concept of writing the group of python statements in a file, save the file with extension .py and submit that entire file to the python interpreter is known as Batch Mode.

In Order to develop the python files we use editors or IDE’s Different editors are notepad, notepad++, edit+,nano, VI, gedil and so on. Open the notepad and write the following code:

Example:

X=1000
Y=2000
print(x+y, x-y, x*y)

Save the file in D drive mindmajix python folder with the demo.py Open command prompt and execute following commands:

Python D:/mindmajix python/Demo.py

3000

-1000

2000.000

Save another method if we correctly set the path

D:

D:/>cd "mindmajix python"

D:/mindmajix Python>python Demo.py
3000
-1000
2000.000

Q. What are The Data Types Supports in Python Language?

  • Numbers- Numbers use to hold numerical values.
  • Strings- A string is a sequence of characters. We declare it using single or double quotes.
  • Lists- A list is an ordered collection of values, and we declare it using square brackets.
  • Tuples- A tuple, like a list, is an ordered collection of values. The difference. However, is that a tupleis immutable. This means that we cannot change a value in it.
  • Dictionary- A dictionary is a data structure that holds key-value pairs. We declare it using curly braces. We can also use a dictionary comprehension:
  • Numbers:
  • Int
  • Float
  • Complex
  • Boolean
  • Operational:
  • Strings
  • List
  • Tuple
  • Set
  • Dictionary

Every data type in python language is internally implemented as a class. Python language data types are categorized into two types.

They are:

  1. Fundamental Types
  2. Collection Types

Control Flow

Q. Explain Control flow statements.

By default python program execution starts from first line, execute each and every statements only once and transactions the program if the last statement of the program execution is over. Control flow statements are used to disturb the normal flow of the execution of the program.

Q. What are the two major loop statements?

for and while

Q. Under what circumstances would one use a while statement rather than for?

The while statement is used for simple repetitive looping and the for statement is used when one wishes to iterate through a list of items, such as database records, characters in a string, etc.

Q. What happens if output an else statement after after block?

The code in the else block is executed after the for loop completes, unless a break is encountered in the for loop execution. in which case the else block is not executed.

Q. Explain the use of break and continue in Python looping.

The break statement stops execution of the current loop. and transfers control to the next block. The continue statement ends the current block’s execution and jumps to the next iteration of the loop.

Q. When would you use a continue statement in a for loop?

When processing a particular item was complete; to move on to the next, without executing further processing in the block. The continue statement says, “I’m done processing this item, move on to the next item.”

Q. When would you use a break statement in a for loop?

When the loop has served its purpose. As an example. after finding the item in a list searched for, there is no need to keep looping. The break statement says, I’m done in this loop; move on to the next block of code.”

Q. What is the structure of a for loop?

for in : … The ellipsis represents a code block to be executed, once for each item in the sequence. Within the block the item is available as the current item from the entire list.

Q. What is the structure of a while loop?

while : … The ellipsis represents a code block to be executed. until the condition becomes false. The condition is an expression that is considered true unless it evaluates to o, null or false.

Q. Use a for loop and illustrate how you would define and print the characters in a string out, one per line.

myString = "I Love Python"
for myChar hi myString:
    print(myChar)

Q. Given the string “I LoveQPython” use afor loop and illustrate printing each character tip to, but not including the Q.

inyString = "I Love Pijtlzon"
for myCizar in myString:    
    fmyC'har ==
    break
print(myChar)
Q. Given the string "I Love Python" print out each character except for the spaces, using a for loop.
inyString = I Love Python"
for myCizar in myString:
fmyChar == '' '':
continue
print myChar
Data Types

Q. What is a Tuple? Tuple Objects can be created by using parenthesis or by calling tuple function or by assigning multiple values to a single variable

  • Tuple objects are immutable objects
  • Incision order is preserved
  • Duplicate elements are allowed
  • Heterogeneous elements are allowed
  • Tuple supports both positive and negative indexing

The elements of the tuple can be mutable or immutable

    #Example:
    x=()
    print(x)
    print(type(x))
    print(len(x))
    y-tuple()
    print(y)
    print(type(y))
    print(len(y))
    z=10,20
    print(z)
    print(type(z))
    print(len(z))
    p=(10,20,30,40,50,10,20,10) Insertion & duplicate
    print(p)
    q=(100, 123.123, True, "mindmajix") Heterogeneous
    print(q)

Q. What is the Dictionary?

  • Dictionary objects can be created by using curly braces{} or by calling dictionary function.
  • Dictionary objects are mutable objects.
  • Dictionary represents key value base.
  • Each key value pair of Dictionary is known as a item.
  • Dictionary keys must be immutable.
  • Dictionary values can be mutable or immutable.
  • Duplicate keys are not allowed but values can be duplicate.
  • Insertion order is not preserved.
  • Heterogeneous keys and heterogeneous values are allowed.

Q. How to Search Path of Modules?

By default python interpreter search for the imported modules in the following locations:

  • Current directory (main module location)
  • Environment variable path
  • Installation dependent directory
  • If the imported module is not found in the any one of the above locations. Then python interpreter giveserror.

Built-in attributes of a module:

  • By default for each and every python module some properties are added internally and we call thoseproperties as a built-in-attribute of a module

Q. What are the Packages?

Package is nothing but a folder or dictionary which represents collection of modules.

A package can also contain sub packages.

We can import the modules of the package by using package name.module name or name.subpackage name.module name

Q. What is File Handling?

  • File is a named location on the disk, which stores the data in permanent manner.
  • Python language provides various functions and methods to provide the communication between python programs and files.
  • Python programs can open the file, perform the read or write operations on the file and close the file.
  • We can open the files by calling open function of built-in-modules.
  • At the time of opening the file, we have to specify the mode of the file.
  • Mode of the file indicates for what purpose the file is going to be opened(r,w,a,b).

Q. What are the Runtime Errors?

The errors which occurs after starting the execution of the programs are known as runtime errors. Runtime errors can occur because of:

  • Invalid Input
  • Invalid Logic
  • Memory issues
  • Hardware failures and so on

With respect to every reason which causes to runtime error correspoing runtime error representation class is available. Runtime error representation classes technically we call as a exception classes. While executing the program if any runtime error is occur corresponding runtime error representation class object is created Creating runtime error representation class object is technically known as a rising exception While executing the program if any exception is raised, then internally python interpreter verify any code is implemented to handle raised exception or not If code is not implemented to handle raised exception then program will be terminated abnormally

Q. What is Abnormal Termination?

The concept of terminating the program in the middle of its execution without executing last statement of the main module is known as a abnormal termination Abnormal termination is undesirable situation in programming languages.

Q. What is try Block?

A block which is preceded by the try keyword is known as a try block Syntax:

try{
//statements that may cause an exception
}

The statements which causes to run time errors and other statements which depends on the execution of run time errors statements are recommended to represent in try block While executing try block statement if any exception is raised then immediately try block identifies that exception, receive that exception and forward that exception to except block without executing remaining statements to try block.

Q. What is the Difference Between Methods & Constructors?

Methods

  • Method name can be any name.
  • With respect to one object one method can be called for ‘n’ members of lines
  • Methods are used to represent business logic to perform the operations

Constructor

  • Constructor will be executed automatically whenever we create a object.
  • With respect to one object one constructor can be executed only once
  • Constructors are used to define & initialize the non static variable

Q. What is the Encapsulation?

The concept of binding or grouping related data members along with its related functionalities is known as a Encapsulation.

Q. Executing DML Commands Through Python Programs?

DML (Data Modification Language) Commands are used to modify the data of the database objects Whenever we execute DML Commands the records are going to be modified temporarily.

Whenever we run “rollback” command the modified records will come back to its original state.

To modify the records of the database objects permanently we use “commit” command

After executing the commit command even though we execute “rollback” command, the modified records will not come back to its original state.

Create the emp1 table in the database by using following command

Create table emp1 as select * from emp;

Whenever we run the DML commands through the python program, then the no.of records which are modified because of that command will be stored into the rowcount attribute of cursor object. After executing the DML Command through the python program we have to call commit method of cursor object.

Multithreading

Q. What is Threads Life Cycle?

Threads Life Cycle

  • Creating the object of a class which is overwriting run method of thread class is known as a creating thread.
  • Whenever thread is created then we call thread is in new state or birth state thread. Whenever we call the start method on the new state threads then those threads will be forwarded for scheduling.
  • The threads which are forwarded for scheduling are known as ready state threads
  • Whenever scheduling time occurs, ready state thread starts execution.
  • The threads which are executing are known as running state threads Whenever sleep fun or join methods are called on the running state threads then immediately those threads will wait.
  • The threads which are waiting are known as waiting state threads Whenever waiting time is over or specified thread execution is over - then immediately waiting state threads are forwarded for scheduling.
  • If running state threads execution is over then immediately those threads execution will be terminated
  • The threads which execution is terminated are known as dead state threads.

Q. What is scheduling?

Among multiple threads:

which thread as to start the execution first, How much time the thread as to execute after allocated time is over, which thread as to continue the execution next this comes under scheduling. Scheduling is highly dynamic.

Q. for loop is implemented in python language as follows:

for element in iterable:
    iter-obj=iter(iterable)
    while true:
        try:
            element=next(iter_obj)
        except(slop iteration)
            break

For loop takes the given object, convert that object in the form of iterable object & gets the one by one element form the iterable object.

While getting the one by value element from the iterable object if stop iteration exception is raised then for loop internally handle that exception

Q. OS Module

OS Module is a predefined module and which provides various functions and methods to perform the operating system related activities, such as creating the files, removing the files, creating the directories removing the directories, executing the operating system related commands, etc. Example:

import os
cwd=os.getwd()
print("1", cwd)
os.chdir("samples")
print("2", os.getcwd())
os.chdir(os.pardir)
print("3",os.getcwd())

Q. What Are Applications of Python?

Applications of Python

  • Automation App
  • Data Analytics
  • Scientific App
  • Web App
  • Web Scrapping
  • Test Cases
  • Network with IOT
  • Admin Script
  • GUI
  • Gaming
  • Animation

Q. How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

Q. What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

Q. What is pass in Python?

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

Q. In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like list.

Q. In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

Q. What are generators in Python?

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable. We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.

    def squares(n):
        i=1
        while(i<=n):
            yield i**2
            i+=1
    for i in squares(7):
        print(i)
1
4
9
16
25
36
49

Q. So, what is an iterator, then?

An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function.

odds=iter([1,3,5])

Then, we call the next() function on it every time we want an object.

 next(odds)
1

 next(odds)
3

 next(odds)
5

And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on.

 next(odds)

Traceback (most recent call last):
File "<pyshell#295>", line 1, in <module> next(odds)
StopIteration

Q. Explain generators and iterators in python?

They do, but there are subtle differences:

  • For a generator, we create a function. For an iterator, we use in-built functions iter() and next().
  • For a generator, we use the keyword ‘yield’ to yield/return an object at a time.
  • A generator may have as many ‘yield’ statements as you want.
  • A generator will save the states of the local variables every time ‘yield’ will pause the loop.
  • An iterator does not use local variables; it only needs an iterable to iterate on.
  • Using a class, you can implement your own iterator, but not a generator.
  • Generators are fast, compact, and simpler.
  • Iterators are more memory-efficient.

Q. How can you copy an object in Python?

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

Q. How you can convert a number to a string?

In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

Q. What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

Q. Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

Q. How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

Q. Explain how can you make a Python Script executable on Unix?

To make a Python Script executable on Unix, you need to do two things,

Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)

Q. Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

Q. Explain how can you generate random numbers in Python?

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)

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

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

Module = =PyImport_ImportModule("");

Q. Mention the use of // operator in Python?

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.

Q. Mention five benefits of using Python?

  • 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 newvariables 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

Q. Mention the use of the split function in Python?

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.

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

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.

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? 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.

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

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

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

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.

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

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

Q. What is List Comprehensions feature of Python used for?

List comprehensions help to create and manage lists in a simpler and clearer way than using map(), filter() and lambda. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses.

Q. What are lambda expressions, list comprehensions and generator expressions?

Lambda expressions

are a shorthand technique for creating single line, anonymous functions. Their simple, inline nature often – though not always – leads to more readable and concise code than the alternative of formal function declarations. On the other hand, their terse inline nature, by definition, very much limits what they are capable of doing and their applicability. Being anonymous and inline, the only way to use the same lambda function in multiple locations in your code is to specify it redundantly.

List comprehensions

provide a concise syntax for creating lists. List comprehensions are commonly used to make lists where each element is the result of some operation(s) applied to each member of another sequence or iterable. They can also be used to create a subsequence of those elements whose members satisfy a certain condition. In Python, list comprehensions provide an alternative to using the built-in map() and filter() functions.

As the applied usage of lambda expressions and list comprehensions can overlap, opinions vary widely as to when and where to use one vs. the other. One point to bear in mind, though, is that a list comprehension executes somewhat faster than a comparable solution using map and lambda (some quick tests yielded a performance difference of roughly 10%). This is because calling a lambda function creates a new stack frame while the expression in the list comprehension is evaluated without doing so.

Generator expressions

are syntactically and functionally similar to list comprehensions but there are some fairly significant differences between the ways the two operate and, accordingly, when each should be used. In a nutshell, iterating over a generator expression or list comprehension will essentially do the same thing, but the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly as needed. Generator expressions can therefore be used for very large (and even infinite) sequences and their lazy (i.e., on demand) generation of values results in improved performance and lower memory usage. It is worth noting, though, that the standard Python list methods can be used on the result of a list comprehension, but not directly on that of a generator expression.

Q. Consider the two approaches below for initializing an array and the arrays that will result. How will the resulting arrays differ and why should you use one initialization approach vs. the other?

 # INITIALIZING AN ARRAY -- METHOD 1
...
 x = [[1,2,3,4]] * 3
 x
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]


 # INITIALIZING AN ARRAY -- METHOD 2
...
 y = [[1,2,3,4] for _ in range(3)]
 y
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

 # WHICH METHOD SHOULD YOU USE AND WHY?
Ans:

While both methods appear at first blush to produce the same result, there is an extremely significant difference between the two. Method 2 produces, as you would expect, an array of 3 elements, each of which is itself an independent 4-element array. In method 1, however, the members of the array all point to the same object. This can lead to what is most likely unanticipated and undesired behavior as shown below.

# MODIFYING THE x ARRAY FROM THE PRIOR CODE SNIPPET:
x[0][3] = 99
x
[[1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99]]

# UH-OH, DON'T THINK YOU WANTED THAT TO HAPPEN!
...
# MODIFYING THE y ARRAY FROM THE PRIOR CODE SNIPPET:
y[0][3] = 99
y
[[1, 2, 3, 99], [1, 2, 3, 4], [1, 2, 3, 4]]
# THAT'S MORE LIKE WHAT YOU EXPECTED!
...

Q. What will be printed out by the second append() statement below?

def append(list=[]):
    # append the length of a list to the list
    list.append(len(list))
    return list

append(['a','b'])
['a', 'b', 2]
append()  # calling with no arg uses default list value of [][0]

append()  # but what happens when we AGAIN call append with no arg?

When the default value for a function argument is an expression, the expression is evaluated only once, not every time the function is called. Thus, once the list argument has been initialized to an empty array, subsequent calls to append without any argument specified will continue to use the same array to which list was originally initialized. This will therefore yield the following, presumably unexpected, behavior:

append() # first call with no arg uses default list value of [][0]
append() # but then look what happens...[0, 1]
append() # successive calls keep extending the same default list!
[0, 1, 2]
append()  # and so on, and so on, and so on...
[0, 1, 2, 3]

Q. How might one modify the implementation of the append method in the previous question to avoid the undesirable behavior described there?

The following alternative implementation of the append method would be one of a number of ways to avoid the undesirable behavior described in the answer to the previous question:

def append(list=None):
    if list is None:
        list = []
        # append the length of a list to the list
        list.append(len(list))
        return list
append()
[0]
append()
[0]

Q: How can you swap the values of two variables with a single line of Python code?

Consider this simple example:

 x = 'X'
 y = 'Y'

In many other languages, swapping the values of x and y requires that you to do the following:

tmp = x
x = y
y = tmp
x, y
('Y', 'X')

But in Python, makes it possible to do the swap with a single line of code (thanks to implicit tuple packing and unpacking) as follows:

x,y = y,x
x,y
('Y', 'X')

Q. What will be printed out by the last statement below?

flist = []
for i in range(3):
    flist.append(lambda: i)

[f() for f in flist] # what will this print out?

In any closure in Python, variables are bound by name. Thus, the above line of code will print out the following: [2, 2, 2]

Presumably not what the author of the above code intended?

A workaround is to either create a separate function or to pass the args by name; e.g.

flist = []
for i in range(3):  
    flist.append(lambda i = i : i)

[f() for f in flist]
[0, 1, 2]

Q. Is Python interpreted or compiled?

As noted in Why Are There So Many Pythons?, this is, frankly, a bit of a trick question in that it is malformed. Python itself is nothing more than an interface definition (as is true with any language specification) of which there are multiple implementations. Accordingly, the question of whether “Python” is interpreted or compiled does not apply to the Python language itself; rather, it applies to each specific implementation of the Python specification.

Further complicating the answer to this question is the fact that, in the case of CPython (the most common Python implementation), the answer really is “sort of both”. Specifically, with CPython, code is first compiled and then interpreted. More precisely, it is not precompiled to native machine code, but rather to bytecode. While machine code is certainly faster, bytecode is more portable and secure. The bytecode is then interpreted in the case of CPython (or both interpreted and compiled to optimized machine code at runtime in the case of PyPy).

Q. What are some alternative implementations to CPython? When and why might you use them?

One of the more prominent alternative implementations is Jython, a Python implementation written in Java that utilizes the Java Virtual Machine (JVM). While CPython produces bytecode to run on the CPython VM, Jython produces Java bytecode to run on the JVM.

Another is IronPython, written in C# and targeting the .NET stack. IronPython runs on Microsoft’s Common Language Runtime (CLR).

As also pointed out in Why Are There So Many Pythons?, it is entirely possible to survive without ever touching a non-CPython implementation of Python, but there are advantages to be had from switching, most of which are dependent on your technology stack.

Another noteworthy alternative implementation is PyPy whose key features include:

  • Speed. Thanks to its Just-in-Time (JIT) compiler, Python programs often run faster on PyPy.
  • Memory usage. Large, memory-hungry Python programs might end up taking less space with PyPy than they do in CPython.
  • Compatibility. PyPy is highly compatible with existing python code. It supports cffi and can run popular Python libraries like Twisted and Django.
  • Sandboxing. PyPy provides the ability to run untrusted code in a fully secure way.
  • Stackless mode. PyPy comes by default with support for stackless mode, providing micro-threads for massive concurrency.

Q. What is unittest in Python? What’s your approach to unit testing in Python?

A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

The most fundamental answer to this question centers around Python’s unittest testing framework. Basically, if a candidate doesn’t mention unittest when answering this question, that should be a huge red flag.

unittest supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.

Assuming that the candidate does mention unittest (if they don’t, you may just want to end the interview right then and there!), you should also ask them to describe the key elements of the unittest framework; namely, test fixtures, test cases, test suites and test runners.

A more recent addition to the unittest framework is mock. mock allows you to replace parts of your system under test with mock objects and make assertions about how they are to be used. mock is now part of the Python standard library, available as unittest.mock in Python 3.3 onwards.

The value and power of mock are well explained in An Introduction to Mocking in Python. As noted therein, system calls are prime candidates for mocking: whether writing a script to eject a CD drive, a web server which removes antiquated cache files from /tmp, or a socket server which binds to a TCP port, these calls all feature undesired side-effects in the context of unit tests. Similarly, keeping your unit-tests efficient and performant means keeping as much “slow code” as possible out of the automated test runs, namely filesystem and network access.

[Note: This question is for Python developers who are also experienced in Java.]

Q. How would you perform unit-testing on your Python code?

Ans. For this purpose, we have the module unittest in Python. It has the following members:

  • FunctionTestCase
  • SkipTest
  • TestCase
  • TestLoader
  • TestResult
  • TestSuite
  • TextTestResult
  • TextTestRunner
  • defaultTestLoader
  • expectedFailure
  • findTestCases
  • getTestCaseNames
  • installHandler
  • main
  • makeSuite
  • registerResult
  • removeHandler
  • removeResult
  • skip
  • skipIf
  • skipUnless Below are some Advanced Python Programming Interview Questions For Experienced. I recommend freshers to also refer these interview questions for advanced knowledge.

Q. How do I test a Python program or component?

Python comes with two testing frameworks:

The documentation test module finds examples in the documentation strings for a module and runs them, comparing the output with the expected output given in the documentation string.

The unittest moduleis a fancier testing framework modeled on Java and Smalltalk testing frameworks.

For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods. And this sometimes has the surprising and delightful effect of making the program run faster because local variable accesses are faster than global accesses.

Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.

The “global main logic” of your program may be as simple as:

if name=="main":
main_logic()

at the bottom of the main module of your program. Once your program is organized as a tractable collection of functions and class behaviors, you should write test functions that exercise the behaviors.

A test suite can be associated with each module which automates a sequence of tests.

You can make coding much more pleasant by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.

“Support modules” that are not intended to be the main module of a program may include a self-test of the module.

if name == "main":
self_test()

Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.

FLASK

Q. What is Flask & its benefits?

Python Flask, as we’ve previously discussed, is a web microframework for Python. It is based on the ‘Werkzeug, Jinja 2 and good intentions’ BSD license. Two of its dependencies are Werkzeug and Jinja2. This means that it has around no dependencies on external libraries. Due to this, we can call it a light framework. A session uses a signed cookie to allow the user to look at and modify session contents. It will remember information from one request to another. However, to modify a session, the user must have the secret key Flask.secret_key.

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.

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

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

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

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

Q. Explain how you can access sessions in Flask?

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.

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

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 your model or main part will be

app.run(debug = True)

Q. Explain database connection in Python Flask?

Best database for flask is MySQL. 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.

Q. How will you sort result of student whose marks are unknown to you based on their roll numbers?

Using bubble sort.

Q. How will you check memory leak on Linux?

valgrind along with gcc.