Python Interview

Python Interview



Indoscie Technologies is Web Design and Development, SEO, PPC, Local Listing, Adwords, E-mail Marketing, Digital Marketing service and solutions providers at a very affordable cost.


Python Interview


 

This page will guide you on how to crack any python programming interview, including:

 

1. Real-World Python interview questions asked in companies like Microsoft, Google, Amazon and how to answer them (saving your interview preparation time).

 

2. Python practice problems which you can solve right away.

 

Let’s get started!

1. What is Python?

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads,
exception-handling and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

 

2. What are the benefits of using Python?

Python is a general-purpose programming language that has simple, easy-to-learn syntax which emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, completely open-source and supports third-party packages encouraging modularity and code-reuse.

Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and
deployment.

 

3. What is a dynamically typed language?

Before we understand what a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed  language, such as Python, "1" + 2 will result in a type error, since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed  language, such as Javascript, will simply output "12" as result.

 

Type-checking can be done at two stages -

 

Static - Data Types are checked before execution.

Dynamic - Data Types are checked during
execution.

Python being an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed language.

 

4. What is an Interpreted language?

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

 

5. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing
information to the Python Community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing in the Python open-source community requires you to follow these style guidelines sincerely and strictly.

 

 

6. How is memory managed in Python?

Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated for Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions
to work upon the private heap space.

Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

 

 

7. What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

 

Local Namespace includes local names inside a function. the namespace is
temporarily created for a function call and gets cleared when the function returns.

Global Namespace includes names from various imported packages/ modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.

Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

Lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer
namespace.

 

8. What is Scope in Python?

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

 

A local scope refers to the local objects available in the current function.

A global scope refers to the objects available throught the code execution since their inception.

A module-level scope refers to the global objects of
the current module accessible in the program.

An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Note: Local scope objects can be synced with global scope objects using keywords such as global.

9. What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behaviour are:

 

Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To
resolve this amiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp().

Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables treating both their namespaces as separate identities.

temp = 10   # global-scope variable

 

def func():

     temp = 20   # local-scope variable

     print(temp)

 

print(temp)   # output => 10

func()
   # output => 20

print(temp)   # output => 10

This behaviour can be overriden using the global keyword inside the function, as shown in the following example:

 

temp = 10   # global-scope variable

 

def func():

     global temp

     temp = 20   # local-scope variable

     print(temp)

 

print(temp)   # output => 10

func()    # output => 20

print(temp)   # output => 20

10. What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing
function in Python without changing the structure of the function itself. They are represented by the @decorator_name in Python and are called in bottom-up fashion. For example:

 

# decorator function to convert to lowercase

def lowercase_decorator(function):

   def wrapper():

       func = function()

       string_lowercase = func.lower()

       return string_lowercase

   return wrapper

 

# decorator function to split words

def splitter_decorator(function):

   def wrapper():

       func =
function()

       string_split = func.split()

       return string_split

   return wrapper

 

@splitter_decorator # this is executed next

@lowercase_decorator # this is executed first

def hello():

   return 'Hello World'

 

hello()   # output => [ 'hello' , 'world' ]

The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function,
plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

 

# decorator function to capitalize names

def names_decorator(function):

   def wrapper(arg1, arg2):

       arg1 = arg1.capitalize()

       arg2 = arg2.capitalize()

       string_hello = function(arg1, arg2)

       return string_hello

   return wrapper

 

@names_decorator

def say_hello(name1, name2):

   return 'Hello ' + name1 + '! Hello ' + name2 +
'!'

 

say_hello('sara', 'ansh')   # output => 'Hello Sara! Hello Ansh!'

11. What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).

But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or
sliced on-the-go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:

 

my_tuple = ('sara', 6, 5, 0.97)

my_list = ['sara', 6, 5, 0.97]

 

print(my_tuple[0])     # output => 'sara'

print(my_list[0])     # output => 'sara'

 

my_tuple[0] = 'ansh'    # modifying tuple => throws an error

my_list[0] = 'ansh'    # modifying list => list modified

 

print(my_tuple[0])     # output => 'sara'

print(my_list[0])     # output => 'ansh'

12. What
are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries or sets from a given list, dictionary or set. Using comprehensions, saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial:

 

Performing mathematical operations on the entire list

my_list = [2, 3, 5, 7, 11]

 

squared_list = [x**2 for x in my_list]    # list comprehension

# output => [4 , 9 , 25 , 49 , 121]

 

squared_dict = {x:x**2
for x in my_list}    # dict comprehension

# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Performing conditional filtering operations on the entire list

my_list = [2, 3, 5, 7, 11]

 

squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension

# output => [9 , 25 , 49 , 121]

 

squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension

# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one

Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.

a = [1, 2, 3]

b = [7,
8, 9]

 

[(x + y) for (x,y) in zip(a,b)]  # parallel iterators

# output => [8, 10, 12]

 

[(x,y) for x in a for y in b]    # nested iterators

# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]

Flattening a multi-dimensional list

A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.

my_list = [[10,20,30],[40,50,60],[70,80,90]]

 

flattened = [x for temp in my_list for x in temp]

# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

Note: List comprehensions have the same
effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python.

 

13. What are the common built-in data types in Python?

There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations but type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following catetgories-

 

None Type

None keyword
represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.

Class Name Description

NoneType Represents the NULL values in Python

 

Numeric Types

There are three distint numeric types - integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.

Class Name Description

int Stores integer literals including hex, octal and binary numbers as integers

float Stores literals containing decimal values and/or exponent sign as floating-point numbers

complex Stores complex number in the form (A + Bj) and has attributes: real and imag

bool
Stores boolean value (True or False)

Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.

 

Sequence Types

According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.

Class Name Description

list Mutable sequence used to store collection of items.

tuple Immutable sequence used to store collection of items.

range Represents an immutable sequence of
numbers generated during execution.

str Immutable sequence of Unicode code points to store textual data.

Note: The standard library also includes additional types for processing:

1. Binary data such as bytearray bytes memoryview , and

2. Text strings such as str .

 

Mapping Types

A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.

Class Name Description

dict Stores comma-separated list of key: value pairs

 

Set Types

Currently, Python has two built-in set types - set and frozenset. set type is
mutable and supports methods like add() and remove(). frozenset type is immutable and can't be modified after creation.

Class Name Description

set Mutable unordered collection of distinct hashable objects

frozenset Immutable collection of distinct hashable objects

Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set.

 

Modules

Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and
myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended.

 

Callable Types

Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes.

Refer the documentation at docs.python.org for a detailed view into the callable types.

 

14. What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python, that can accept any number of arguments,
but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

 

Assigning lambda functions to a variable

mul = lambda a, b : a * b

print(mul(2, 5))    # output => 10

Wrapping lambda functions inside another function

def myWrapper(n):

 return lambda a : a * n

 

mulFive = myWrapper(5)

print(mulFive(2))    # output => 10

15. What is pass in Python?

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty
blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

 

def myEmptyFunc():

   # do nothing

   pass

 

myEmptyFunc()    # nothing happens

 

## Without the pass keyword

# File "<stdin>", line 3

# IndentationError: expected an indented block

16. How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies
of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module -

 

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values are references to other objects, just the reference addresses for the same are copied.

Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

from copy import copy, deepcopy

 

list_1 = [1, 2, [3, 5], 4]

 

## shallow copy

 

list_2 =
copy(list_1)  

list_2[3] = 7

list_2[2].append(6)

 

list_2    # output => [1, 2, [3, 5, 6], 7]

list_1    # output => [1, 2, [3, 5, 6], 4]

 

## deep copy

 

list_3 = deepcopy(list_1)

list_3[3] = 8

list_3[2].append(7)

 

list_3    # output => [1, 2, [3, 5, 6, 7], 8]

list_1    # output => [1, 2, [3, 5, 6], 4]

17. What is the difference between xrange and range in Python?

xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a
Python list, whereas, xrange() returns an xrange object.

 

So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object type generators and has been termed as "yielding".

 

Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).

 

for i in xrange(10):    # numbers from o to 9

 
 print i       # output => 0 1 2 3 4 5 6 7 8 9

 

for i in xrange(1,10):    # numbers from 1 to 9

   print i       # output => 1 2 3 4 5 6 7 8 9

 

for i in xrange(1, 10, 2):    # skip by two for next

   print i       # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.

18. What are modules and packages in Python?

Python packages and Python modules are two
mechanisms that allow for modular programming in Python. Modularizing ahs several advantages -

 

Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.

Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.

Reusability: Functions defined in a module can be easily reused by other parts of the application.

Scoping: Modules typically define a separate
namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

 

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similary manner, packages help avoid clashes between module names.

Creating a package is easy since it
makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

 

Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.

19. What are global, protected and private attributes in Python?

Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global
keyword.

Protected attributes are attributes defined with a underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.

Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

20. What is self in Python?

Self is a keyword in Python used to define an instance or an object of a class. In Python, it is explicity used as the first paramter, unlike in Java where it is optional.
It helps in disinguishing between the methods and attributes of a class from its local variables.

 

21. What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

 

# class definition

class Student:

   def __init__(self, fname, lname, age, section):

       self.firstname = fname

       self.lastname = lname

       self.age =
age

       self.section = section

 

# creating a new object

stu1 = Student("Sara", "Ansh", 22, "A2")

22. What is break, continue and pass in Python?

Break The break statement terminates the loop immediately

and the control flows to the statement after the body of the loop.

Continue The continue statement terminates the current iteration of the statement,

skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.

Pass As explained above, pass keyword in Python is generally used to fill-up empty blocks

and is similar to an empty statement represented by a
semi-colon in languages such as Java, C++, Javascript etc.

 

pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]

 

for p in pat:

   pass

   if (p == 0):

       current = p

       break

   elif (p % 2 == 0):

       continue

   print(p)    # output => 1 3 1 3 1

 

print(current)    # output => 0

23. What is pickling and unpickling?

Python library offers a feature - serialization out of the box. Serializing a object refers to transforming it into a format that can be stored, so as to
be able to deserialize it later on, to obtain the original object. Here, the pickle module comes into play.

 

Pickling

Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions.

The function used for the above process is pickle.dump().

 

Unpickling

Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects
stored in the file, and loads the object to memory.

The function used for the above process is pickle.load().

 

Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from pickle.

 

24. What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

Let's try and build a generator for fibonacci numbers -

 

## generate fibonacci numbers upto n

def fib(n):

   p, q = 0, 1

   while(p < n):

       yield p

       p, q = q, p + q

 

x = fib(10)    # create generator object
 

 

## iterating using __next__(), for Python2, use next()

x.__next__()    # output => 0

x.__next__()    # output => 1

x.__next__()    # output => 1

x.__next__()    # output => 2

x.__next__()    # output => 3

x.__next__()    # output => 5

x.__next__()    # output => 8

x.__next__()    # error

 

## iterating using loop

for i in fib(10):

   print(i)    # output => 0 1 1 2 3 5 8

25. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can
set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

 

26. What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.

dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant
data, rather than the complete information.

 

For Modules/Library objects, it returns a list of all attributes, contained in that module.

For Class Objects, it returns a list of all valid attributes and base attributes.

With no arguments passed, it returns a list of attributes in the current scope.

27. What is the difference between .py and .pyc files?

.py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

Before executing a
python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.

Having .pyc file saves you the compilation time.

28. How Python is interpreted?

Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.

Source code is a file with .py extension.

Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is
an implementation of that virtual machine. This intermediate format is called “bytecode”.

.py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by official CPython, or JIT(Just in Time compiler) compiled by PyPy.

29. What are unittests in Python?

unittest is a unit testing framework of Python.

Unit testing means testing different components of software separately. Can you think why unit testing is important? Imagine a scenario, you are building software which uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for
breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.

This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

30. What is docstring in Python?

Documentation string or docstring is a multiline string used to document a specific code segment.

The docstring should describe what the function or method does.

31. How are arguments passed by value or by reference in python?

Pass by value: Copy of the actual object is passed. Changing the value
of the copy of the object will not change the value of the original object.

Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.

In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

 

def appendNumber(arr):

   arr.append(4)

 

arr = [1, 2, 3]

 

print(arr)  #Output: => [1, 2, 3]

appendNumber(arr)

print(arr)  #Output: => [1, 2, 3, 4]

32. What are iterators in Python?

Iterator is an object.

It remembers its state i.e., where it is during
iteration (see code below to see how)

__iter__() method initializes an iterator.

It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.

It is also self iterable.

Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

class ArrayList:

   def __init__(self, number_list):

       self.numbers = number_list

 

   def __iter__(self):

       self.pos = 0

       return
self

 

   def __next__(self):

       if(self.pos < len(self.numbers)):

           self.pos += 1

           return self.numbers[self.pos - 1]

       else:

           raise StopIteration

 

array_obj = ArrayList([1, 2, 3])

 

it = iter(array_obj)

 

print(next(it)) #output: 2

print(next(it)) #output: 3

 

print(next(it))

#Throws Exception

#Traceback (most recent call last):

#...

#StopIteration

33. What is
slicing in Python?

As the name suggests, ‘slicing’ is taking parts of.

Syntax for slicing is [start : stop : step]

start is the starting index from where to slice a list or tuple

stop is the ending index or where to sop.

step is the number of steps to jump.

Default value for start is 0, stop is number of items, step is 1.

Slicing can be done on strings, arrays, lists, and tuples.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(numbers[1 : : 2])  #output : [2, 4, 6, 8, 10]

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

Script file must begin with #!/usr/bin/env python

35. Explain how to
delete a file in Python?

Use command os.remove(file_name)

import os

os.remove("ChangedFile.csv")

print("File Removed!")

36. Explain split() and join() functions in Python?

You can use split() function to split a string based on a delimiter to a list of strings.

You can use join() function to join a list of strings based on a delimiter to give a single string.

string = "This is a string."

string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘

print(string_list) #output: ['This', 'is', 'a', 'string.']

print(' '.join(string_list)) #output: This is a string.

37. What is the difference
between Python Arrays and lists?

Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.

Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

import array

 

a = array.array('i', [1, 2, 3])

 

for i in a:

    print(i, end=' ')    #OUTPUT: 1 2 3

 

a = array.array('i', [1, 2, 'string'])    #OUTPUT: TypeError: an integer is required (got type
str)

 

a = [1, 2, 'string']

 

for i in a:

   print(i, end=' ')    #OUTPUT: 1 2 string

38. What does *args and **kwargs mean?

*args

 

*args is a special syntax used in function definition to pass variable-length argument.

“*” means variable length and “args” is the name used by convention. You can use any other.

def multiply(a, b, *argv):

   mul = a * b

 

   for num in argv:

       mul *= num

 

   return mul

 

print(multiply(1, 2, 3, 4, 5)) #output:
120

**kwargs

 

**kwargs is a special syntax used in function definition to pass variable-length keyworded argument.

Here, also, “kwargs” is used just by convention. You can use any other name.

Keyworded argument means a variable which has a name when passed to a function.

It is actually a dictionary of variable name and its value.

def tellArguments(**kwargs):

   for key, value in kwargs.items():

       print(key + ": " + value)

tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")

#output:

# arg1: argument 1

# arg2: argument 2

# arg3:
argument 3

39. What are negative indexes and why are they used?

Negative indexes are the indexes from the end of the list or tuple or string.

Arr[-1] means last element of array Arr[]

arr = [1, 2, 3, 4, 5, 6]

 

#get the last element

print(arr[-1]) #output 6

 

#get the second last element

print(arr[-2]) #output 5

 

source: https://www.interviewbit.com/python-interview-questions/

 

################################# PYTHON ##################################

100 Data Science in Python Interview Questions and Answers for 2018

30 Dec 2015

Python’s growing adoption in
data science has pitched it as a competitor to R programming language. With its various libraries maturing over time to suit all data science needs, a lot of people are shifting towards Python from R. This might seem like the logical scenario. But R would still come out as the popular choice for data scientists. People are shifting towards Python but not as many as to disregard R altogether. We have highlighted the pros and cons of both these languages used in Data Science in our Python vs R article. It can be seen that many data scientists learn both languages Python and R to counter the limitations of either language. Being prepared with both languages will help in data science job
interviews.

 

 

Click here to get 100+ Data Science interview coding questions + solution code.

 

 

Python is the “friendly” programming language that plays well with everyone and runs on everything. So it is hardly surprising that Python offers quite a few libraries that deal with data efficiently and is therefore used in data science. Python was used for data science only in the recent years. But now that it has firmly established itself as an important language for Data Science, Python programming is not going anywhere. Mostly Python is used for data analysis when you need to integrate the results of data analysis into
web apps or if you need to add mathematical/statistical codes for production.

 

Work on Hands on Projects in Big Data and Data Science

 

In our previous posts 100 Data Science Interview Questions and Answers (General) and 100 Data Science in R Interview Questions and Answers, we listed all the questions that can be asked in data science job interviews. This article in the series, lists questions which are related to Python programming and will probably be asked in data science interviews.

 

Data Science in Python Interview Questions and Answers

 

 

 

Data Science interview coding questions + solution
code

Here are some solved data cleansing code snippets that you can use in your interviews or projects. Click on these links below to download the python code for these problems. Complete list of ready-to-use solved use-cases is available here.  

How to Flatten a Matrix?

How to Calculate Determinant of a Matrix or ndArray?

How to calculate Diagonal of a Matrix?

How to Calculate Trace of a Matrix?

How to invert a matrix or nArray in Python?

How to convert a dictionary to a matrix or nArray in Python?

How to reshape a Numpy array in Python?

How to select elements from Numpy array in Python?

How to create a sparse Matrix in
Python?

How to Create a Vector or Matrix in Python?

How to run a basic RNN model using Pytorch?

How to save and reload a deep learning model in Pytorch?

How to use auto encoder for unsupervised learning models?​

 

 

Data Science Python Interview Questions and Answers

 

The questions below are based on the course that is taught at DeZyre – Data Science in Python. This is not a guarantee that these questions will be asked in Data Science Interviews. The purpose of these questions is to make the reader aware of the kind of knowledge that an applicant for a Data Scientist position needs to possess.  
 

 

Data Science Interview Questions in Python are generally scenario based or problem based questions where candidates are provided with a data set and asked to do data munging, data exploration, data visualization, modelling, machine learning, etc. Most of the data science interview questions are subjective and the answers to these questions vary, based on the given data problem. The main aim of the interviewer is to see how you code, what are the visualizations you can draw from the data, the conclusions you can make from the data set, etc.

 

1) How can you build a simple logistic regression model in Python? (get solved code examples for hands-on
experience)

 

2) How can you train and interpret a linear regression model in SciKit learn?

 

3) Name a few libraries in Python used for Data Analysis and Scientific computations.

 

NumPy, SciPy, Pandas, SciKit, Matplotlib, Seaborn

 

4) Which library would you prefer for plotting in Python language: Seaborn or Matplotlib?

 

Matplotlib is the python library used for plotting but it needs lot of fine-tuning to ensure that the plots look shiny. Seaborn helps data scientists create statistically and aesthetically appealing meaningful plots. The answer to this question varies based on the requirements for
plotting data.

 

5)  What is the main difference between a Pandas series and a single-column DataFrame in Python?

 

6) Write code to sort a DataFrame in Python in descending order.

 

7) How can you handle duplicate values in a dataset for a variable in Python? (get solved use-cases + code)

 

8) Which Random Forest parameters can be tuned to enhance the predictive power of the model?

 

9) Which method in pandas.tools.plotting is used to create scatter plot matrix?

 

   Scatter_matrix

 

10) How can you check if a data set or time series is
Random?

 

To check whether a dataset is random or not use the lag plot. If the lag plot for the given dataset does not show any structure then it is random.

 

11) Can we create a DataFrame with multiple data types in Python? If yes, how can you do it?

 

 12) Is it possible to plot histogram in Pandas without calling Matplotlib? If yes, then write the code to plot the histogram?

 

13) What are the possible ways to load an array from a text data file in Python? How can the efficiency of the code to load data file be improved?

 

  numpy.loadtxt ()

 

14) Which is the standard data
missing marker used in Pandas?

 

NaN

 

15) Why you should use NumPy arrays instead of nested Python lists?

 

16)  What is the preferred method to check for an empty array in NumPy? (get solved use-cases + code)

 

17) List down some evaluation metrics for regression problems.

 

18) Which Python library would you prefer to use for Data Munging?

 

Pandas

 

19) Write the code to sort an array in NumPy by the nth column?

 

Using argsort () function this can be achieved. If there is an array X and you would like to sort the nth column then code for this will
be x[x [: n-1].argsort ()]

 

20) How are NumPy and SciPy related?

 

21) Which python library is built on top of matplotlib and Pandas to ease data plotting?

 

Seaborn

 

22) Which plot will you use to access the uncertainty of a statistic?

 

Bootstrap

 

23) What are some features of Pandas that you like or dislike?

 

24) Which scientific libraries in SciPy have you worked with in your project?

 

25) What is pylab?

 

A package that combines NumPy, SciPy and Matplotlib into a single namespace.

 

     26) Which
python library is used for Machine Learning?

 

       SciKit-Learn

 

Learn Data Science in Python to become an Enterprise Data Scientist

 

Basic Python Programming  Interview Questions  

27) How can you copy objects in Python?

 

The functions used to copy objects in Python are-

 

1)         Copy.copy () for shallow copy

 

2)         Copy.deepcopy () for deep copy

 

However, it is not possible to copy all objects in Python using these functions.  For instance, dictionaries have a separate copy
method whereas sequences in Python have to be copied by ‘Slicing’.

 

 

 

28) What is the difference between tuples and lists in Python?

 

Tuples can be used as keys for dictionaries i.e. they can be hashed. Lists are mutable whereas tuples are immutable - they cannot be changed. Tuples should be used when the order of elements in a sequence matters. For example, set of actions that need to be executed in sequence, geographic locations or list of points on a specific route.

 

29) What is PEP8?

 

PEP8 consists of coding guidelines for Python language so that programmers can write readable
code making it easy to use for any other person, later on.

 

30) Is all the memory freed when Python exits?

 

No it is not, because the objects that are referenced from global namespaces of Python modules are not always de-allocated when Python exits.

 

31) What does _init_.py do?

 

_init_.py is an empty py file used for importing a module in a directory. _init_.py provides an easy way to organize the files. If there is a module maindir/subdir/module.py,_init_.py is placed in all the directories so that the module can be imported using the following command-

 

import
 maindir.subdir.module

 

32) What is the different between range () and xrange () functions in Python?

 

range () returns a list whereas xrange () returns an object that acts like an iterator for generating numbers on demand.

 

33) How can you randomize the items of a list in place in Python? (get solved use-cases + code)

 

Shuffle (lst) can be used for randomizing the items of a list in Python

 

34) What is a pass in Python?

 

Pass in Python signifies a no operation statement indicating that nothing is to be done.

 

35) If you are gives the first and last names of
employees, which data type in Python will you use to store them?

 

You can use a list that has first name and last name included in an element or use Dictionary.

 

Python Interview

36) What happens when you execute the statement mango=banana in Python?

 

A name error will occur when this statement is executed in Python.

 

37) Write a sorting algorithm for a numerical dataset in Python. (get solved use-cases + code)

 

38) Optimize the below python code-

 

word = 'word'

 

print word.__len__ ()

 

Answer: print ‘word’._len_ ()

 

39) What is monkey patching in Python?

 

Monkey patching is a technique that helps the programmer to modify or extend other code at runtime. Monkey patching comes handy in testing but it is not a
good practice to use it in production environment as debugging the code could become difficult.

 

40) Which tool in Python will you use to find bugs if any?

 

Pylint and Pychecker. Pylint verifies that a module satisfies all the coding standards or not. Pychecker is a static analysis tool that helps find out bugs in the course code.

 

41) How are arguments passed in Python- by reference or by value?

 

The answer to this question is neither of these because passing semantics in Python are completely different. In all cases, Python passes arguments by value where all values are references to objects.

 

42) You
are given a list of N numbers. Create a single list comprehension in Python to create a new list that contains only those values which have even numbers from elements of the list at even indices. For instance if list[4] has an even value the it has be included in the new output list because it has an even index but if list[5] has an even value it should not be included in the list because it is not at an even index.

 

[x for x in list [1::2] if x%2 == 0]

 

The above code will take all the numbers present at even indices and then discard the odd numbers.

 

43) Explain the usage of decorators.

 

Decorators in Python are used
to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.

 

44) How can you check whether a pandas data frame is empty or not? (get solved use-cases + code)

 

The attribute df.empty is used to check whether a data frame is empty or not.

 

45) What will be the output of the below Python code –

 

def multipliers
():

 

   return [lambda x: i * x for i in range (4)]

 

   print [m (2) for m in multipliers ()]

 

The output for the above code will be [6, 6,6,6]. The reason for this is that because of late binding the value of the variable i is looked up when any of the functions returned by multipliers are called.

 

46) What do you mean by list comprehension?

 

The process of creating a list while performing some operation on the data so that it can be accessed using an iterator is referred to as List Comprehension.

 

Example:

 

[ord (j) for j in
string.ascii_uppercase]

 

    [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

 

Matser Data Science with Python by working on innovative Data Science Projects in Python

 

47)       What will be the output of the below code

 

word = ‘aeioubcdfg'

 

print word [:3] + word [3:]

 

The output for the above code will be: ‘aeioubcdfg'.

 

In string slicing when the indices of both the slices collide and a “+” operator is applied on the string it concatenates
them.

 

48)       list= [‘a’,’e’,’i’,’o’,’u’]

 

print list [8:]

 

The output for the above code will be an empty list []. Most of the people might confuse the answer with an index error because the code is attempting to access a member in the list whose index exceeds the total number of members in the list. The reason being the code is trying to access the slice of a list at a starting index which is greater than the number of members in the list.

 

49)       What will be the output of the below code: (get solved use-cases +
code)

 

def foo (i= []):

 

   i.append (1)

 

   return i

 

>>> foo ()

 

>>> foo ()

 

The output for the above code will be-

 

[1]

 

[1, 1]

 

Argument to the function foo is evaluated only once when the function is defined. However, since it is a list, on every all the list is modified by appending a 1 to it.

 

50) Can the lambda forms in Python contain statements?

 

No, as their syntax is restrcited to single expressions and they are used for creating function objects
which are returned at runtime.

 

This list of questions for Python interview questions and answers is not an exhaustive one and will continue to be a work in progress. Let us know in comments below if we missed out on any important question that needs to be up here.

 

 

 

Get hands-on experience for your interview

with solved use-cases + code

 

 

 

 

PREVIOUS

 

NEXT

 

 

 

Follow

 

Big Data and Hadoop Training Courses in Popular Cities

Hadoop Training in Texas

Hadoop Training in
California

Hadoop Training in Dallas

Hadoop Training in Chicago

Hadoop Training in Charlotte

Hadoop Training in Dubai

Hadoop Training in Edison

Hadoop Training in Fremont

Hadoop Training in San Jose

Hadoop Training in Washington

Hadoop Training in New Jersey

Hadoop Training in New York

Hadoop Training in Atlanta

Hadoop Training in Canada

Hadoop Training in Abu Dhabi

Hadoop Training in Detroit

Hadoop Trainging in Germany

Hadoop Training in Houston

Hadoop Training in Virginia

 

source:
https://www.dezyre.com/article/100-data-science-in-python-interview-questions-and-answers-for-2018/188

 

############################# PYTHON ########################

Table of Contents

 

Best Python Interview Questions

Question: Describe how multithreading is achieved in Python.

Question: Draw a comparison between the range and xrange in Python.

Question: Explain Inheritance and its various types in Python?

Question: Explain how is it possible to Get the Google cache age of any URL or webpage using Python.

Question: Give a detailed explanation about setting up the database in Django.

Question: How will you
differentiate between deep copy and shallow copy?

Question: How will you distinguish between NumPy and SciPy?

Question: Observe the following code:

Question: Python supports negative indexes. What are they and why are they used?

Question: Suppose you need to collect and print data from IMDb top 250 Movies page. Write a program in Python for doing so. (NOTE: - You can limit the displayed information for 3 fields; namely movie name, release year, and rating.)

Question: Take a look at the following code:

Question: What do you understand by monkey patching in Python?

Question: What do you understand by the process of compilation and linking in
Python?

Question: What is Flask and what are the benefits of using it?

Question: What is the map() function used for in Python?

Question: What is Pickling and Unpickling in Python?

Question: Whenever Python exits, all the memory isn’t deallocated. Why is it so?

Question: Write a program in Python for getting indices of N maximum values in a NumPy array.

Question: Write code to show randomizing the items of a list in place in Python along with the output.

Question: Explain memory managed in Python?

Question: What is the lambda function?

Question: What are Python decorators?

Question: Differentiate between list and
tuple.

Question: How are arguments passed in Python? By value or by reference?

Question: What are the built-in types provided by the Python?

Question: How a file is deleted in Python?

Question: What are Python modules?

Question: What is the // operator? What is its use?

Question: What is the split function used for?

Question: Explain the Dogpile effect.

Question: What is a pass in Python?

Question: Is Python a case sensitive language?

Question: Define slicing in Python.

Question: What are docstring?

Question: What is [::-1} used for?

Question: Define Python Iterators.

Question: How are comments written in
Python?

Question: How to capitalize the first letter of string?

Question: What is, not and in operators?

Question: How are files deleted in Python?

Question: How are modules imported in Python?

Question: What is monkey patching?

Question: Does Python supports multiple inheritances?

Question: What does the method object() do?

Question: What is pep 8?

Question: What is namespace in Python?

Question: Is indentation necessary in Python?

Question: Define a function in Python

Question: Define self in Python

Conclusion

Irrespective of the source you pick a list of best programming languages to learn in 2020 from,
one name that will always find its place there is Python.

 

So, the answer is yes, if you are asking whether a lucrative career is possible by dedicating yourself to the interpreted, high-level, general-purpose programming language i.e. learning Python.

 

Best Python Interview Questions

Once you’ve had enough understanding of the various concepts of Python, it’s time to give a shot at some interviews. To increase your chances of clearing them, here is a list of top Python interview questions that you must know answers to:

 

Question: Describe how multithreading is achieved in Python.

Answer: Even though Python comes
with a multi-threading package, if the motive behind multithreading is to speed the code then using the package is not the go-to option.

 

 

The package has something called the GIL or Global Interpreter Lock, which is a construct. It ensures that one and only one of the threads execute at any given time. A thread acquires the GIL and then do some work before passing it to the next thread.

 

This happens so fast that to a user it seems that threads are executing in parallel. Obviously, this is not the case as they are just taking turns while using the same CPU core. Moreover, GIL passing adds to the overall overhead to the
execution.

 

Hence, if you intend to use the threading package for speeding up the execution, using the package is not recommended.

 

Question: Draw a comparison between the range and xrange in Python.

Answer: In terms of functionality, both range and xrange are identical. Both allow for generating a list of integers. The main difference between the two is that while range returns a Python list object, xrange returns an xrange object.

 

 

Xrange is not able to generate a static list at runtime the way range does. On the contrary, it creates values along with the requirements via a special technique called yielding. It is
used with a type of object known as generators.

 

If you have a very enormous range for which you need to generate a list, then xrange is the function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive system, such as a smartphone.

 

The range is a memory beast. Using it requires much more memory, especially if the requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result in a Memory Error and ultimately lead to crashing the program.

 

Question: Explain Inheritance and its various types in Python?

Answer: Inheritance enables a class to acquire all the members of
another class. These members can be attributes, methods, or both. By providing reusability, inheritance makes it easier to create as well as maintain an application.

 

The class which acquires is known as the child class or the derived class. The one that it acquires from is known as the superclass or base class or the parent class. There are 4 forms of inheritance supported by Python:

 

Single Inheritance – A single derived class acquires from on single superclass.

Multi-Level Inheritance – At least 2 different derived classes acquire from two distinct base classes.

Hierarchical Inheritance – A number of child classes
acquire from one superclass

Multiple Inheritance – A derived class acquires from several superclasses.

Question: Explain how is it possible to Get the Google cache age of any URL or webpage using Python.

Answer: In order to Get the Google cache age of any URL or webpage using Python, the following URL format is used:

 

 

http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE

 

Simply replace URLGOESHERE with the web address of the website or webpage whose cache you need to retrieve and see in Python.

 

Question: Give a detailed explanation about setting up the database in Django.

Answer:
The process of setting up a database is initiated by using the command edit mysite/setting.py. This is a normal Python module with a module-level representation of Django settings. Django relies on SQLite by default, which is easy to be used as it doesn’t require any other installation.

 

SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use the database. For this, the project’s setting.py file needs to be used. Following code must be added to the file for making the database workable with the Django project:

 

DATABASES = {

'default': {

'ENGINE' : 'django.db.backends.sqlite3',

'NAME' :
os.path.join(BASE_DIR, 'db.sqlite3'),

}

}

If you need to use a database server other than the SQLite, such as MS SQL, MySQL, and PostgreSQL, then you need to use the database’s administration tools to create a brand new database for your Django project.

 

You have to modify the following keys in the DATABASE ‘default’ item to make the new database work with the Django project:

 

ENGINE – For example, when working with a MySQL database replace ‘django.db.backends.sqlite3’ with ‘django.db.backends.mysql’

NAME – Whether using SQLite or some other database management system, the
database is typically a file on the system. The NAME should contain the full path to the file, including the name of that particular file.

NOTE: - Settings like Host, Password, and User needs to be added when not choosing SQLite as the database.

 

Check out the advantages and disadvantages of Django.

 

Question: How will you differentiate between deep copy and shallow copy?

Answer: We use shallow copy when a new instance type gets created. It keeps the values that are copied in the new instance. Just like it copies the values, the shallow copy also copies the reference pointers.

 

Reference points copied in the shallow copy
reference to the original objects. Any changes made in any member of the class affects the original copy of the same. Shallow copy enables faster execution of the program.

 

 

Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object in addition to storing the new object that is pointed by some other object.

 

Changes made to the original copy will not affect any other copy that makes use of the referenced or stored object. Contrary to the shallow copy, deep copy makes execution of a program slower. This is due to the
fact that it makes some copies for each object that is called.

 

Question: How will you distinguish between NumPy and SciPy?

Answer: Typically, NumPy contains nothing but the array data type and the most basic operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the numerical code resides in SciPy.

 

As one of NumPy’s most important goals is compatibility, the library tries to retain all features supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions despite the fact that these more appropriately belong to the SciPy library.

 

SciPy contains fully-featured
versions of the linear algebra modules available to NumPy in addition to several other numerical algorithms.

 

Question: Observe the following code:

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 =  

A6 = [[i,i*i] for i in A1]

print(A0,A1,A2,A3,A4,A5,A6)

Write down the output of the code.

Answer:

 

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary

A1 = range(0, 10)

A2 = []

A3 = [1, 2, 3, 4, 5]

A4 = [1, 2, 3, 4, 5]

A5 =

A6 =
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

 

Question: Python has something called the dictionary. Explain using an example.

 

Answer: A dictionary in Python programming language is an unordered collection of data values such as a map. Dictionary holds key:value pair. It helps in defining a one-to-one relationship between keys and values. Indexed by keys, a typical dictionary contains a pair of keys and corresponding values.

 

Let us take an example with three keys, namely Website, Language, and Offering. Their corresponding values are hackr.io, Python, and Tutorials. The code for the example will
be:

 

dict={‘Website’:‘hackr.io’,‘Language’:‘Python’:‘Offering’:‘Tutorials’}

print dict[Website] #Prints hackr.io

print dict[Language] #Prints Python

print dict[Offering] #Prints Tutorials

Question: Python supports negative indexes. What are they and why are they used?

Answer: The sequences in Python are indexed. It consists of positive and negative numbers. Positive numbers use 0 as the first index, 1 as the second index, and so on. Hence, any index for a positive number n is n-1.

 

 

Unlike positive numbers, index numbering for the
negative numbers start from -1 and it represents the last index in the sequence. Likewise, -2 represents the penultimate index. These are known as negative indexes. Negative indexes are used for:

 

Removing any new-line spaces from the string, thus allowing the string to except the last character, represented as S[:-1]

Showing the index to representing the string in the correct order

Question: Suppose you need to collect and print data from IMDb top 250 Movies page. Write a program in Python for doing so. (NOTE: - You can limit the displayed information for 3 fields; namely movie name, release year, and rating.)

Answer:

 

from bs4 import
BeautifulSoup

import requests

import sys

url = 'http://www.imdb.com/chart/top'

response = requests.get(url)

soup = BeautifulSoup(response.text)

tr = soup.findChildren("tr")

tr = iter(tr)

next(tr)  

for movie in tr:

title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]

year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]

rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]

row = title + ' - ' + year + ' ' + ' ' + rating  

print(row)

Question: Take a look at the following
code:

try: if '1' != 1:  

raise "someError"  

else: print("someError has not occured")  

except "someError": pr

int ("someError has occured")

What will be the output?

Answer: The output of the program will be “invalid code.” This is because a new exception class must inherit from a BaseException.

 

Question: What do you understand by monkey patching in Python?

Answer: The dynamic modifications made to a class or module at runtime are termed as monkey patching in Python. Consider the following code snippet:

 

# m.py

class MyClass:

def f(self):

print "f()"

We can
monkey-patch the program something like this:

 

import m

def monkey_f(self):

print "monkey_f()"

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

Output for the program will be monkey_f().

 

The examples demonstrate changes made in the behavior of f() in MyClass using the function we defined i.e. monkey_f() outside of the module m.

 

Python Interview

Question: What do you understand by the process of compilation and linking in Python?

Answer: In order to compile new extensions without any error, compiling and linking is used in Python. Linking initiates only and only when the

Python Interview

Here are the top Python interview questions and answers that cover a wide base of topics associated with Python such as the use of the assert statement, the difference between Shallow copy vs deep copy, decorators in Python. Go through these Python interview question-answer sets and land your dream job as a Python Developer, Full Stack engineer, and other top profiles. Practice these interview questions on Python with answers provided by experts and be fully prepared for your next Python interview.

### Beginer:

1#How do I check whether a file exists using Python?

ANS:

There are a couple of ways to check if a file exists or not. First method is use open() function
on a file and see if it raises any exception. If the file is indeed existing, the open() function will be executed correctly. However, if it doesn’t, an exception will be raised.

 

>>> try:

file=open(filename)

print ('the file exists')

file.close()

except:

print ('file is not existing')

You can also use exists() method of path object defined in os module.

 

>>> from os import path

>>> path.exists(filename)

Here filename should be a string containing name along with file’s path. Result will be True if file exists otherwise false.

 

Python library consists
of pathlib module. You can also check if file exists or not by using exists() method in this module as follows:

 

>>> import pathlib

>>> file=pathlib.Path(filename)

>>> file.exists()

 

2#Why is Python called dynamically typed language?

ANS:

Computer languages are generally classified as statically or dynamically typed. Examples of statically typed languages are C/C++, Java, C# etc. Python, along with JavaScript, PHP etc are dynamically typed languages.  

 

First we have to understand the concept of variable. In C/C++/Java, variable is a user defined convenience name given to a memory
location. Moreover, compilers of these languages require prior declaration of name of variable and type of data that can be stored in it before actually assigning any value. Typical variable declaration and assignment statement in C/C++/Java would be as follows:

 

int x;

x=10;

Here, the variable x is permanently bound to int type. If data of any other type is assigned, compiler error will be reported. Type of variable decides what can be assigned to it and what can’t be assigned.

 

In Python on the other hand, the object is stored in a randomly chosen memory location, whereas variable is just an identifier or a label referring to it. When
we assign 10 to x in Python, integer object 10 is stored in memory and is labelled as x. Python’s built-in type() function  tells us that it stores object of int type.

 

>>> x=10

>>> type(x)

<class 'int'>

However, we can use same variable x as a label to another object, which may not be of same type.  

 

>>> x='Hello'

>>> type(x)

<class 'str'>

Python interpreter won’t object if same variable is used to store reference to object of another type. Unlike statically typed languages, type of variable changes dynamically as per the object whose reference has
been assigned to it. Python is a dynamically typed language because type of variable depends upon type of object it is referring to.

 

3#Is Python weakly typed or strongly typed?

ANS:

 

4#What is difference between string and raw string?

ANS:

5#Python library has built-in pow() function. It also has pow() function in math module. What's the difference?</p>                                                            

ANS:

6#Python's math module has ceil() and floor() division
functions. What is the difference?

ANS:

7#How do we define class level attributes and methods in a Python class?

ANS:

8#How can arguments be passed from command line to a Python program?

ANS:

9#How do you unpack a Python tuple object?

ANS:

10#What is the difference between break and continue?

ANS:

11#What according to you is the difference between shallow copy and deep copy?

ANS:

12#What are Python-specific environment variables?

ANS:

13#Python index operator can accept negative numbers. Explain how?

ANS:

14#List and tuple data types appear to be similar in nature. Explain typical use cases of
list and tuple.

ANS:

15#What is the difference between TypeError and ValueError?

ANS:

16#Explain the builtins getattr() and setattr() functions.

ANS:

17#How are Python’s built-in functions ord() and chr() related?

ANS:

18#What is the use of slice object in Python?

ANS:

19#Explain the behaviour of view objects in Python.

ANS:

20#Single and double underscore symbols have special significance in Python. When and where are they used?

ANS:

21#How do you define a constructor in Python class? Can a class have overloaded constructor in Python?

ANS:

22#How does destructor work in a Python
class?

ANS:

23#In what circumstances is the ‘elif’ keyword recommended to be used?

ANS:

24#Python offers two keywords – while and for – to constitute loops. Can you bring out the difference and similarity in their usage?

ANS:

25#What are some different command line options available for using Python interpreter?

ANS:

26#What is the use of built-in zip() function. Explain with suitable examples.

ANS:

27#Explain built-in any() and all() functions.

ANS:

28#How is multiplication and division of complex numbers done? Verify the process with complex number objects of Python.

ANS:

29#When
should finally clause be used in exception handling process?

ANS:

30#Explain hash() function in the built-in library.

ANS:

 

source: https://www.knowledgehut.com/interview-questions/python

### Intermediate

1#Python's standard library has a built-in function next(). For what purpose is it used?

ANS:

2#Explain with example the technique of list comprehension in Python.

ANS:

3#Where and how is Python keyword yield used?

ANS:

4#Explain concept of mutable vs immutable object in Python.

ANS:

5#What is the difference between set and frozenset?

ANS:

6#Does Python support operator overloading?
How?

ANS:

7#How is a complex number in Python represented in terms of polar coordinates?

ANS:

8#Recursion is also a kind of iteration. Discuss their relative merits and demerits.

ANS:

9#What is assert in Python? Is it a function, class or keyword? Where and how is it used?

ANS:

10#What is a callable object in Python?

ANS:

11#What is the special significance of * and ** in Python?

ANS:

12#Which type of function calling mechanism is employed in Python? Call by value or Call by reference?

ANS:

13#Does Python support data encapsulation?

ANS:

14#One of the 33 keywords of Python is lambda. How and for
what purpose is it used?

ANS:

15#Explain how useful Python’s ‘with’ statement is.

ANS:

16#Explain the concept of packages in Python

ANS:

17#Explain the advantage of ‘x’ as value of mode parameter in open() function.

ANS:

18#How can we check if a certain class is a subclass of another?

ANS:

19#Explain the concept of global, local and nonlocal variables in Python.

ANS:

20#What are various string formatting features available in Python?

ANS:

21#Consider following expression in Python console:<br>>>> num=100, Is the above expression valid? If yes, what is the data
type of num? Why?

ANS:

22#What is the difference between Python and IPython?

ANS:

23#What is a range object in Python?

ANS:

24#What is JSON? How can Python objects be represented in JSON format?

ANS:

25#How does Python differentiate between executable script and importable script?

ANS:

26#What are the different ways of importing a module?

ANS:

27#Does Python support polymorphism? Explain with a suitable example.

ANS:

28#What are IP address versions? How does Python manage IP addresses?

ANS:

29#Explain briefly the usage of pip utility.

ANS:

30#Explain the concept of unit testing with a
simple example.

ANS:

31#How is DocTest framework used?

ANS:

32#For what purpose(s) is Python’s ‘as’ keyword used?

ANS:

33#What is a user defined exception? How is it raised in Python script?

ANS:

34#The built-in print() function accepts a number of optional arguments. Explain their use with an example.

ANS:

 

source: https://www.knowledgehut.com/interview-questions/python

### Advanced

 

1#What is a metaclass in Python?

ANS:

2#Python doesn't have concept of array as in C/C++/Java etc. But it does have array module in the standard library. How is it
used?

ANS:

3#Functions are higher order objects in Python. What does this statement mean?

ANS:

4#What do you mean by object serialization? Is it the same as data persistence?

ANS:

5#Python's standard library has random module and secrets module. Both have functions to generate random number. What's the difference?

ANS:

6#What do you understand by SQL injection? What is the prescribed method of executing parameterized queries using DB-API?

ANS:

7#What are important features of dataclasses in Python?

ANS:

8#What is the advantage of employing keyword arguments in definition of function? How can we force compulsory usage of
keyword arguments in function call?

ANS:

9#What is the importance of using a virtual environment? Explain how to setup, activate and deactivate virtual environment?

ANS:

10#Built-in exec() function is provided for dynamic execution of Python code. Explain its usage.

ANS:

11#What is ‘shebang’ in a Python script? Is it possible to make a Python script self-executable?

ANS:

12#What are some alternative implementations of Python?

ANS:

13#What is a partial object in Python?

ANS:

14#What is the purpose of getpass module in standard library?

ANS:

15#Python scripts are saved with .py extension. However,
.pyc files are frequently found. What do they stand for?

ANS:

16#What is garbage collection? How does it work in Python?

ANS:

17#What is ‘monkey patching’? How is it performed in Python?

ANS:

18#Explain how and when Python’s built-in property() function should be used?

ANS:

19#Are there any alternatives to standard input/output functions of Python?

ANS:

20#What is the difference between built-in functions eval() and exec()?

ANS:

21#Explain how built-in compile() function works

ANS:

22#What does pprint() function do? Is it the same as print() function?

ANS:

23#What is the
difference between CGI and WSGI?

ANS:

24#What is FieldStorage class in Python? Explain its usage.

ANS:

25#What is the difference between bytes() and bytearray() in Python?

ANS:

26#What are abstract base classes in Python?

ANS:

27#What are hashing algorithms? How can we obtain md5 hash value of a string in Python?

ANS:

28#Give a brief comparison of vars() and dir() built-in functions in Python’s standard library.

ANS:

29#Python script written using Python 2.x syntax is not compatible with Python 3.x interpreter. How can one automatically port Python 2.x code to Python 3.x?

ANS:

30#What is the difference
between assertion and exception? Explain with the help of suitable Python examples.

ANS:

31#How are warnings generated in Python?

ANS:

32#What are the characteristics of Counter object in Python?

ANS:

33#Give a brief overview of various data compression and archiving APIs in Python’s standard library.

ANS:

34#What do you mean by duck typing? How does Python implement duck typing?

ANS:

35#What are Closures in Python?

ANS:

36#What is memoryview object in Python?

ANS:

source: https://www.knowledgehut.com/interview-questions/python

Python Interview