Top 50 Python Interview Questions For Freshers – Theory Version

Python programming language has become a must skill set on most of the companies’ requirements in a developer. Python programming language has become popular with the machine learning community and is a basic need skill for data scientist/machine-learning developer/deep-learning developer. This article helps you through most of the up to date possible Python interview questions; and covers basic, intermediate and advanced Python interview questions. Here are the top 50 theory question for freshers,

1 – What is Python? What are the benefits of using Python?
Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is open source.

2 – What is PEP 8?
PEP 8 is a coding convention, a set of recommendations, about how to write your Python code more readable.

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

4 – How Python performs Compile-time and Run-time code checking?
Some portion of the Python coding is executed at compile-time, but almost all the checking like name, type and so on, are deferred until code execution. So, if the Python code references a user-defined function that hardly exists, the code will run effectively. The Python code will be unsuccessful just with an exception while the code execution path is not present.

5 – Is Python case-sensitive?
A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In other words, it cares about the case – lowercase or uppercase. Let’s try this with Python.

6 – What are the key features of Python?

  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x=”I’m a string” without error

  • Python is well suited to object-orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private).

  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first-class objects

  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The NumPy package is a good example of this, it’s really quite quick because a lot of the number-crunching it does isn’t actually done by Python

  • Python finds use in many spheres – web applications, automation, scientific modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.

7 – What is PYTHONPATH?

It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

8 – How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

9 – What are the built-in types of python?

There are two categories of ‘types’ present in Python, which is mutable and immutable.

Mutable built-in types

  • List
  • Dictionary
  • Set

Immutable built-in type

  • String
  • Number
  • Tuple

10 – Explain About Indexing And Slicing Operation In Sequences?

Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequences. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.

11 – What is type conversion in Python?

Type conversion refers to the conversion of one data type into another.

int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
tuple() – This function is used to convert to a tuple.
set() – This function returns the type after converting to set.
list() – This function is used to convert any data type to a list type.
dict() – This function is used to convert a tuple of order (key,value) into a dictionary.
str() – Used to convert integer into a string.
complex(real, imag) – This function converts real numbers to complex(real, imag) numbers.

12 – What is the difference between list and tuples in Python?
Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists since the value of the items stored in the list can be changed whereas the tuple is immutable and the value of the items stored in the tuple can not be changed.

List in python is implemented to store the sequence of various types of data. However, python contains six data types that are capable of storing the sequences but the most common and reliable type is list.

Difference between list and tuple

13 – What are negative indexes and why are they used?

To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on.

When we use the index to access elements from the end of a list, it’s called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’. The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are called negative indexes.

14 – Can Dictionary have duplicate keys?

Python Doesn’t allow duplicate keys however if a key is duplicated the second key-value pair will overwrite the first as a dictionary can only have one value per key.

For eg :

my_dict={'a':1 ,'b' :2 ,'b':3}
 {'a': 1, 'b': 3}

15 – What happens if we call a key that is not present in a dictionary and how to tackle that kind of error?

It will return a Key Error. We can use the get method to avoid such conditions. This method returns the value for the given key if it is present in the dictionary and if it is not present it will return None (if get() is used with only one argument).

Dict.get(key, default=None)

16 – what is the difference between input and raw_input?

There is no raw_input() in python 3.x  only input() exists. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). In python 3.x  We can manually compile and then eval for getting old functionality.

17 – How does break, continue and pass work?

Python (Break, Pass, Continue)

18 – What is namespace in Python?

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

19 – What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

20 – What is the purpose of is, not and in operators?

Operators are special functions. They take one or more values and produce a corresponding result.

is: returns true when 2 operands are true  (Example: “python” is ‘python’)
not: returns the inverse of the boolean value
in: checks if some element is present in some sequence

21 – What is the parameter passing mechanism in Python?

Python consists of two-parameter passing mechanism named as-

  • Pass by references: Every parameter (argument) is passed “by reference” to the functions by default. However, in case you modify the value of the parameter in the function, the impact can also be reflected in the called function.
  • Pass by value: The pass by value is that at whatever time you pass the parameters to functions which are of the type such as strings, numbers, tuples. This is due to the immutable nature of them.

22 – What does this mean: *args, **kwargs? And why would we use it?

Basically *args is applied when you are not sure about the number of arguments that are going to be passed to a function, or if there arises a need to pass a stored list or tuple of arguments to a function.

Whereas **kwargs is used when you are unsure about the number of keyword arguments that will be passed to a function, or it can be also used to pass the values of a dictionary as keyword arguments. The identifier args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

23 – What is MRO in python?
Method resolution order or MRO refers to when one class inherits from multiple classes. The class that gets inherited is the parent class and the class that inherits is the child class. It also refers to the order where the base class is searched while executing the method.

24 – What is typecasting in python?
The entity that changes the data types from one form to another is known as typecasting. In programming languages, it is used to make sure the variables are processed in the correct sequence by the function. E.g., while converting an integer to string.

25 – What is the type () in Python?
The built-in method which decides the types of the variable at the program runtime is known as type() in Python. When a single argument is passed through it, then it returns given object type. When 3 arguments pass through this, then it returns a new object type.

26 – Does Python have OOps concepts?

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as procedural as well as structural language.

27 – 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.

28 – What is __init__?

 __init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

29 – Mention what are the rules for local and global variables in Python?

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

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

30 – What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional.  It helps to differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

31 – How are instance variables different from class variables?

Instance variables are usually made locally within a class to refer to an object of the class. A class variable is made globally within a class as well as can be accessed in every instance of the class.

Class variables are stated with keyword static as well as Instance variables are stated with static keyword.

Class variables can be obtained anywhere in the class while an instance variable can be obtained in a specific object of the class.

Class variables can be obtained by making use of the class name of object reference. Instance variables can be obtained only with the help of object reference.

32 – Does python have a private keyword in python? how to make any variable private in python?

It does not have a private keyword in python and for any instance variable to make it private you can __  prefix in the variable so that it will not be visible to the code outside of the class. Eg, 

Class A:
    def __init__(self):

    def printNum(self):
        print self.__num

33 – Explain Inheritance in Python with an example.

As Python follows an object-oriented programming paradigm, classes in Python have the ability to inherit the properties of another class. This process is known as inheritance. Inheritance provides the code reusability feature. The class that is being inherited is called a superclass and the class that inherits the superclass is called a derived or child class. Following types of inheritance are supported in Python:

  • Single inheritance: When a class inherits only one superclass
  • Multiple inheritance: When a class inherits multiple superclasses
  • Multilevel inheritance: When a class inherits a superclass and then another class inherits this derived class forming a ‘parent, child, and grandchild’ class structure
  • Hierarchical inheritance: When one superclass is inherited by multiple derived classes

34 – Does python make use of access specifiers?

Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behaviour of protected and private access specifiers. 

35 – What is the use of try, except, finally and raise in Error Handling.

Python makes use of try, except and finally blocks for error handling. Try block is used to execute the code until an error occurs. We can make use of an except block to receive control which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the finally block is executed. Raise may be used to raise your own exceptions.

In case of error handling, Python uses try, except, finally and raise blocks.

  • Use of try block helps in executing the code until an error arises.
  • Use of the except block helps in getting the control which further gets control after each and every error, or simply you can utilize particular exception handling blocks for different error types. Control is moreover moved to the suitable except block.
  • The finally block is executed in each case.
  • You can raise our own exception as well with the help of raise block.

36 – Name some standard Python errors you know?

TypeError: Occurs when the expected type doesn’t match with the given type of a variable.
ValueError: When an expected value is not given- if you are expecting 4 elements in a list and you gave 2.
NameError: When trying to access a variable or a function that is not defined.
IOError: When trying to access a file that does not exist.
IndexError: Accessing an invalid index of a sequence will throw an IndexError.
KeyError: When an invalid key is used to access a value in the dictionary.

We can use dir(__builtin__) to list all the errors in Python.

37 – What is a Python module?

Modules are independent Python scripts with the .py extension that can be reused in other Python codes or scripts using the import statement. A module can consist of functions, classes, and variables, or some runnable code. Modules not only help in keeping Python codes organized but also in making codes less complex and more efficient. The syntax to import modules in Python is as follows:

import module_name   # include this code line on top of the script

38 – What do you understand by the term Deep copy?

To store the values, which have already been copied, deep copy is used. The reference pointers to the object are not copied by the deep copy. It simply helps in making reference to the object and the new object that is pointed by some other object gets stored. The changes are made in the original copy that will not affect any other copy while using the object. The Deep copy makes execution of the program slower due to making certain copies for each object that is being called.

39 – What are docstrings and comments?

Docstring refers to a documentation string for a function. It must be defined at first, within a function that defines it. Though there’s not much difference between the two, one could put it this way– Docstrings are for documentation, however, comments are for code readers/reviewers.

40 – Explain garbage collection in Python?

Garbage collection generally depends on which implementation. In particular, CPython uses reference counting, and a creative cyclic collector that’s both generational and utilizes its reference count itself to detect continuously iterating loops or cycles.

41 – Key Differences Between Python 2 and Python 3

  • Python 3 syntax is simpler and easily understandable whereas Python 2 syntax is comparatively difficult to understand.
  • Python 3 default storing of strings is Unicode whereas Python 2 stores need to define Unicode string value with “u.”
  • Python 3 value of variables never changes whereas in Python 2 value of the global variable will be changed while using it inside for-loop.
  • Python 3 exceptions should be enclosed in parenthesis while Python 2 exceptions should be enclosed in notations.
  • Python 3 rules of ordering comparisons are simplified whereas Python 2 rules of ordering comparison are complex.
  • Python 3 offers Range() function to perform iterations whereas, In Python 2, the xrange() is used for iterations.

42 – What are the applications of Python?

Below find the applications of Python:

  • GUI based desktop applications.
  • Web and Internet Development.
  •  Scientific and Numeric Applications.
  • Software Development Applications.
  • Applications in Education.
  • Applications in Business.
  • Database Access.
  • Network Programming.
  • Games, 3D Graphics.
  • Other Python Applications.

43 – 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 possess 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 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.

44 – Is Python platform independent?

Yes, there are some modules and functions in python that can only run on certain platforms.

45 – What is the python syntax for switch-case statements?
Python doesn’t support switch-case statements. You can use if-else statements for this purpose.

46 – Is python statically typed or dynamically typed?
Dynamic. In a statically typed language, the type of variables must be known (and usually declared) at the point at which it is used. Attempting to use it will be an error. In a dynamically typed language, objects still have a type, but it is determined at runtime. You are free to bind names (variables) to different objects with a different type. So long as you only perform operations valid for the type the interpreter doesn’t care what type they actually are.

47 – What is GIL? What does it do? How does it impact concurrency in Python? What kinds of applications does it impact more than others?
Python’s GIL is intended to serialize access to interpreter internals from different threads. On multi­core systems, it means that multiple threads can’t effectively make use of multiple cores. (If the GIL didn’t lead to this problem, most people wouldn’t care about the GIL ­ it’s only being raised as an issue because of the increasing prevalence of multi­core systems.) Note that Python’s GIL is only really an issue for CPython, the reference implementation. Jython and IronPython don’t have a GIL. As a Python developer, you don’t generally come across the GIL unless you’re writing a C extension. C extension writers need to release the GIL when their extensions do blocking I/O, so that other threads in the Python process get a chance to run.

48 – Explain the disadvantages of python
Disadvantages of Python are: Python isn’t the best for memory-intensive tasks. Python is an interpreted language & is slow compared to C and C++. 

49 – What is Rstrip() in Python?

Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end.

The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.

The signature of the rstrip() is:

str.rstrip([char sequence/pre> #Example

test_str = 'Programming    ' # The trailing whitespaces are excluded

50 – What is whitespace in Python?
Whitespace represents the characters that we use for spacing and separation.
They possess an “empty” representation. In Python, it could be a tab or space.

51 – What is pip and when is it used?
pip is a package management system and it is used to install many python packages. Eg. Django, mysql.connector

pip install package_name
pip install Django 2020