Top 100 Python Interview Questions and Answers in 2021

Python programming language is used by software engineers all across the globe. Python is said to be dynamic in nature. Compared to other programming languages like C#, C++, and Java – Python programming is flexible in terms of structure and usability. Python is also compatible with open-source frameworks. This makes it the first choice for many developers.

The industry currently has many positions opened for python developers. Here is a curated list of python interview questions that will help you in a python interview. These interview questions cover all levels from basic to advanced. 

Table of Contents

Things to keep in mind for your Python interview

The preparation for your python interview needs to be crisp. The basic foundations will help you answer all the python interview questions. The idea is to share the knowledge that you have about the programming language. Interview questions can vary from simple definition to complex code writing or deduction of a logic for a problem.

It is important to become aware of the fundamental concepts. Most python interview questions target your basic understanding of the language. Use this guide for interview questions and answers to help you prepare for your python interview.  Here is a quick pointer for the interview:-

  1. Answer the questions confidently
  2. Give examples to support your answer
  3. Preparation should include both theoretical and practical aspects
  4. Revise most frequently asked questions on python

Top Python Interview Questions and Answers 

Python interview questions and answers

Before you start applying for your next Python interview, make sure you go through as many questions as possible. 

1. Draw a comparison between Python and Java

Answer:

Programming language and its featuresNXlXlIchOLwG2oKHnnMmHQ9W7ug6GBc7wTiWQXZG15Z5SwiEI HE8Mv6ygA OrDcEDmBhEf4SNuffI2 kDOK3nqCd4S2313echHl agPNk8dSwpTJgfQOesCnbK7FIjyAALnsRHZ
(Features of Python)
WCY2oF bNqhS3dfFnOjvlPEHeatcTxpy6yKYy4WbmdXCjDgoVj3wEJixWUSyosX7HV7hyTjru DlKe pqYK98UdjpEM1AairAEIDXD
(Features of java)FrameworkDjango, Flask (limited frameworks)Hibernate, Spring (more available)Key FeaturesDynamic typingFast developmentMemory managed in python is simpleObject oriented programmingNo specific platform requiredMemory management is automaticRobustObject oriented programmingCodeLess code requiredMore code requiredSpeedUsing interpreted language makes it slightly slowerNo interpreted language used here. Fast, high compiling power
SyntaxCloser to regular languageSpecific and has a lot of rules.
DatabaseMore loosely held database can be used. Unstructured DBs like – MongoDB are used often.JDBC (Java Database connectivity) is used.

2. List the key features of python

  • Dynamic coding – python is dynamically typed
  • Interpreted programming language
  • Object oriented programming 
  • Pre-defined functions in python
  • Function is a first class object in python
  • Shallow copy creation 
  • Deep copy creation

3. What is a dictionary in Python?

A dictionary in python has a bunch of key value pairs. They are used to depict arrays. 

For e.g.,

a = {
      <key>:<value>, <key>:<value,......
      }

4. Can you write an efficient code to count the number of capital letters in a file?

The answer to this question is given below: – 

with open('sample.txt') as lettercount:
    count = 0
    text = lettercount.read()
    for character in text:
        if character.isupper():
            count += 1
print(count) 

5. Write a program to sort a numerical list in Python programming language. 

Here is a short snippet that can be asked in your python interview: – 

num_list = [4, 5, 20, 10]numbers.sort()   
print(numbers) 
Output: 4, 5, 10, 20

6. Demonstrate reverse a list in Python?


Use the following code sample to answer python interview questions: – 

List_1 = [banana, apple, mango]
List_2 = List_1.reverse()
print (List_2)
Output: [mango, apple, banana]

Python Interview Questions and Answers 

7. How will you remove the last object from a list using a Python code?

Use the following sample to remove the last object in python from any list:-

ListAnimals = [‘Tiger’ ,‘Cheetah’, ‘Lion’,‘Leopard’]
del ListAnimals[-1]
print(“List after removing last element:”, ListAnimals)
Output: List after removing last element: [‘Tiger’, ‘Cheetah’, ‘Lion’]

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

When you see a list in an array, the last element is denoted by ‘-1’ and ‘-2’ will be used to call the second last element in the array or list. It is used to call, print, or use the value of the element within the program. The negative indexes are common in python. 

See also  Top 100 MySQL Interview Questions And Answers

9. What are split(), sub(), and subn() methods in Python? Answer the following question with syntax. 

  1. Split() – a split function is used to separate a string depending on the pattern. 

Syntax – re.split (pattern, string, maxsplit=0, flags=0)

  1. Sub() – used to find the pattern of one string in another.

Syntax – re.sub (pattern, repl, string, count=0, flags=0)

  1. Sunn() – same as sub(), in addition it also gives a value.

10. How is range() and xrange() different from one another?

Answer:

range()xrange()
It used to return an object range. It is used to return the generator object with the help of looping. It only loads the items of a particular range.
Takes up more memoryMemory management is optimal
Speed is relatively slowSpeed is relatively fast

11. What is pickling and unpickling in python?

Pickling is used as a serializing tool for objects. An object hierarchy is formed with the help of this technique. Unpickling is the reversal of the same process. When the hierarchy is removed for the python objects, it is referred to as unpickling. 

12. What is a map function in Python?

map() is a predefined function. This helps execute the python objects in an iterative process without using any loops. map() depicts the functional programming style. It is used when a transformation function needs to be applied. 

13. Write a code to get the indices of N maximum values from a NumPy array.

Let us look at the following block of code that will give the indices for N maximum values from NumPy array.

numbers = np.array([8, 9, 3, 5, 4])
n = 2
indices = (-numbers).argsort()
print(indices)

Output
[8 9]

14. What is a Python module?

A module is nothing but a file that comprises the code. It will have the functions, classes and objects pertaining to your code. All the python objects and data will have a scope within the file.

Top Python Interview Questions and Answers

15. What do file-related modules in Python do? Can you name some file-related modules in Python?

There are many built in types of modules that deal with handling files. One can create files and directories, find the patterns in filenames, go through the directory tree, delete files and modules, copy & move files, etc. 

16. Explain the use of the ‘with’ statement in python.

When you use it in python code, you basically restrict the scope of the object within the given block. The behaviour of the objects can be used and exploited within the given block only.

17. Explain all file processing modes supported in Python.

Answer for the modes of opening a file are:-

  • r – file to be opened
  • w – file for writing
  • x – open if already exists
  • a – appending to an existing file
  • b – binary mode
  • t – text mode 
  • +r – reading and writing of the file

18. Is indentation optional in Python?

Yes, indentation is optional. Also, python IDEs are not case sensitive. Python is flexible. 

19. How are Python arrays and Python lists different from each other?

Let us examine the answer closely: – 

ListArray
Heterogenous mixture of variablesHomogenous mixture of variables
Need not import any moduleNeed to import modules
Arithmetic operations can not be performedArithmetic operations can be performed
Printing list is easyLoops are required for printing
Large python memoryCompact python memory

20. Write a code to display the contents of a file in reverse

Use this sample snippet to answer the question :

namefile=input("Enter file name: ")
for line in reversed(list(open(namefile))):
print(line.rstrip())

21. Differentiate between NumPy and SciPy.

Answer: 

NumPySciPy
Numerical PythonScientific Python
Homogenous data in arraysCollection of tools for mathematical operations
Used for sorting, elementary functions in pythonUsed for integration, differentiation and other complex scientific calculations

22. Can we make multiline comments in Python?

There are no multi-line comments in python. 

23. What is __init__ in Python?

It is a reversed method. Also known as a constructor. As soon as an object is created, the following method is called. The variables are automatically initiated in the block. 

24. What do you understand by Tkinter?

There is a toolkit called the Tk GUI toolkit. Python is obliged to this particular toolkit. The calls from Tkinter are converted into TCL commands which are further processed in the python interpreter. 

25. Is Python fully object oriented?

Python can be used to create object oriented programming. However, it is not entirely object oriented by itself.

26. What is the lambda function in Python?

When a function is declared without any name it is called the lambda function. There is no need to put arguments to this function. 

Below lines will answer the questions related to the lambda function:-

a = lambda b:b+15
print(a(10))
Output = 25

27. What is a self keyword in Python?

“Self” enables access to all the variables and methods in a block of code. The objects can have their own set of functions and elements. 

28. What is a control flow statement in Python?

This is one of the most frequently asked questions. There are three control flow statements:-

  1. Sequential
  2. Selection
  3. Repetition

Sequential: step-by-step processes are part of this control flow. For e.g.

a=2
b=3
c=a+b
print(a)
Output = 5

Selection: these are conditional and are dependent on decision making. 

  • Simple if statements  – these are general-purpose statements. 
Conditional decision
  • If else statement
If else statement
  • Nested if 
Nested If

Repetition: this is enabled by using loops: for loop, while loop

  • For loop
For loop
  • While loop
While loop

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

Answer: 

Append()Extend()
One element is added at the end of the listMultiple elements can be added at the end of the list.
Single element is taken at a timeTakes multiple elements in an iterable manner. 
Syntax: nums.append(value)Syntax: nums.extend(values)

30. What is the purpose of the PYTHONPATH environment variable?

It is used to append directories into the environment. When a user creates his or her own modules, pythonpath is used to integrate it. It can hold string data types. It helps in locating the python standard library. 

31.  What are loop interruption statements in Python?

Break and continue are two loop interruption statements. Here is a flow chart to depict their actions. Depending on whether the function returns true or false, the cases are executed. 

loop interruption statements in Python

32. What is docstring in Python?

This answer will cover the basics on docstrings in python. Docstring helps in documentation (pep 8 in python) for coding using the following:-

  1. Functions
  2. Modules
  3. Classes

Here are some docstrings that are used in Python:-

  • _doc_ for primitive data types
    • Multi-line
    • Single line 
  • Help function 
Python module:
def hello_world(): 
    """Docsting Demo"""
return None
# printing using __doc__ method 
print "Using __doc__ method:"
print hello_world.__doc__ 
# printing using help function 
print "HelpFunction:"
help(helloworld)

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

When programming is done through construction of methods and functions it is termed as functional programming. Python is not a functional programming language yet it uses some aspects of it. Methodologies followed in functional programming.

Develop → Debug and test→ Understand

Here are few methods to implement functional oriented programming:-

  1. Functional purity
def func_sum(m):
    a= 0
    for m in list:
        a+= m
    return a

This can be represented as sum (m) in python, without having to type so many lines. 

  1. Loops Reduced

Using python one can write just a single statement to run a loop. 

  1. Recursion 

Division of issues into small parts is called recursion. Python uses recursion to break down the problems. 

34. Write a program in python to check whether a given string is a palindrome or not, without using an iterative method. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam, nurses run, etc.

Sample:

inputstring = inputstring.casefold()
reverseString = reversed(inputstring
if list(inputstring) == list(reversString):
   print(" palindrome.")
else:
   print(" not a palindrome.")

35. Do we need to declare variables with data types in Python?

No, we do not need to declare the data type of a variable.

36. What is the purpose of PYTHONSTARTUP, PYTHONCASEOK, and PYTHONHOME environment variables?

PYTHONSTARTUPPYTHONCASEOKPYTHONHOME
Has the initialization path with the source code. It runs on starting the python interpreterWindows uses this. It looks for statements that are not case sensitive. Enables switching between the other two variables. 

37. Write a Python program to count the total number of lines in a text file.

file = open("gfg.txt","r") 
Counter1 = 0
Text = file.read() //read the file
List1 = Text.split("\n") //stores the number of lines
for j in List1: 
    if j: 
        Counter1 += 1
print (Counter1)

38. Why would you use NumPy arrays instead of lists in Python?

Follow are the reasons to use NumPy arrays:-

  1. Less space is utilised
  2. Can perform complex operations
  3. It is faster 

39. What is the easiest way to calculate percentiles when using Python?

It is just a one-line code. Make sure you have the Numpy library.
Syntax:- 

numpy.percentile(arr, n, axis=None, out=None)

40. Is multiple inheritance supported in Python?

Yes, multiple inheritance is supported in python. 

Sample code

class case1(object): 
    def __init__(self): 
        self.c 3 = "python"
        print("case1") 
class case2(object): 
    def __init__(self): 
        self.y = "java"        
        print("case2") 
class Derived(case1, case2): 
    def __init__(self): 
       case1.__init__(self) 
      case2.__init__(self) 
        print("Derived") 
    def printStrs(self): 
        print(self. c 3, self.y) 
ob = Derived() 
ob.printStrs() 

41. What is monkey patching in Python?

Monkey patching has the capabilities of changing the code at run time. It is a way to extend the python program or modify the code depending on the use case. 

See also  Top 100 MySQL Interview Questions And Answers

42. Can you give an example of the split() function in Python?

sample_text= "Today is beautiful day"
spliting_text = sample_text.split()
print(spliting_text)
Output - [‘today’, ‘is’, ‘beautiful’, ‘day’]

43. Which data types are supported in Python?

  1. Integers
  2. Floating point numbers (decimal numbers)
  3. Complex Numbers
  4. Strings or Characters
  5. Boolean – true or false

44. What is the difference between lists and tuples?

ListTuples
mutableimmutable
Slower during run-timeFaster during run-time
Perfect for insertion/deletionUtilised for handling elements
Wide range of built in types of functionsNo built in methods

45. How is memory managed in Python?

Memory is automatically managed in Python. The python memory manager has the following elements. Memory management is important for the performance of the application. The python private heap space allocated for each process needs to be managed efficiently. 

  1. Garbage Collector (GC): Helps in getting rid of unwanted elements and frees up memory from time to time. It creates a python private heap space for a process to run. 
  2. Reference Counting: Python objects that are being referenced need to be counted. This counting is important because any object that is being referenced can be removed at a later stage to clear up some space. 
  3. Heap Memory: Every line written has a function to perform for which a certain memory is allocated. This allocation can also be done dynamically by the programmer.

46. What is a string in Python?

All characters put together form a string. For example “chess” is a string. Strings need to be defined at the beginning of a program in python. Post which they can not be changed unless functions are used to modify them. 

47. What is slicing in python?

When one wishes to take elements from one index to another it is denoted as slicing. 

import numpy as list_arr
m = list_arr.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:4])
Output of the following: 2, 3, 4, 5

48. What is the index in Python?

It is an inbuilt function. It looks for the element from beginning to end to return the smallest index.

Syntax: nameofList.index(element, start, end)

49. How many basic types of functions are available in Python?

There are three basic types of functions:-

  1. Built in functions
  2. User defined functions
  3. Anonymous functions

50. What is the return keyword used for in Python?

The ‘return’ keyword is used to call the value of the variable.

51. What is “Call by Value” in Python?

When a variable is created within the function, its value is not modified. There is always a deep copy (different from shallow copy) of the original element available at all times. 

Call by Value in Python

52. What is “Call by reference” in python?

A variable is said to be called by reference when its original value is susceptible to change. 

Call by Reference in Python

53. What is the return value of the trunc() function?

trunc() is a predefined function that rounds of the digits to the nearest decimal place that is specified. 

For eg. trunc(13.14) – will return 13

54. What is the statement that can be used in Python if the program requires no action but requires it syntactically?

The ‘pass’ statement is used when there are no actions being taken. Often syntactical situations arise in python coding. Especially after a conditional block.

55. Is it mandatory for a Python function to return a value?

Yes, python function will always return a value regardless of being called explicitly or not. 

56. What does ‘continue’ do in Python?

Continue is an interruption in a loop that forces the loop to run unless terminated by false expression. 

57. What is the purpose of id() function in Python?

For a given object when id() is used, it gives a unique id. As soon as an object is created, an id is assigned to it right away. Can be used for numbers, list, string and class. 

Syntax: id(object)

Top Python Interview Questions and Answers

58. What does the *args do in Python?

*args is used for non-keyword arguments. It is used when arguments need to be passed in a function. In case the developer is unsure of the data type of the arguments, then *args are used. 

59. What does the **kwargs do in Python?

**kwargs is used for keyword arguments. The length of the variable pertaining to the keyword can be passed using **kwargs.   

60. Does Python have a Main() method?

There is no exclusive main() function required in python as the interpreter deals with code in a sequential manner. 

61. What does the __ Name __ do in Python?

_Name_ is a built in function. It is a replacement for main() in python in terms of the functionality.  For e.g. – print type (_name_)

62. What is the purpose of “end” in Python?

The end is a default function that gets executed after the print() function. It was implemented in Python 3. It helps the python interpreter understand what is to be displayed after the print function.  Syntax: end= “desired character.”If a space is put in the end character then after the print function is executed a space is appended.

63. When should you use the “break” in Python?

Break is an interruption statement used in loops. This will allow you to break the loop in case some condition is not required to be executed further. 

64. What is the difference between pass and continue in Python?

‘Continue’ allows the loop to run after checking the condition. Whereas the pass statements does nothing and lets the code continue sequentially. ‘Pass’ is called an empty statement.

Execute the following code to understand the difference between pass and continue. 

m = "quick"
# Pass statement 
for i in m: 
    if i == 'c': 
        print('Pass ') 
        pass
    print(i) 
print() 
# Continue statement 
for i in m: 
    if i == 'c': 
        print('Continue ') 
        continue
    print(i) 
Output:
q
u
i
c
Pass
k
q
u
i
Continue
k


65. What does the len() function do in Python?

It is used to find the number of objects. In other words it returns the length of the variable (in case it is a string variable). 

Sample python code

string_name= ‘work’
length_str=len(string_name)
print(string_name)

Output: 4 

66. What does the chr() function do in Python?

The inbuilt function chr() basically takes a numerical value and returns the corresponding ASCII character for it. For e.g chr (98) wil give a value of “B” 

67. What does the ord() function do in Python?

The inbuilt function ord() returns the unicode value of a given character that is passed in the function. For eg. ord(9) will give a value of 57. 

68. What is Rstrip() in Python?

rstrip() is a built-in function that helps in the removal of trailing characters. For example, space is the default character for this function that is removed in all cases.

text_words= ‘a&b&c&d&e’final_out=text_words.rstrip(‘&’)
Output : a b c d e

69. What is whitespace in Python?

The characters that allow space to be created in the code is called the whitespace. 

70. What is isalpha() in Python?

This function checks the strings if they are alphabets. It returns true for such cases.

For e.g.
text_words= “hello”
print(isalpha(text_words))
Output - true

71. What does the Title() method do in Python?

The title() function converts the first letter of each word in a string. Following is an example of  the same.

72. What are the built-in types available in Python?

  1. Value testing 
    1. None & false
    2. Decimals, fractions
    3. Empty sequences
  2. Boolean
    1. And
    2. Or
    3. Not
  3. Comparisons
    1. Lesser than <
    2. Greater than >
    3. Less than or equal to <=
    4. Greater than >=
    5. Equal ==
    6. Not equal !=
    7. Is
    8. Is not
  4. Numerics – int, float
  5. Bitwise operators

73. Which package is the fastest form of Python?

The latest python 3.7 is the fastest form of python to this date. 

74. What is GIL in the Python language?

Global interpreter lock is a lock that enables just one thread at a time. This is useful in memory management. There will be fewer issues pertaining to memory leaks. 

75. How is Python thread safe?

The thread is said to be in a safe state when it can not be changed frequently. As the GIL prevents python from deploying more than one active thread at a time. It creates a safe thread that can help with processing. 

76. What is the set object in Python?

A list consisting of elements that are not in any specific order is part of the set object. It contains unique elements without any replications or repetitions. It helps in using the mathematical concepts of sets and functions to depict intersections, union, and symmetric differences.

One of the sample python modules:- 

set1 = {5, 2,4}
print(set1)
set1 = {3.0, "Pink", (5, 2, 4)}
print(set1)

Output: {3.0, (5,2,4), “Pink”}

Python Interview Questions and Answers 

77. What are Attributes and Methods in a Python class?

Attributes help with defining the methods for the objects. It helps in taking care of classes (there is parent class & derived class). Here are some of the methods.

  1. delattr() – helps in deletion of an attribute. After deletion, the attribute can not be accessed. 
  2. getattr() – Can get hold of the attribute for an object
  3. setattr() – If there is no attribute present, it automatically creates it at the same instance. 
  4. hasattr() – used to verify if the attribute is present or not.

78. What is Inheritance in Python programming?

A key concept in OOPs is inheritance. As his name suggests the idea is to “inherit” a certain class directly with no changes at all. The below example depicts the derivation of one class through another. The new class (or the second class in this case) is the child class. And the main class which is being inherited is the parent class. 

See also  Top 100 MySQL Interview Questions And Answers

One of the sample python modules:-

class FirstClass:
  Body of first class
class SecondClass(FirstClass): // the second class is the derived class
  Body of second class

79. What is Composition in Python?

Composition helps in establishing relationships. It can create objects of a certain object type. There is cardinality that is often expressed for composition.  

  1. Number 
  2. The * symbol
  3. Range 1*4

80. What are Errors and Exceptions in Python programs?

Errors have the potential to halt the processing of a code. In certain cases there might be potential errors that an interpreter detects, at that point of time an exception is raised to surpass the issue. There are 2 types of error. 

  1. Logical  – these errors occur due to some faulty logic in the code. Let’s say an infinite loop is enabled by wrong logic.
  2. Syntax – these errors occur due to syntax issues. It could be a missing bracket or misplaced keyword. 

Let us look into some exceptions that can be raised during the processing of a code

NameDescription
Type ErrorWrong data type is evoked for a variable.
Name ErrorUndefined variables often lead to this issue.
Memory ErrorOut of memory issues.
Key ErrorWhen the key is missing for the dictionary.
Import ErrorThe import file is missing.
Index ErrorIncorrect indices are returned.
Assertion ErrorFailure of assertions
Attribute ErrorFailure in assignment of an attribute.

81. What are Python Generators?

Generators in Python are used to automate tough tasks in python. When there is a need to run a class with __iter__() and __next__() and also raise alerts generators are used as it takes a lot of time and effort to make it happen using regular methods or functions. Generators are used to implement iterations for any repetitive scenarios. 

Creating generators

It is similar to defining a function in python. It is usually constructed using ‘yield.’ It basically replaces the functionality of the ‘return’ attribute. There is still a difference in functionalities. Return usually ends the function or method that invokes it. Whereas, yield simply pauses the processing for some time. 

82. What are decorators? When is the Python decorator used?

Decorators are used to modify and extend the functions or methods in python. This does not cause any significant long term changes. The changes are still temporary. There is an opportunity to add more functionality to a class using a decorator. Following are instances where decoration can be used: 

  1. Caching
  2. Limiting the rate
  3. Timing functions
  4. Instrumentation functions
  5. Authentication 
  6. Access control
  7. Logging 

Python Interview Questions and Answers 

83. What are Closures in Python? 

After a function completes its execution, there is a free environment variable available that can be accessed by a function that is nested. These are closures in python. Following are more details on the behavior of the closures. Answer this question as simple points as mentioned below. 

  1. Comes from an enclosed function
  2. Can access a variable that is free
  3. Nested functions

Any variable that is not bound by the local variables’ scope of function or class is called a free variable. In order to avoid incorporating global variables and data hiding, closures are used very often in python

84. What is the use of globals() function in Python?

Current global symbols table has a dictionary that can be accessed using the globals() function. It is a data structure. It does not need any parameters to be passed. It also returns the dictionary. The variables used here are automatically part of the global variables with global scope. Types of symbol tables:-

  1. Global symbol table – stores the elements that are within the local scope. It is usually available through globals()
  2. Local symbol table –  stores the elements that are within the local scope. It is usually available through locals()

Syntax: globals ()

Source Code sample:

first_num= 100
globals()[first_num] = 112
print(first_NUM)

85. Explain the use of session in Django framework?

With help of sessions Django keeps the check on the site and the browser. As in when the browser connects to the site, certain data is generated. This is required to be stored and sessions enable this operation. A session id is created by Django for a cookie. This gets stored in the database. The cookies are saved as a file. 

86. Explain what Flask is and its benefits?

It is a framework that enables python coding. It has a wide range of benefits that make it suitable for python programming. There is documentation (like the pep 8 in python) available for its users. There are also many options for developers when it comes using flask as the primary framework for their coding. Here are the benefits of flask 

  1. Can be deployed to production with ease
  2. Automated RESTful services
  3. Ninja Template
  4. Secures cookie
  5. Compatible with google engine
  6. APIs are readily available
  7. Vast documentation (for e.g pep 8 for python)
  8. Unit test support available

87. Discuss Django architecture.

Django follows a Model-View-Controller (MVC) model. In coding there are three key aspects that are covered in terms of logic – input, business and interface. These three components need to be handled carefully. There has to be an easy flow of data from all three layers of the model. Django enables this with great care. Let us look into the depth of the model.

  1. Model:This contains the interface between the front-end and the database. The actual logic is implemented here. This is the interface that interacts with the user the most.  
  2. View: This has the UI logic, that takes care of how things look like. The HTML and CSS parts of the code are presented here.
  3. Controller: It is the primary unit that regulates all the other parts of the system. 

88. Explain how you can set up the Database in Django

Django is an open source framework that allows python programming in its platform. Here are the steps to set up a database in the Django framework. 

  1. Step 1: MySQL installation
  2. Step 2: Create project skeleton in Django
  3. Step 3: Edit the settings 
  4. Step 4: Installation of the Database connector
  5. Step 5: Start creating the Database
  6. Step 6: Conjoin the Database to the Application
  7. Step 7: Check the connection and test it

89. Write a program to produce Fibonacci series in Python

Here is the fibonacci series : 0, 1, 1, 2, 3, 5, 8, 13…

Source code:

terms_1 = int(input("Number of terms: "))
x, y = 0, 1
counter = 0
if terms_1 <= 0:
   print(" enter a positive integer")
elif terms_1 == 1:
   print("Fibonacci sequence",terms_1,":")
   print(x)
else:
   print("Fibonacci sequence:")
   while counter < terms_1:
       print(x)
       z = x + y
       x = y
       y = z
       counter += 1

90. What is namespace in Python?

It is a group of representative names which are tagged with some information pertaining to the names. Four types of namespaces:-

  1. Local
  2. Global (can use global variables)
  3. Built-in
  4. Enclosing

91. How to get multithreading in Python?

It is always suggested to avoid using multithreading. However, in certain cases it used to increase the speed of the application. Using GIL (Global interpreter Lock) will help in controlling the situation by enabling just one thread at a time. This puts some pressure on the CPU cores. 

92. What is Polymorphism in Python?

Polymorphism is one of the object oriented programming concepts. The idea is to have the same name for multiple classes or forms in which the statements can be expressed. This is very much possible in python. Here are some sample programs that demonstrate polymorphism. 

print(len(“polymorphism”)) // to find the length of the string
pring(len([23,47,29])) // same way another string’s length can be found as well.

93. Define encapsulation in Python?

The word encapsulation typically means to safeguard something. When it comes to programming it talks about safeguarding the functions, variables, objects and data structures.. In other words, it disables easy access to the functions within the python program. The idea is to hide the variable from outside view. Not all information needs to be seen by the user.

A user interacts with certain properties and functionalities of the application. The rest is hidden away from the viewers. In python, we can create classes – private & protected where the variables and functions used inside these classes can not be accessed beyond the scope of the variables. In python, private variables are declared using double underscore “__.” 

94. Does Python make use of access modifiers?

Yes access modifiers are applicable in python as well. They are used to control the scope of variables in the program. The access modifiers are divided into three parts – public, private and protected. 

Public modifiers – any variables that are part of the public class, they can be accessed at any point of the program. They can be used inside and outside the class.

Private modifiers – the variables declared in a private class can not be accessed outside of the class.

Protected modifiers – the can be accessed at certain instances, yet the scope of the variables is restricted within the protected class. 

This topic has been part of the python interview uestions a lot. Make sure you implement classes and modifiers practically. 

95. Write a program in Python to execute the Bubble sort algorithm.

The following code for bubble sort algorithm:-

# Python program for implementation of Bubble Sort 
def bubbleSort(arr): 
    x = len (arr1) 
    for i in range (x-1): 
          for j in range (0, x-i-1): 
                if arr [j] > arr [j+1] : 
                arr [j], arr [j+1] = arr [j+1], arr [j] 
arr = [12, 54, 33, 67, 98, 10, 60] 
bubbleSort (arr1) 
print ("Sorted array:") 
for i in range (len (arr1)): 
    print ("%d" %arr1 [i])

Python Interview Questions

96. How do you make 3D plots/visualizations using NumPy/SciPy?

Python has a predefined repository that takes care of 3D visualization. Using the matplotlib you can plot the graphs. The matplotlib toolkit allows one to develop 2D models as well. Here is a sample code that can give you a graphical visualization. 

import numpy as np 
import matplotlib.pyplot as plt 
plot_1 = plt.figure () 
Axis_1 = plt.axes (projection ='3d') 

97. What is the maximum possible length of an identifier?

There is no limit to the length of the identifiers. Other programming languages restrict the length of characters upto 79. However, it is not the case in python. 

98. Why are local variable names beginning with an underscore discouraged?

When a variable name is used with underscore, the variable automatically becomes private. This restricts its scope. Unless the variable is to be used in a private class, there is not need to use underscore. 

99. Mention what the Django templates consist of.

Django templates are basically a document containing some text. It has constructs within the document. It gives a basic format for the final outcome to be processed and displayed. The two major ones are said to be the variable and tags.

Variables Sample: Your first name is {{ first_name }}. Your last name is {{ last_name }}. 

Tags Sample: {% cycle ‘positive’ ‘negative’ %}, { % cycle ‘zip’ ‘a’ ‘b’ ‘c’ ‘3’%}

100. Give an example of how you can write a VIEW in Django?

Here are the steps to write a view in Django:-

  1. Get the httpresponse from django.http. Ensure that the datetime library of python is also installed.
  2. Create a new function for the current date. Which will be the new function that will take the http request. 
  3. The new function will return the response. 

Conclusion

Industries in the current era are using python more than ever. The flexibility it provides in terms of usage is vast and groundbreaking. Therefore, job opportunities for python developers are increasing day by day. This is why a lot of people are learning python.

This may be your first python interview or one of many. The idea is to have a strong preparation. The python interview questions and answers mentioned in this article act as a repository for reference. Try to focus on interview questions that have been asked repeatedly over a course of time.

Recommended Articles