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.


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


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)



('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


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.


str = "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.


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.


txt = "welcome to the withoutbook"

x = txt.split()



['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:


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)) { something with line...

where in Python you're forced to write this:

while True:
  line = f.readline() if not line:
  break 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:

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:

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: 
x = 0 # Default value of the 'x' configuration setting 
import config
config.x = 1
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):
  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): 
  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:
  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?


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!") 
'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():
  def b():
    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)

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

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

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
Generative AI interview questions and answers - Total 30 questions
Django interview questions and answers - Total 50 questions
©2023 WithoutBook