Top Interview Questions and Answers for Python in 2021

Top Interview Questions and Answers for Python in 2021

Table of Contents

  1. What is python

Python is a high-level, object oriented programming language that is dynamically typed. It is simple and has fairly easy syntax, yet very powerful, making it one of the most popular programming languages for various applications. 

  1. What are the key features of Python 
  • Python is an interpreted language. This means that codes are interpreted line by line and not compiled as is the case in C. See an example below. 
print('This will be printed even though the next line is an error')
Print()#this should return an error

Output:

This will be printed even though the next line is an error

Traceback (most recent call last):

File "<ipython-input-21-1390f7d30421>", line 2, in <module>Print()
NameError: name 'Print' isnot defined

As seen above, the first line was printed, then the second line returned the error. 

  • Python is dynamically typed: This means that the variable type does not have to be explicitly stated when defining a variable and these variables can be changed at any point in time. In Python, the line of code below works perfectly. 

x = 3 #this is an integer

x = ‘h2kinfosys’ #this is a string

x has been dynamically changed from an integer to a string

  • Everything in Python is an object. Python supports Object Oriented Programming (OOP) and that means you can create classes, functions, methods. Python also supports the 3 key features of OOP – Inheritance, Polymorphism and Encapsulation. 
  • Python is a general-purpose language. Python can be used for various applications including web development, hacking, machine learning, game development, test automation etc. 
  1. What are the builtin types in python

Data types in python can be classified into two: mutable type and immutable types. 

For the mutable types, they are sets, dictionaries, lists

For the immutable types, they are tuples, int, floating point numbers, strings, boolean and range. 

  1. What is the difference between a method and a function

A method is usually linked to and called on an object while a function is called generally. Since a method is called on an object, it has access to the object and can alter its form. A function on the other hand basically operates on the object and returns an object.

x = 'h2kinfosys' #this is a string (an object)
len(x) #len() is a function
x.upper() #upper() is a method
  1. What is PEP-8

PEP-8 is a public document that guides programmers on the best practises to write readable and robust programs 

  1. What is a virtual environment

A virtual environment (venv) is an allocation on your system where the python interpreter, libraries and scripts are installed and run. It is good practise to create a virtual environment for a new project because some of the libraries and dependencies may be of varying versions, which could cause conflicts and break your code. 

  1. What is the difference between a list and a tuple

The major difference between a list and a tuple is that a tuple is immutable while a list is mutable. By immutable, we mean its elements can not be changed or updated. A tuple is defined using () while a list is defined using []. 

  1. What are decorators

Decorators are a tool in python that allows you to add more functionality to an object in python. With decorators, you can tweak how a function or method behaves in Python. 

  1. What is the difference between pickling and unpickling 

Pickling is the process of taking a python object, converting it into a string and dumping it in a file for later purpose. Unpickling on the other hand is the reverse case, where the pickle file is retrieved and converted back into a Python object for use. 

  1. How is memory managed in Python

Memory management in Python is done by the Python Memory Manager. The Python Memory Manager allocates memory in the form of private heap space. Memories from all Python objects are stored in the heap space and are inaccessible to programmers. Python also has a garbage collector that reassigns unused memory for the heap space. 

  1. What tools are used to find bug and perform static analysis 

Pylint and Pychecker are the two most popular tools for detecting bugs in your python program. Pylint and pychecker are both open source bug checkers for python, that follows the recommended style by PEP-8 and also indicates the complexity of the bug. 

  1. How do you convert an int type to a string

You change data type in python through typecasting. To convert an int data type to a string, the str() function is called, passing the int as argument. 

  1. What is a namespace in Python

Namespace in python helps to check that the names of objects in a program are unique and can be used anywhere in the program without conflict. The namespace is implemented in a dictionary form such that the names are the dictionary keys while the objects are the dictionary values. Examples of namespaces are local namespace, global namespace and built-in namespace. 

A local namespace is an object name in a defined function. The name is only recognised within the function and gets cleared once the function is called and returns an output. 

A global namespace are names that are used when some packages or modules are imported in a project. The namespace is created at the instance of importing the package and remains defined until the program is executed. 

A built-in namespaces are the names for python built-in functions are names for errors and exceptions.

  1. What is lambda function in Python

A lambda function is an anonymous function that can be defined in one line of expression. One thing differentiates a lambda function from a normal function and that is the fact that the function does not have a name. See an example of a function and a lambda function in python 

#defining a function
def add_numbers(a, b);
    return a + b
#defining a lambda function
lambda a, b: a + b
  1. What is inheritance 

Inheritance is an important feature of OOP where a class can take functionality from another class called the superclass and be reused. The class that is being inherited from is typically called the super class. Conversely, the child class is the class that receives functionality from the super class. 

  1. Define the pass statement in Python

The pass statement also regarded as the null statement is used when you want the python interpreter to skip the line of code. Just like in comments, nothing happens when the pass statement is seen. 

  1. Write a short code to remove duplicates in Python
lists = [1, 2, 2, 3, 4, 4, 4, 4, 5, 6, 6]
uniques = []
for each_element in lists:
    if each_element not in  uniques:
        uniques.append(each_element)
print(uniques)

Output:

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

  1. In python, what are iterators

An iterator is simply a python object whose elements can be traversed. Technically speaking, an iterator is attributed to have the __iter__() method and the __next()__ method. 

  1. What is slicing in Python

Slicing is a way of retrieving a chunk of elements from a list. The start element and stop element are indicated using the format [start:stop]

  1. Write a python code to find the largest number in a list
lists = [1, 23, 430, 12, 200]
largest = lists[0]
for each in lists:
    if each > largest:
        largest = each
print(largest)

Output:

430

  1. What is docstring in Python

Docstrings in python are the strings found after a function, method or module is defined in the Python official documentation. They help to document and further explain how the function, method or module is used. You can access the docstring by using the .__doc__ attribute. 

  1. What is a negative index in Python?

A negative index indicates that the index is counted backward. The last index in a list is negative 1, the second to the last is -2 and so on. Note that for positive indexing, the first index is 0, then 1 etc

  1. Is it compulsory for a python function to return a value?

No, a python function may not have a return statement

  1. What are list and dict comprehensions?

List comprehensions are used to concisely manipulate an already created list to return a new list. See an example below

lists = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#create a list for the square of odd numbers
odd_squares = [x**2 for x in lists if x%2 == 1]
print(odd_squares)

Output:

[1, 9, 25, 49, 81]

Dictionary comprehension works just as list comprehension. Just that in dictionary comprehensions, the key has to be defined. 

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

#create a dictionary for the square of odd numbers

odd_squares = {x : x**2 for x in lists if x%2 == 1}

print(odd_squares)

Output:

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

  1. Is python case sensitive

Yes, python is case sensitive. A variable where one character is in uppercase is completely different from a variable where all the characters are in lowercase. 

  1. What is PYTHONPATH

PYTHONPATH is a virtual environment variable in python that allows you to add more directories for different modules and packages. When you import a module or package, PYTHONPATH is used to check if that module or package exists in the directory. 

  1. How do you copy an object in Python? 

To copy an object in python, you will need to import the copy function from the copy module. The code below shows how to copy a list using the copy function

from copy import copy
lists = [1, 2, 3, 4, 5, 6]
copy_list = copy(lists)
print(copy_list)

Output:

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

  1. What are modules and packages in python?

Modules are simply python files with the .py extension. They can be imported and used in other python programs using the import statement. A package is simply a collection of modules or python files in a particular directory. The collections of the python files in a package is usually accompanied with an __init__.py file. This file informs the python interpreter to treat all modules in the directory as a package. 

  1. What is the self keyword in Python?

The self keyword is used to define an object in a class. While it is optional to define the self parameter in Java, it is important in Python as it helps in differentiating between methods or attributes from a class and that from a local variable. 

  1. What is __init__ in Python

The init is a constructor in Python that is called automatically and helps to allocate a memory to every instance of the class. The __init__ method also helps to differentiate between method or attribute from a class and that from a local variable. See a class Machine created below. Two instances (car and truck) were created based on its fuel type, number of wheels and average speed.  The __init__ method gets called automatically. 

class Machine():
        def __init__(self, fuel, wheels, top_speed):
        self.fuel = fuel
        self.wheels = wheels
        self.top_speed = top_speed
car = Machine('petrol', 4, 200)
truck = Machine('diesel', 8, 60)
Car.fuel
Output: 'petrol'

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class