Quantcast
Viewing latest article 8
Browse Latest Browse All 26

MUST Have Python Interview Questions

Here we are starting with a MUST Have Python Interview Questions with detailed answers explaining the concepts with the help of examples and source code. We will start with beginner level basic concepts and further take to  intermediate and advanced topics throughout this Python Interview Questions and Answers Series.
Image may be NSFW.
Clik here to view.
Python Interview Questions

Let’s Move on with Python Interview Questions and Answers

Below is the list of MUST Know Python Interview Questions with detailed answers:

Quick and Easy way to grasp Web, Database, Web Scrapping, Data Science, Web Visualization, Image Processing & More…
  • A Name Generator
  • A Website URL Timed Blocker
  • A Web Map Generator
  • A Portfolio Website with Flask
  • A GUI based desktop Application
  • A Webcam Motion detector
  • A Web Scraper of Property
  • An Interactive web-based Financial Chart
  • A Data Collector Web Application
  • A Geo Coding Web Service

Learn More Now…Click Here

How to Install Python and Prepare Environment?

Python increasingly becoming one of the most popular programming language among developers, especially for Machine Learning and research purpose. This is very easy and straight forward to learn python. The first step of getting started with python, is to install it. In this section we would describe the Installation Process for python in different environment.

How to Install Python:

WINDOWS:

  • Open the download page link on a browser.
    Image may be NSFW.
    Clik here to view.
    Installing Python on Windows
  • Download the installer package for Windows
    Image may be NSFW.
    Clik here to view.
    Python Installer Package for Windows
    Once the download is complete, execute the installer and once the installation s complete, open a terminal and run the following command.
    python -V
  • This will provide the following details.Image may be NSFW.
    Clik here to view.
    Python Interview Questions

MAC:

  • Open the download page link on a browser.
    Image may be NSFW.
    Clik here to view.
    Python Installer Package for Mac
  • Download the installer package for Mac OS X
    Image may be NSFW.
    Clik here to view.
    Python Releases for Mac OS X
  • Once the download is complete, execute the installer and once the installation is complete, open a terminal and run the following command to check if the installation is correct, which will print the version of installed python.
    python -V

LINUX:

  • Python is by default installed.
  • To check if the python is available, open a terminal and run the following command to check if the installation is correct , which will print the version of installed python.
    python -V

Back to top

What are the Key Features/Benefits of using Python?

There are several flexibility and uniqueness in Python that is contributing in order to make this language as one of the most promising language in the world:

  • The community is very large, therefore, there are lots of tutorial and learning material available
  • Easy to learn
  • Comparatively less code is required than any other language
  • Simple and straight forward
  • Machine learning and deep learning community as well as research work are using python extensively.

Benefits using Python:

One of the main argument in favor of python from python developer is that it as for being a dynamic-typed language needs no variable declaration, no explicit type conversion. As a result the same functionality can be implemented in fewer line of code than any other language. Development is quicker in python for this reason.

Python is excellent language for functional programming. Functions are like object, therefore, it is possible to assign them to any other class object or even return from another function as well as can be passed as parameter to other function.

For automation, Python is very popular.

Python is still number one language for big data analytics. Even though R has been designed specifically for data analytics however Python is still number one choice among data scientist for its simplicity and powerful computation tool.

The huge community and lots of opensource tools is another reason for growing popularity of python.

Back to top

How does the Ternary Operator work in Python? Explain with the help of a Real-Time example?

One of the most important as well as interesting feature of python is ternary operator. These are conditional expression in Python.

What is Ternary Operator?

These operators are used to evaluate any expression and provide output as either true or false. Some feature of ternary operator are as following:

  • It takes 3 arguments
    [<comparison expression> <result for true statement> <result for false statement>]
  • Example
    $result = ($x==1) ? true: false;
    So If x=1, $result = true otherwise $result = false.
  • This is a common concept across different programming languages. For example,  in Java this is the similar keyword as self.

How does the Ternary Operator work in Python?

In the following example, True and False can be used as the index of the dictionary as True =1 and False = 0.Image may be NSFW.
Clik here to view.
Python Questions

Therefore, True and False can be used as Boolean variable as well. As in the following example:Image may be NSFW.
Clik here to view.
Python Ternary Example

This is the beauty of Python, based on the context the variable can be used as different type.

The if-else block can be defined as following:Image may be NSFW.
Clik here to view.
Python Ternary Example Question

This is the magic of Python.

Back to top

What does the “self” keyword do?

The “self” keyword is a variable that refer to an instance of an object. When a class is created there is not explicit reference of the object of that class type, therefore in python in order to refer the current class or current object, self is used as a reference.

class User:
    def __init__(self):
        self.name = 'Muhammad Ahmad’
        self.age = 16
 
user_obj = User()
user_obj.name    # self.name holds 'Muhammad Ahmad' as value

Back to top

Define the following Items in Python?

Iterator:

Iterator are used for iterating through array:

for k in {"a": 1, "b": 2}:
    print (k)

Function:

Function is very interesting and can be used in so many different ways in python.

Creating a Function: 

The definition of function starts with the keyword “def” and followed by the name of the fucntion and finally it returns a result. In the following example, the name of the function is “square_of_first_ten_number” and it returns the square of 1 to 10.

def square_of_first_ten_number(n):
   return [x**2 for x in range(10)]

This function then can be used in any code segment of the complete program.

Pdb:

Pdb is the debugging module for python, here are some pdb commands for  debugging Python code.

  • To add breakpoint : <b>
  • To resume execution : <c>
  • To go through line by line debugging : <s>
  • To go to next line : <n>
  • To list source code : <l>
  • To print an expression : <p>

Generator:

  • A function that returns inerrable object
  • Used to control iterative behavior of a loop
  • it contains yield expression in the function definition, using yield expression it can iterate, however this can be done only once as the object is not persisted in memory
  • loop can be replaced with generators for efficient iteration over large dataset
    def  customgen(n):
        x = 0
        while x < n:
            x = x + 1
            if x % 4== 0:
                yield x
    
    for i in customgetn(100):
        print i
    The generator in the above example that iterates from 0 to n, and it yields the variable if the loop variable is a multiple of 4.

Lambda:

This is a normal method in python

def square(x):
   return x * 2

This method can be represented as a lambda

square = lambda x: x * 2

lambda can have e a number of arguments but execute a single expression.

Map:

  • Map accepts a function and a list
  • Map is equivalent to for loop
  • However for each iteration, it perform the passed function on each item of the list
  • It returns a list
    list = [1, 2, 3, 4, 5]
    def cube(x): return x ** 3
    list(map(cube, items))
    >>>>[1, 8, 27, 64, 125]

Filter:

  • Accepts a condition and a list
  • Iterate through the list and compute for each item if the condition is true or false
  • Return a subset of given list that matches the condition
list( filter((lambda x: x > 0), range(-5,5)))
>>>>>[1,2,3,4,5]
Reduce:
  • Accepts a function and a list
  • Iterate through the list and compute for each item and perform the operation specified by the function and aggregate the result
reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
Static Method:

Static method are method from any python class those can be called from any part of the program without creating a object of the associated class.  From Python 3.6 there is a decorator to define any method as static method and later they can be classed just using the class name such as:

class Fruit(object)
	@staticmethod
	def generaldescription(x):
		print ("This is a static method of Fruit class with argument", x)

Fruit.generaldescription(2) # call static method from Fruit class

The output would be:Image may be NSFW.
Clik here to view.
Static method Output in Python

They can be also called on an object of the class, such as:

class Fruit(object)
	@staticmethod
	def generaldescription(x):
		print ("Fruit class with static method having argument", x)

Fruit().generaldescription(3) # call static method from Fruit class

The output would be as following:Image may be NSFW.
Clik here to view.
Python Static Function Interview Questions

Back to top

Continue with More Advanced Python Interview Questions and Answers

What is Threading? Explain how multi-threading can be implemented in Python? Give an example of multi-threading using Python?

A thread is a small unit of program that can be scheduled in OS. Usually a program is forked to more than one parallel task and scheduled in OS for the execution of thread. Each process has at least one thread, however it can have more than one thread.

There are two specific kind of thread, such as

  • User- specific
  • kernel

How to Create a Thread in Python?

There are 2 module in python, such as

  1. thread
  2. threading

Using Threading Module:

from threading import Thread

t1 = Thread(target=execute, args=("Thread-1", 1, 5))
t1.start()

Here, target argument in Thread() is a callable function and  args are the argument for the callable function

def execute (name, delay, repeat):
    print("Thread: " + name + " Started")

    while repeat > 0:
        time.sleep(delay)
        print
        name + ": " + str(time.ctime(time.time()))
        repeat -= 1
    print("Thread: " + name + " Completed")

Some Features of Threading in Python:

Image may be NSFW.
Clik here to view.
Multithreading in Python

  • Thread share data and code with main thread
  • Multiple thread can co-exists in the same process and can communicate with each other
  • Multiple thread can execute code faster as they can run concurrently
  • For a single process each thread of its share the global data, therefore it need proper data-lock mechanism while multiple thread is manipulating the same data.

Example of Multi-threading using Python:

Here is an example, when Thread-1 is acquire a lock on particular interval and Thread-2 keep trying to acquire the lock, it can only acquire the lock when the lock has been released by Thread-1.

from threading import Thread
import threading
import time

data=0

def timer(name, delay, repeat, lock):
    print("Timer: " + name + " Started")
    global data
    while repeat > 0:
        time.sleep(delay)
        if(name == 'Thread-1'):
            while True:
                lock.acquire()
                try:
                    print('Locking')
                    time.sleep(1.0)
                finally:
                    print('Releasing Lock')
                    lock.release()
                    time.sleep(1.0)
        if(name == 'Thread-2'):
            num_tries = 0
            num_acquires = 0
            while num_acquires < 3:
                time.sleep(0.5)
                print('Trying to acquire')
                acquired = lock.acquire(0)
                try:
                    num_tries += 1
                    if acquired:
                        print('Try',num_tries, ': Acquired' )
                        num_acquires += 1
                    else:
                        print('Try ',num_tries, ': Not acquired')
                finally:
                    if acquired:
                        lock.release()
            print('Done after',num_tries,' tries' )
        print(name + ": " + str(time.ctime(time.time()))+":",data)

        repeat -= 1
    print("Thread: " + name + " Completed")



def main():
    lock = threading.Lock()
    t1 = Thread(target=timer, args=("Thread-1", 1, 2,lock))
    t2 = Thread(target=timer, args=("Thread-2", 2, 2, lock))
    t1.start()
    t2.start()

    print("Main proogram complete")



if __name__ == '__main__':
   main()

The output would be as following:

Timer: Thread-1 Started
Timer: Thread-2 Started
Main proogram complete
Locking
Releasing Lock
Trying to acquire
Try 1 : Acquired
Locking
Trying to acquire
Try  2 : Not acquired
Trying to acquire
Try  3 : Not acquired
Trying to acquire
Releasing Lock
Try  4 : Not acquired
Trying to acquire
Try 5 : Acquired
Locking
Trying to acquire
Try  6 : Not acquired
Trying to acquire
Try  7 : Not acquired
Releasing Lock
Trying to acquire
Try 8 : Acquired
Done after 8  tries
Thread-2: Sun Jun 25 22:53:53 2017: 0
Locking
Releasing Lock
Trying to acquire
Try 1 : Acquired
Locking
Trying to acquire
Try  2 : Not acquired
Trying to acquire
Try  3 : Not acquired
Releasing Lock
Trying to acquire
Try 4 : Acquired
Trying to acquire
Try 5 : Acquired
Done after 5  tries

  • Thread-2: Sun Jun 25 22:53:57 2017: 0
    Thread: Thread-2 Completed
  • Thread can be interrupted or can totally put into sleep for certain time.
  • Each data can have its own local data and local code
  • Thread run in the same process of the main program, it can run concurrently with main thread, so it is used for quick task or background task.

In the following example, two separate thread is performing two different operation on the same global data:

from threading import Thread
import time

data=0

def timer(name, delay, repeat):
    print("Timer: " + name + " Started")
    global data
    while repeat > 0:
        time.sleep(delay)
        if(name == 'Thread-1'):
            data= data+5
        if(name == 'Thread-2'):
            data = data*5
        print(name + ": " + str(time.ctime(time.time()))+":",data)

        repeat -= 1
    print("Thread: " + name + " Completed")



def main():
    t1 = Thread(target=timer, args=("Thread-1", 1, 5))
    t2 = Thread(target=timer, args=("Thread-2", 2, 5))
    t1.start()
    t2.start()

    print("Main proogram complete")



if __name__ == '__main__':
   main()

The output would be as following

Timer: Thread-1 Started
Timer: Thread-2 Started
Main proogram complete
Thread-1: Sun Jun 25 22:39:59 2017: 5
Thread-2: Sun Jun 25 22:40:00 2017: 25
Thread-1: Sun Jun 25 22:40:00 2017: 30
Thread-1: Sun Jun 25 22:40:01 2017: 35
Thread-2: Sun Jun 25 22:40:02 2017: 175
Thread-1: Sun Jun 25 22:40:02 2017: 180
Thread-1: Sun Jun 25 22:40:03 2017: 185
Thread: Thread-1 Completed
Thread-2: Sun Jun 25 22:40:04 2017: 925
Thread-2: Sun Jun 25 22:40:06 2017: 4625
Thread-2: Sun Jun 25 22:40:08 2017: 23125
Thread: Thread-2 Completed

Back to top

What is __init__.py? How to import class from different directory?

__init__.py is mainly used to initialize Python packages.Image may be NSFW.
Clik here to view.
Initialize Python Packages

the __init__.py file in a lstm_m directory indicates to the Python interpreter that this directory is to be treated like a Python package.

How to Import Class from different Directory?

Usually  __init__.py  is an empty file. Now if we want to use lstm.py in run.py file we simple need to import it as following:

Image may be NSFW.
Clik here to view.
Import Class in Python

And also there must be a __init__.py  inside the module folder that is intended to be imported.

Back to top

Image may be NSFW.
Clik here to view.
Python Certification Training

Explain different ways of Reading and Writing files in Python?

The most popular reason for using Python in order to process file, is that it supports streaming. For example, in order to read huge data set for big data analytics and process the file.

Usercase 1: Read all txt files in a directory

The yield command enables a function to comeback where it left off when it is called again. It took only 4 line to execute this processing.

for root, directories, files in os.walk(given_directory):
        for file in filter(lambda file: file.endswith('.txt'), files):
            # read each document as one big string
            document = open(os.path.join(root, file)).read()
            # returns a generator
            yield document

Usercase 2: Read a huge file using generator

def get_line():
     with open('filename') as file:
         for i in file:
             yield i

lines_required = 100
gen = get_line()
chunk = [next(gen) for i in range(lines_required)]

Back to top

How do we debug a Program in Python? Is it possible to step through Python code?

There is a built-in model ‘pdb’ which provide a interactive python debugger.

python -m pdb mypyscript.py

Run pdb from  interpreter

>>> import pdb_script
>>> import pdb
>>> pdb.run('pdb_script.MyPyObj(6).go()')
> <string>(1)<module>()
(Pdb)

From python script file

import pdb

class MyObj(object):
    count = 5
    def __init__(self):
        self.count= 9

    def go(self):
        for i in range(self.count):
            pdb.set_trace()
            print i
        return

if __name__ == '__main__':
    MyObj(5).go()

Back to top

Describe Python’s Garbage Collection Mechanism?

Garbage Collector:

As like Java, python also has its own built-in garbage collector, it release memory when any memory taken by any object is no longer is being used.  Now when garbage collector know the memory is not being used. Garbage collector use reference counter of object, if the reference counter of any object is 0, it is called dead object and it is ready to be cleared by GC.  However, this mechanism is called as referencing counting.  Referencing counting is easy to implement, however, it is not thread safe. If a object has been referenced so many times that is also stored in memory, therefore, for a single object it need to store name, reference counter and value which needs memory.Image may be NSFW.
Clik here to view.
Python Interview Questions

Another algorithm used by python to manage garbage collection is Mark and Sweep Tracing.

Cyclic Reference:

When two object reference each other. The reference cant not be deleted.  This situation is known as cyclical reference. Under this situation the reference counter for both x and y is ot 0, therefore even if they are not being used, however, it is not collected by garbage as both of them are unreachable.Image may be NSFW.
Clik here to view.
Cyclic Reference in Python

Mark and Sweep Tracing:

Any garbage collection algorithm must perform 2 basic operations. One, it should be able to detect all the unreachable objects and secondly, it must reclaim the heap space used by the garbage objects and make the space available again to the program.

The above operations are performed by Mark and Sweep Algorithm in two phases:

1) Mark phase

2) Sweep phase

Mark

This mechanism follows a depth first search to search each object and check its mark bit, which is assigned to 0 at the time creation, if that object is reachable from current object, that is marked as 1, otherwise the mark bit remains 0.

Sweep

So all the objects whose mark bit is still 0 are considered as unreachable object. And this mechanism clear off all the unreachable objects and thereby clears the heap memory. Now the mark value for all the reachable objects is reset to false for further garbage detection.

Back to top

The course is designed to cover web, database, data science, web scrapping, image processing, web visualization and much more.

Followings are few highlight about this Python Online Course:

  • Best Seller Udemy Online Course
  • 40,016++ students enrolled
  • 6,251 Review available
  • 23 Hours on-demand videos
  • 28 Articles
  • 36 Supplemental Resource
  • Access on Mobile and TV
  • Certificate of Completion
  • Lifetime Access
  • 30 days Money back guarantee
  • You can get the course at Discounted Price here.

Most attractive feature is 30 days Money Back Guarantee means there is NO RISK. If you didn’t like this Python Online Course, you can refund your money back within 30 days of purchase.

Image may be NSFW.
Clik here to view.
Take-This-Course

This was first part in Python Language Interview Questions and details answers.  We will explore more advanced concepts in following parts. Keep in touch.
Image may be NSFW.
Clik here to view.
Step forward in 2017: Build in-demand career skills with Coursera

More Python and Related:

The post MUST Have Python Interview Questions appeared first on Web Development Tutorial.


Viewing latest article 8
Browse Latest Browse All 26

Trending Articles