Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Python Interview Questions and Answers

Test your skills through the online practice test: Python Quiz Online Practice Test

Freshers / Beginner level questions & answers

Ques 1. What is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high-level dynamic data types, and classes.

Python combines remarkable power with very clear syntax. It has interfaces to many systems calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface.

Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

Is it helpful? Add Comment View Comments
 

Ques 2. What are the benefits of Python?

The benefits of Python are as follows: 

  • Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process control capabilities and possesses strong integration.
  • Extensive Support for Libraries: Python provides a large standard library that includes areas such as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the programming tasks are already been scripted in the standard library which reduces effort and time.
  • User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to build fast user-friendly data structures.
  • Existence of Third-Party Modules: The presence of third-party modules in the Python Package Index (PyPI) will make Python capable to interact with other platforms and languages.
  • Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for beginners to learn.

Is it helpful? Add Comment View Comments
 

Ques 3. What are the key features of Python?

 The following are the significant features of Python, and they are:

  • Interpreted Language: Python is an interpreted language that is used to execute the code line by line at a time. This makes debugging easy.
  • Highly Portable: Python can run on different platforms such as Unix, Macintosh, Linux, Windows, and so on. So, we can say that it is a highly portable language.
  • Extensible: It ensures that the Python code can be compiled on various other languages such as C, C++, and so on.
  • GUI programming Support: It implies that Python provides support to develop graphical user interfaces

Is it helpful? Add Comment View Comments
 

Ques 4. What type of language is Python? Programming or Scripting?

Python is suitable for scripting, but in general, it is considered a general-purpose programming language.

Is it helpful? Add Comment View Comments
 

Ques 5. What are the applications of Python?

The applications of Python are as follows:

  • GUI-based desktop applications
  • Image processing applications
  • Business and Enterprise applications
  • Prototyping
  • Web and web framework applications

Is it helpful? Add Comment View Comments
 

Ques 6. Define modules in Python?

The module is defined as a file that includes a set of various functions and Python statements that we want to add to our application. 

Is it helpful? Add Comment View Comments
 

Ques 7. What is the difference between .py and .pyc files?

py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler.

Is it helpful? Add Comment View Comments
 

Ques 8. Define String in Python?

String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified because they are immutable objects. String literals in Python can be declared using double quotes or single quotes.

Ex:

  • print("Hello")
  • print('Hello')

Is it helpful? Add Comment View Comments
 

Ques 9. What do you understand by the term namespace in Python?

A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are:

  • Local namespace
  • Global namespace
  • Built-in namespace

Scope of an object in Python: 

Scope refers to the availability and accessibility of an object in the coding region.

Is it helpful? Add Comment View Comments
 

Ques 10. Define iterators in Python?

In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is mainly used to iterate a group of containers, elements, the same as a list.

Is it helpful? Add Comment View Comments
 

Ques 11. How does a function return values?

Functions return values using the return statement.

Ex:

def func():

    num = 10

    return num

Is it helpful? Add Comment View Comments
 

Ques 12. Define slicing in Python?

Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and so on.

a = ("a", "b", "c", "d", "e", "f", "g", "h")

x = slice(3, 5)

print(a[x])

Output:

('d', 'e')

Is it helpful? Add Comment View Comments
 

Ques 13. Define package in Python.

In Python packages are defined as the collection of different modules.

Is it helpful? Add Comment View Comments
 

Ques 14. Which command is used to delete files in Python?

OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming. Example:

import OS

OS.remove('hello.txt')

Is it helpful? Add Comment View Comments
 

Ques 15. Explain the difference between local and global namespaces?

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

Is it helpful? Add Comment View Comments
 

Ques 16. What is a boolean in Python?

Boolean is one of the built-in data types in Python, it mainly contains two values, which are true and false

Python bool() is the method used to convert a value to a boolean value.

Is it helpful? Add Comment View Comments
 

Ques 17. What are the functions in Python?

In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.

Is it helpful? Add Comment View Comments
 

Ques 18. Define self in Python?

In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python programming using self keyword.  

In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other methods self refers to the object whose method was called. 

Is it helpful? Add Comment View Comments
 

Ques 19. How do we convert the string to lowercase?

 The lower() function is used to convert string to lowercase.

Example:

str = "WithoutBook"

print(str.lower())

Output:

withoutbook

Is it helpful? Add Comment View Comments
 

Ques 20. What is Try Block in python?

A block that is preceded by the try keyword is known as a try block.

Syntax:

try {

    // Statements that may cause exception

}

Is it helpful? Add Comment View Comments
 

Ques 21. Why do we use the split method in Python?

split() method in Python is mainly used to separate a given string.

Example:

txt = "welcome to the withoutbook"

x = txt.split()

print(x)

Output:

['welcome', 'to', 'the', 'withoutbook']

Is it helpful? Add Comment View Comments
 

Ques 22. Can we make multi-line comments in Python?

In python, there is no specific syntax to display multi-line comments like in other languages. In order to display multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by the Python parser.

Is it helpful? Add Comment View Comments
 

Ques 23. What are the OOP's concepts available in Python?

Python is also an object-oriented programming language like other programming languages. It also contains different OOP's concepts, and they are 

  • Object
  • Class
  • Method
  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Is it helpful? Add Comment View Comments
 

Ques 24. Define object in Python.

An object in Python is defined as an instance that has both state and behavior. Everything in Python is made of objects.

Is it helpful? Add Comment View Comments
 

Ques 25. What is a class in Python?

Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes. 

Is it helpful? Add Comment View Comments
 

Ques 26. How to create a class in Python?

In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:

Example:

class ClassName:

    code statement

Is it helpful? Add Comment View Comments
 

Ques 27. What is the syntax for creating an instance of a class in Python?

The syntax for creating an instance of a class is as follows:

<object-name> = <class-name>(<arguments>)

Is it helpful? Add Comment View Comments
 

Ques 28. Define what is “Method” in Python programming.

The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of object can have methods.

Is it helpful? Add Comment View Comments
 

Ques 29. Why can't I use an assignment in an expression?

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
  ...do something with line...
}

 
where in Python you're forced to write this:

while True:
  line = f.readline() if not line:
  break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

 
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

 
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

 
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

Is it helpful? Add Comment View Comments
 

Ques 30. How do you set a global variable in a function in Python?

x = 1 # make a global
def f():
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.


The solution is to insert an explicit global declaration at the start of the function:

 
def f():
  global x
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
In this case, all references to x are interpreted as references to the x from the module namespace.

Is it helpful? Add Comment View Comments
 

Ques 31. What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. 


Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time.

You'd have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Is it helpful? Add Comment View Comments
 

Ques 32. How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.


For example:

config.py: 
x = 0 # Default value of the 'x' configuration setting

mod.py: 
import config
config.x = 1

main.py:
import config
import mod
print config.x

 
Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

Is it helpful? Add Comment View Comments
 

Ques 33. How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:

def f(x, *tup, **kwargs):
  kwargs['width']='14.3c'
  g(x, *tup, **kwargs)

In the unlikely case that you care about Python versions older than 2.0, use 'apply':

def f(x, *tup, **kwargs): 
  kwargs['width']='14.3c'
  apply(g, (x,)+tup, kwargs)

Is it helpful? Add Comment View Comments
 

Ques 34. How do you make a higher order function in Python?

You have two choices: you can use nested scopes or you can use callable objects.

For example, 
suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b): 
  def result(x):
    return a*x + b
      return result

Or using a callable object: 

class linear: 
  def __init__(self, a, b):
    self.a, self.b = a,b
    def __call__(self, x):
      return self.a * x + self.b

In both cases: 
taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.

 
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear): 
  # __init__ inherited
  def __call__(self, x):
    return self.a * (x ** self.b)

Object can encapsulate state for several methods: 
class counter:
  value = 0
    def set(self, x): self.value = x
    def up(self): self.value=self.value+1
    def down(self): self.value=self.value-1
    count = counter()
    inc, dec, reset = count.up, count.down, count.set

Here inc(), dec() and reset() act like functions which share the same counting variable.

Is it helpful? Add Comment View Comments
 

Ques 35. How do I copy an object in Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method: newdict = olddict.copy()

Sequences can be copied by slicing: new_l = l[:]

Is it helpful? Add Comment View Comments
 

Ques 36. How can I find the methods or attributes of an object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

Is it helpful? Add Comment View Comments
 

Ques 37. How do I convert a string to a number?

For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0.

By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError.

int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number. 

Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory. 

eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8).

Is it helpful? Add Comment View Comments
 

Ques 38. How can my code discover the name of an object?

Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of def and class statements, but in that case the value is a callable. Consider the following code:

class A:
  pass
  B = A
  a = B()
  b = a
  print b
  <__main__.A instance at 016D07CC>
  print a
  <__main__.A instance at 016D07CC>

Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value.

Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:
The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)
....and don't be surprised if you'll find that it's known by many names, or no name at all!

Is it helpful? Add Comment View Comments
 

Ques 39. Is there an equivalent of C's "?:" ternary operator?

No.

Is it helpful? Add Comment View Comments
 

Ques 40. How do I convert a number to a string in Python?

  • To convert, e.g., the number 144 to the string '144', use the built-in function str().
  • If you want a hexadecimal or octal representation, use the built-in functions hex() or oct().
  • For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. 

Is it helpful? Add Comment View Comments
 

Ques 41. How do I modify a string in place?

You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:

>>> s = "Hello, world" >>> a = list(s) 
>>>print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']

>>> a[7:] = list("there!") 
>>>''.join(a)
'Hello, there!' 

>>> import array 
>>> a = array.array('c', s) >>> print a
array('c', 'Hello, world')

>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'

Is it helpful? Add Comment View Comments
 

Ques 42. How do I use strings to call functions/methods in Python?

There are various techniques.

* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct: 

def a():
  pass
  def b():
    pass
    dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
    dispatch[get_input()]() # Note trailing parens to call function

Use the built-in function getattr(): 
import foo
getattr(foo, 'bar')()

Note that getattr() works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this: 

class Foo: 
  def do_foo(self):
    def do_bar(self):
      f = getattr(foo_instance, 'do_' + opname)
        f()

  • Use locals() or eval() to resolve the function name: 
    def myFunc(): print "hello" fname = "myFunc" f = locals()[fname] f() f = eval(fname) f()

Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed. 

Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? 
Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurences of any line terminator.
from the end of the string S without removing other trailing whitespace. If the string S represents more
than one line, with several empty lines at the end, the line terminators for all the blank lines will be
removed:
>>> lines = ("line 1 "
... 
... ) 
>>> lines.rstrip(" ") 
"line 1" 
Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works
well.
For older versions of Python, There are two partial substitutes:
* If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline.
* Otherwise, if there is only one line in the string S, use S.splitlines()[0].
Is there a scanf() or sscanf() equivalent?
Not as such.

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task.

Is it helpful? Add Comment View Comments
 

Ques 43. What is the difference between a list and a tuple in Python?

The difference between a tuple and list in python is as follows:

ListTuple
The list is mutable (can be changed)A tuple is immutable (remains constant)
These lists performance is slowerTuple performance is faster when compared to lists
Syntax: list_1 = [20, ‘Mindmajix’, 30]Syntax: tup_1 = (20, ‘Mindmajix’, 30)

Is it helpful? Add Comment View Comments
 

Ques 44. Define PYTHON PATH?

PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we import a module, PYTHONPATH is used to check the presence of the modules that are imported in different directories. Loading of the module will be determined by interpreters.

Is it helpful? Add Comment View Comments
 

Ques 45. What are the two major loop statements?

Two major loop statements are:

  • for
  • while

Is it helpful? Add Comment View Comments
 

Ques 46. What do you understand by the term PEP 8?

PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all about how to format your Python code for maximum readability.

Is it helpful? Add Comment View Comments
 

Ques 47. What are the built-in types available in Python?

The built-in types in Python are as follows:

  • Integer
  • Complex numbers
  • Floating-point numbers
  • Strings
  • Built-in functions

Is it helpful? Add Comment View Comments
 

Ques 48. What are Python Decorators?

Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function. 

Is it helpful? Add Comment View Comments
 

Ques 49. How do we find bugs and statistical problems in Python?

We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is another tool called PyLint that checks whether the Python modules meet their coding standards or not.

Is it helpful? Add Comment View Comments
 

Ques 50. How do you invoke the Python interpreter for interactive use?

By using python or pythonx.y we can invoke a Python interpreter. where x.y is the version of the Python interpreter.

Is it helpful? Add Comment View Comments
 

Ques 51. How can Python be an interpreted language?

As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called an interpreted language. 

Is it helpful? Add Comment View Comments
 

Ques 52. What happens when a function doesn’t have a return statement? Is this valid?

Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code that is executed (i.e., the indenting) not by any explicit keyword.

Is it helpful? Add Comment View Comments
 

Ques 53. How can we make a Python script executable on Unix?

In order to make a Python script executable on Unix, we need to perform two things. They are:

  • Script file mode must be executable and
  • The first line should always begin with #.

Is it helpful? Add Comment View Comments
 

Ques 54. What are Dict and List comprehensions in Python?

These are mostly used as syntax constructions to ease the creation of lists and dictionaries based on existing iterable.

Is it helpful? Add Comment View Comments
 

Ques 55. Define the term lambda.

Lambda is the small anonymous function in Python that is often used as an inline function.

Is it helpful? Add Comment View Comments
 

Ques 56. When would you use triple quotes as a delimiter?

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

Is it helpful? Add Comment View Comments
 

Ques 57. How do we reverse a list in Python?

By using the list.reverse(): we can reverse the objects of the list in Python.

Is it helpful? Add Comment View Comments
 

Ques 58. Does multiple inheritances are supported in Python?

Multiple inheritances are supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class. 

Is it helpful? Add Comment View Comments
 

Ques 59. Define Constructor in Python.

Constructor is a special type of method with a block of code to initialize the state of instance members of the class. A constructor is called only when the instance of the object is created. It is also used to verify that they are sufficient resources for objects to perform a specific task.

There are two types of constructors in Python, and they are:

  • Parameterized constructor
  • Non-parameterized constructor

Is it helpful? Add Comment View Comments
 

Ques 60. What is the best Python IDE for beginners?

There are many IDE’s to execute Python code. But, as a beginner, the following two IDE’s will be helpful 

  • PyCharm
  • Spyder

Is it helpful? Add Comment View Comments
 

Ques 61. How do I prepare for a Python interview?

  • First of all, learn how to write code in the white paper without any support (IDE)
  • Maintain basic Python control flow
  • Be confident in explaining your program flow
  • Learn where to use oops concepts and generators

Is it helpful? Add Comment View Comments
 

Ques 62. Why should you choose Python?

There is no doubt, Python is the best choice for coding in the interview. Other than Python,  if you prefer to choose C++ or java you need to worry about structure and syntax.

Is it helpful? Add Comment View Comments
 

Ques 63. Can we use Python for coding in interviews?

Choosing an appropriate language to code also matters at the time of the interview. Any language can be used for coding but coding in Python is seeming less and easy.

Is it helpful? Add Comment View Comments
 

Intermediate / 1 to 5 years experienced level questions & answers

Ques 64. How memory management is done in Python?

  • In Python memory management is done using private heap space. The private heap is the storage area for all the data structures and objects. The interpreter has access to the private heap and the programmer cannot access this private heap. 
  • The storage allocation for the data structures and objects in Python is done by the memory manager. The access for some tools is provided by core API for programmers to code.
  • The built-in garbage collector in Python is used to recycle all the unused memory so that it can be available for heap storage area.

Is it helpful? Add Comment View Comments
 

Ques 65. What are the differences between Java and Python?

Please refer Java vs Python.

Is it helpful? Add Comment View Comments
 

Ques 66. Define pickling and unpickling in Python.

Pickling in Python: The process in which the pickle module accepts various Python objects and converts them into a string representation and dumps the file accordingly using the dump function is called pickling. 

Unpickling in Python: The process of retrieving actual Python objects from the stored string representation is called unpickling.

Is it helpful? Add Comment View Comments
 

Ques 67. What are Python String formats and Python String replacements?

Python String Format: The String format() method in Python is mainly used to format the given string into an accurate output or result.

Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of the substring is replaced by another substring.

Is it helpful? Add Comment View Comments
 

Ques 68. Name some of the built-in modules in Python.

The built-in modules in Python are:

  • sys module
  • OS module
  • random module
  • collection module
  • JSON
  • Math module

Is it helpful? Add Comment View Comments
 

Ques 69. What is _init_?

The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects. 

Is it helpful? Add Comment View Comments
 

Ques 70. Define generators in Python?

The way of implementing an effective representation of iterators is known as generators. It is only the normal function that yields expression in the function.

Is it helpful? Add Comment View Comments
 

Ques 71. Define docstring in Python?

The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.

Is it helpful? Add Comment View Comments
 

Ques 72. How to remove values from a Python array?

The elements can be removed from a Python array using the remove() or pop() function. The difference between pop() and remove() will be explained in the below example.

Example of remove():

fruits = ['apple', 'banana', 'cherry']

fruits.remove('banana')

print(fruits)

Output:

['apple', 'cherry']

 

Example of pop():

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)

print(fruits)

Output:

['apple', 'cherry']

Is it helpful? Add Comment View Comments
 

Ques 73. How do Python arrays and lists differ from each other?

The difference between Python array and Python list is as follows:

ArraysLists
The array is defined as a linear structure that is used to store only homogeneous data.The list is used to store arbitrary and heterogeneous data
Since array stores only a similar type of data so it occupies less amount of memory when compared to the list.List stores different types of data so it requires a huge amount of memory 
The length of the array is fixed at the time of designing and no more elements can be added in the middle.The length of the list is no fixed, and adding items in the middle is possible in lists.

Is it helpful? Add Comment View Comments
 

Ques 74. What is the difference between range and xrange?

Both methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ only when we talk about Python versions.

The difference between range and xrange is as follows:

Range() methodXrange() method
The xrange() method is not supported in Python3 so that the range() method is used for iteration in for loops.The xrange() method is used only in Python version 2 for the iteration in loops.
The list is returned by this range() methodIt only returns the generator object because it doesn’t produce a static list during run time.
It occupies a huge amount of memory as it stores the complete list of iterating numbers in memory. It occupies less memory because it only stores one number at a time in memory.

Is it helpful? Add Comment View Comments
 

Ques 75. What is data abstraction in Python?

In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality. In Python abstraction can be achieved using encapsulation.

Is it helpful? Add Comment View Comments
 

Ques 76. Define encapsulation in Python.

Encapsulation is one of the most important aspects of object-oriented programming. The binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.

Is it helpful? Add Comment View Comments
 

Ques 77. What is polymorphism in Python?

By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on.

Is it helpful? Add Comment View Comments
 

Ques 78. Does Python make use of access specifiers?

Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behavior of private and protected access specifiers.

Is it helpful? Add Comment View Comments
 

Ques 79. How can we create an empty class in Python?

Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keywords and object to this class can be created outside the class itself.

Is it helpful? Add Comment View Comments
 

Ques 80. How can we create a constructor in Python programming?

The _init_ method in Python stimulates the constructor of the class. 

Example:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Output:

John

16

Is it helpful? Add Comment View Comments
 

Ques 81. Define Inheritance in Python?

When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.

Is it helpful? Add Comment View Comments
 

Ques 82. What are the cool things you can do with Python?

The following are some of the things that you can perform using Python:

  • Automate tasks
  • Play games
  • Build a Blockchain to mine Bitcoins
  • Build a chatbot interface combined with AI

Is it helpful? Add Comment View Comments
 

Experienced / Expert level questions & answers

Ques 83. What are the differences between Python 2 and Python 3?

Please refer Python 2 vs Python 3.

Is it helpful? Add Comment View Comments
 

Ques 84. How can we access a module written in Python from C?

We can access the module written in Python from C by using the following method.

Module == PyImport_ImportModule("<modulename>");

Is it helpful? Add Comment View Comments
 

Ques 85. How do you copy an object in Python?

To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().

Example:

fruits = ["apple", "banana", "cherry"]

x = fruits.copy()

print(x)

Output:

['apple', 'banana', 'cherry']

Is it helpful? Add Comment View Comments
 

Ques 86. What is the procedure to install Python on Windows and set path variables?

We need to implement the following steps to install Python on Windows, and they are:

  • First, you need to install Python from https://www.python.org/downloads/
  • After installing Python on your PC, find the place where it is located in your PC using the cmd python command.
  • Then visit advanced system settings on your PC and add a new variable. Name the new variable as PYTHON_NAME then copy the path and paste it.
  • Search for the path variable and select one of the values for it and click on ‘edit’.
  • Finally, we need to add a semicolon at the end of the value, and if the semicolon is not present then type %PYTHON_NAME%.

Is it helpful? Add Comment View Comments
 

Ques 87. Differentiate between SciPy and NumPy?

The difference between SciPy and NumPy is as follows:

NumPySciPy
Numerical Python is called NumPyScientific Python is called SciPy
It is used for performing general and efficient computations on numerical data which is saved in arrays. For example, indexing, reshaping, sorting, and so onThis is an entire collection of tools in Python mainly used to perform operations like differentiation, integration and many more.
There are some of the linear algebraic functions present in this module but they are not fully fledged.For performing algebraic computations this module contains some of the fully-fledged operations

Is it helpful? Add Comment View Comments
 

Ques 88. What is Django? What are different interview questions and answers on Django?

Please refer Django interview questions and answers.

Is it helpful? Add Comment View Comments
 

Ques 89. List the ways we add view functions to urls.py.

  • Adding a function view
  • Adding a class-based view

Is it helpful? Add Comment View Comments
 

Ques 90. What is flask and provide some interview questions and answers?

Please refer Flask interview questions and answers.

Is it helpful? Add Comment View Comments
 

Ques 91. What is the Dogpile effect?

This is defined as an occurrence of an event when the cache expires and also when the websites are hit with more requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begins generating new value.

Is it helpful? Add Comment View Comments
 

Ques 92. Does Python replace Java?

Python alone can't replace Java, whereas a group of programming languages can replace Java but JVM can't be replaced.

Is it helpful? Add Comment View Comments
 

Ques 93. How to crack a coding interview?

It is not that easy as we usually think. Mugging up some programs and executing the same will not work. The ideal way to crack the coding interview, you should be proficient in writing code without the support of any IDE. Don't panic or argue, test your code before you submit, wait for their feedback. Practicing mock interviews will help.

Is it helpful? Add Comment View Comments
 

Ques 94. Top 5 tips to crack the python interview?

The following are the top 5 tips to crack Python interview:

  • Building a proper profile will fetch you better results
  • Setting up your portfolio might impress your interviewer
  • Learn all the fundamentals of Python and OOps concepts as 90% of the interview start from basics
  • Feel free to write code pen and paper
  • Apart from all the above practice is what required.

Is it helpful? Add Comment View Comments
 

Ques 95. What is nested function in Python?

In Python, we can create a function inside another function. This is known as a nested function. For example,

def greet(name):
    # inner function
    def display_name():
        print("Hi", name)
    
    # call inner function
    display_name()

# call outer function
greet("John")  

Output:

Hi John

In the above example, we have defined the display_name() function inside the greet() function.

Here, display_name() is a nested function. The nested function works similar to the normal function. It executes when display_name() is called inside the function greet().

Is it helpful? Add Comment View Comments
 

Ques 96. What is Python Closures?

As we have already discussed, closure is a nested function that helps us access the outer function's variables even after the outer function is closed. For example,

def greet():
    # variable defined outside the inner function
    name = "John"
    
    # return a nested anonymous function
    return lambda: "Hi " + name

# call the outer function
message = greet()

# call the inner function
print(message())

Output:

Hi John

In the above example, we have created a function named greet() that returns a nested anonymous function.

Is it helpful? Add Comment View Comments
 

Ques 97. When to use closures? So what are closures good for?

Closures can be used to avoid global values and provide data hiding, and can be an elegant solution for simple cases with one or few methods.

However, for larger cases with multiple attributes and methods, a class implementation may be more appropriate.

Is it helpful? Add Comment View Comments
 

Ques 98. What is the difference between append() and extend() methods?

Both append() and extend() methods are methods used to add elements at the end of a list.

  • append(element): Adds the given element at the end of the list that called this append() method
  • extend(another-list): Adds the elements of another list at the end of the list that called this extend() method

Is it helpful? Add Comment View Comments
 

Ques 99. How is Multithreading achieved in Python?

Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.

  • Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  • This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.

Is it helpful? Add Comment View Comments
 

Ques 100. What is functional programming? Does Python follow a functional programming style? If yes, list a few methods to implement functionally oriented programming in Python.

Functional programming is a coding style where the main source of logic in a program comes from functions.

Incorporating functional programming in our codes means writing pure functions.

Pure functions are functions that cause little or no changes outside the scope of the function. These changes are referred to as side effects. To reduce side effects, pure functions are used, which makes the code easy-to-follow, test, or debug.

Python does follow a functional programming style.

Is it helpful? Add Comment View Comments
 

Ques 101. What is monkey patching in Python?

Monkey patching is the term used to denote the modifications that are done to a class or a module during the runtime. This can only be done as Python supports changes in the behavior of the program while being executed.

Is it helpful? Add Comment View Comments
 

Ques 102. What is pandas?

Pandas is an open source python library which supports data structures for data based operations associated with data analyzing and data Manipulation. Pandas with its rich sets of features fits in every role of data operation,whether it be related to implementing different algorithms or for solving complex business problems. Pandas helps to deal with a number of files in performing certain operations on the data stored by files.

Is it helpful? Add Comment View Comments
 

Ques 103. What are dataframes?

A dataframe refers to a two dimensional mutable data structure or data aligned in the tabular form with labeled axes(rows and column).

  • data:It refers to various forms like ndarray, series, map, lists, dict, constants and can take other DataFrame as Input.
  • index:This argument is optional as the index for row labels will be automatically taken care of by pandas library.
  • columns:This argument is optional as the index for column labels will be automatically taken care of by pandas library.
  • Dtype: refers to the data type of each column.

Is it helpful? Add Comment View Comments
 

Ques 104. What is regression?

Regression is termed as supervised machine learning algorithm technique which is used to find the correlation between variables and help to predict the dependent variable(y) based upon the independent variable (x). It is mainly used for prediction, time series modeling, forecasting, and determining the causal-effect relationship between variables.

Scikit library is used in python to implement the regression and all machine learning algorithms.

There are two different types of regression algorithms in machine learning :

Linear Regression: Used when the variables are continuous and numeric in nature.

Logistic Regression: Used when the variables are continuous and categorical in nature.

Is it helpful? Add Comment View Comments
 

Ques 105. What is classification?

Classification refers to a predictive modeling process where a class label is predicted for a given example of input data. It helps categorize the provided input into a label that other observations with similar features have. For example, it can be used for classifying a mail whether it is spam or not, or for checking whether users will churn or not based on their behavior.

These are some of the classification algorithms used in Machine Learning:

  • Decision tree
  • Random forest classifier
  • Support vector machine

Is it helpful? Add Comment View Comments
 

Ques 106. What is SVM?

Support vector machine (SVM) is a supervised machine learning model that considers the classification algorithms for two-group classification problems. Support vector machine is a representation of the training data as points in space are separated into categories with the help of a clear gap that should be as wide as possible.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related differences

Python vs JavaPython 2 vs Python 3

Related interview subjects

Flask interview questions and answers - Total 40 questions
OpenCV interview questions and answers - Total 36 questions
Python interview questions and answers - Total 106 questions
Django interview questions and answers - Total 50 questions
©2023 WithoutBook