New Year Offer - Flat 50% Off On All Courses


Top 70 Python Interview Questions you need to prepare in 2021

Last updated on Nov. 30, 2020, 7:45 p.m. 1033 Views

Kirandeep Kaur

Kirandeep Kaur |

Kirandeep is a Technophile & Cybernaut who loves to learn and write on various emerging technologies like Data Science, Machine Learning, Cyber Security, Artificial Intelligence, Java, SQL, Digital Marketing, and so on. When she is not writing anything, you can find her playing mobile games, cooking, or surfing about technology trends. She is a music lover!

Top 70 Python Interview Questions you need to prepare in 2021

Last updated on Nov. 30, 2020, 7:45 p.m. 1033 Views

Kirandeep Kaur

Kirandeep Kaur

You have received a call from the recruiter and now you have to prove your Python skills and knowledge. But interviews are not just solving given problems rather it is about writing clean Python code using Python built-in libraries and functionality. At Codegnan, we have put our hands together that you remain at the frontline with your coding skills. This blog will talk through the top 70 Python interview questions and answers to ace your Python interview with confidence. 

This blog is helpful to the readers like Python interview questions and answers for freshers, Python interview questions and answers for intermediates, and Python interview questions and answers for advanced learners. Python interview questions will help you find answers to the questions that are frequently asked in Python interviews. The top Python interview questions and answers will give you a quick ride on the topics like Control Flow Statements, Syntax, Decorators, etc.

Let’s begin!

Basic Python Interview Questions

Q1) What is Python?

Python is a high-level, interpreted, and general-purpose programming language. General-purpose language means it can be used to create almost any type of application with the right tools or libraries. Python supports objects, modules, threads, exception-handling and automatic memory management which helps in modeling real-world problems and creating applications to solve these problems.

Q2) Explain the key features of Python

  • Deciphered language: Python is a deciphered language which implies that, dissimilar to programming languages like C and its variations, Python shouldn't be compiled before it is run. Other deciphered dialects are PHP and Ruby. 
  • Dynamically typed language: Python is a dynamically typed language this implies you don't have to express the sorts of factors when you pronounce them or anything like that. You can do things like x=111 and afterward x=" it is a string" without error. 
  • Object-oriented programming approach: Python is appropriate to object-oriented programming as it permits the meaning of classes alongside creation and inheritance. Python doesn't approach specifiers (like C++'s public, private). 
  • Functional language: In Python, functions are top of the line objects. This implies they can be allocated to variables, returned from different functions, and can be passed to functions. Classes are also known as the top of the line objects 
  • Quick compose of coding: Composing Python code is quick however running it is regularly slower than other programming languages. Fortunately, Python permits the incorporation of C-based extensions so bottlenecks can be improved. The NumPy package is a genuine case of this present, it is actually very fast in light of the fact that a great deal of the calculating it does isn't really done by Python 
  • Global use: Python can be used globally – web applications, automation, scientific modeling, big data applications, and some more. 

Q3) Why is Python called a dynamically typed language?

Typing means type-checking in programming languages. Python is a strongly typed language which means "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other side, a weakly-typed language like JavaScript will simply output "12" as a result.

Type-checking can be done at two stages -

Static - Data Types are checked before execution.

Dynamic - Data Types are checked during execution.

Python is known as an interpreted language as it executes each statement line by line and thus type-checking is done on the fly, during execution. By this means, Python is a Dynamically Typed Language.

Q4) What are Python namespaces?

Namespaces in Python are known as dictionaries with “name as key” mapped to a corresponding “object as value”. This allows multiple namespaces to utilize the same name and map it to a separate object. Following are the types of namespaces used in Python:

Local Namespace that includes local names inside a function. It is temporarily created for a function call and gets cleared when the function returns.

Global Namespace includes names from various imported packages or modules that are being used in the current project. It is created when the package is imported into the script and lasts until the execution of the script.

Built-in Namespace that includes built-in functions of core Python and built-in names for various types of exceptions.

Q5) Explain the scope of an object in Python?

Local: It refers to the local objects available in the current function.

Global: It refers to the objects available throughout the code execution since their inception.

Module-level: It refers to the global objects of the current module accessible in the program.

Outermost: It refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Tip: Local scope objects can be synced with global scope objects using keywords such as global.

Q6) State definition and differences between lists and tuples in Python?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['John’, 6, 0.19], while tuples are represented with parentheses ('Sena', 5, 0.97).

my_tuple = ('John', 6, 5, 0.97)

my_list = ['John', 6, 5, 0.97]

print(my_tuple[0])     # output => 'John'

print(my_list[0])     # output => 'John'

my_tuple[0] = 'Sena'    # modifying tuple => throws an error

my_list[0] = 'Sena'    # modifying list => list modified

print(my_tuple[0])     # output => 'John'

print(my_list[0])     # output => 'Sena'

Q7) How to check if all characters in a string are alphanumeric?

For this, we use the method isalnum()

Q8) What are the different methods to capitalize the first letter of a string in Python?

By using the method capitalize().

>>> 'abc'.capitalize()



>>> type(str.capitalize)

<class ‘method_descriptor’>

However, it will let other characters be.

>>> '@bc'.capitalize()



>>> 'abc123'.isalnum()

Other methods that we have to include:

>>> '123'.isnumeric()


>>> 'abc'.islower()


>>> 'Abc'.istitle()


>>> ' '.isspace()

Q9) What are the disadvantages of using Python?

  • Design restrictions
  • Slow when compared to C/C++ or Java
  • Weak in mobile computing
  • Underdeveloped database access layers

Q10) How will you find which directory you are currently in?

With the use of a function named getcwd(). It is used by importing it from the module OS.

For example:

>>> import os

>>> os.getcwd()


>>> type(os.getcwd)


Simply change the directly we are currently using-

>>> os.chdir('C:\\Users\\mypc\\Desktop')

>>> os.getcwd()

Python Coding Interview Questions:

Q11) How can you insert an object at a given index in Python?

Firstly, create a list

>>> ab=[1,2,4]

Then use the method insert. The first argument is the index at which to insert, the second is the value to insert

>>> ab.insert(2,3)

>>> ab

Q12) How can you reverse a list in Python?

Using reverse() method

>>> a.reverse()

>>> a

Or using a slicing method from right to left

>>> a[::-1]

>>> a

Q13) What is a Python interpreter?

>>> This sign is known as a Python interpreter.

Q14) How does a function return values?

A function uses the ‘return’ keyword to return a value.

>>> def add(a,b):

return a+b

Q15) How can you define a block in Python?

For any kind of statement, we possibly need to define a block of code under them. However, Python does not support curly braces. This means we must end such statements with colons and then indent the blocks under those with the same amount.

>>> if 3>1:


print("Good day")

Q16) What is the use of break and continue statements in Python?

Both break and continue statements are the control flow statements in Python loops. Break statement stops the current loop from executing further and transfers the control to the next block. Continue statement jumps to the next iteration of the loop without exhausting it.

Q17) Do we need do-while loop work if you don’t end it with a semicolon?

Python does not support an intrinsic do-while loop.

Q18) How you’ll get the max alphabetical character from a string?

With the use of max() method

>>> max('flyiNg')

Q19) What are the applications of Python?

Python can be used in the following:

  • Web and Internet Development
  • Desktop GUI
  • Scientific and Numeric Applications
  • Software Development Applications
  • Applications in Education
  • Applications in Business
  • Database Access
  • Network Programming
  • Games, 3D Graphics
  • And much more…

 Python Programming Questions

Q20) State any 10 built-in functions in Python.

complex()- Creates a complex number.

>>> complex(3.5,4)

eval()- Parses a string as an expression.

>>> eval('print(max(22,22.0)-min(2,3))')

filter()- Filters in items for which the condition is true.

>>> list(filter(lambda x:x%2==0,[1,2,0,False]))

format()- Format a string

>>> print("a={0} but b={1}".format(a,b))

hash()- Returns the hash value of an object.

>>> hash(3.7)

hex()- Converts an integer to hexadecimal.

>>> hex(14)

input()- Reads and returns a line of string.

>>> input('Enter a number')

len()- Returns the length of an object.

>>> len('Ayushi')

locals()- Returns a dictionary of the current local symbol table.

>>> locals()

open()- Opens a file.

>>> file=open('tabs.txt')

Q21) What will be the output of this code

>>> word=’abcdefghij’

>>> word[:3]+word[3:]

The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.

Q22) How can you convert a list into a string?

By using join() method

For example:

>>> nums=['one','two','three','four','five','six','seven']

>>> a=' '.join(nums)

>>> a

Q23) How can you remove a duplicate element from a list?

By turning elements into a set

For example:

>>> list=[1,2,1,3,4,2]

>>> set(list)

Q24) What is a Python dictionary?

The Python dictionary holds key-value pairs. It is mutable and uses a comprehension to create it.

Q25) What are membership operators?

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

>>> 'me' in 'disappointment'


>>> 'us' not in 'disappointment'


Q26) What are identity operators in Python?

The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

>>> 10 is '10'


>>> True is not False


Q27) Explain data types supported by Python.

There are a total of 5 data types supported by Python:

Numbers – Numbers are used to holding numerical values.

>>> a=7.0


Strings – A string is a sequence of characters. We declare it using single or double-quotes.

>>> title="Aryan's Book"

Lists – A list is an ordered collection of values, and we declare it using square brackets.

>>> colors=['red','green','blue']

>>> type(colors)

<class ‘list’>

Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, it is that a tuple is immutable. This means that we cannot change a value in it.

>>> name=('Good','day')

>>> name[0]='Avery'
  1. Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces. 
>>> squares={1:1,2:4,3:9,4:16,5:25}

>>> type(squares)

 We can also use a dictionary comprehension

>>> squares={x:x**2 for x in range(1,6)}

>>> squares

Q28) How can we convert a string into an int?

If a string contains only numeric characters, you can convert it into an integer using the int() function.

>>> int('117')


Do this to check the types:

>>> type('117')


>>> type(int('117'))

Q29) Explain the function in Python.

When we want to execute a sequence of statements, we can give it a name. Let’s define a function to take two numbers and return the greater number.

>>> def greater(a,b):

return a is a>b else b

>>> greater(3,3.5)

Python programs for interview

Q30) Explain recursion.

When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.

For example:

>>> def fact(n):

if n==1: return 1

return n*fact(n-1)

>>> fact(4)

Q31) How can you get all values from a Python dictionary?

To get all the keys from a dictionary, the keys() method is used.

>>> 'd' in {'a':1,'b':2,'c':3,'d':4}.values()

Q32) How can you use a toggle case in Python?

By using swap case() method from the str class

>>> 'HelloWorld'.swapcase()

Q33) You have a string “I Love Python”. Write a code to print up to letter t.

>>> i=0

>>> while s[i]!='t':



Q34) You have a string “I Love Python”. Write a code to print everything excerpt the spaces.

>>> for i in s:

if i==' ': continue


Q35) You have a string “I Love Python”. Write a code to print this string 5 times in a row

>>> for i in range(6):


Q36) What is a control flow statement in Python?

A Python program typically begins to execute from the first line. From that point, it travels through every statement only a single time and when it's finished with the last statement, it exchanges the program. However, we might need to take an increasingly turned path through the code. Control flow statements let us upset the ordinary execution flow of a program and curve it to our will. 

Q37) How can you swap two numbers?

>>> a,b=2,3

>>> a,b=b,a

>>> a,b

Q38) If you are stuck in an infinite loop then how will you break out of it?

Pressing the Ctrl+C key combination interrupts the execution.

Q39) How does an infinite loop occur?

>>> def counterfunc(n):


>>> counterfunc(9)

Q40) What makes Python an object-oriented language?

In Python, we have the following object-oriented features:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism
  • Data hiding

Q41) What type of objects does Python support?

Mutable objects 

These let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.

>>> [2,4,9]

Immutable objects

These do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster

>>> tuple=(1,2,4)

>>> tuple

Q42) What are the advantages of using Python?

  • Interpreted
  • Free and open source
  • Extensible
  • Object-oriented
  • Built-in data structure
  • Readability
  • High-Level Language
  • Cross-platform
  • Interpreted
  • Free and open source
  • Portable
  • Extensible
  • Object-oriented
  • Built-in data structure

Q43) What is a zip() function in Python?

Zip() function in Python returns a zip object which maps a similar index of multiple containers.


zip(iterator1, iterator2, iterator3 ...)

Q44) What is Python’s parameter passing mechanism?

  • Pass by value
  • Pass by reference

Q45) How can you remove whitespaces from a string?

string = "  hello "  

string2 = "    hello        "  

string3 = "       hello"  




print("After stripping all have placed in a sequence:")  




Q46) What are the file processing models supported by Python?


  • Read-only mode: Open a file for reading. It is the default mode.
  • Write-only mode: Open a file for writing. If the file contains data, data would be lost. Another new file is created.
  • Read-Write mode: Open a file for reading, write mode. It means updating mode.
  • Append mode: Open for writing, append to the end of the file, if the file exists.

Q47) What operators Python support?

  • Arithmetic Operators
  • Relational Operators
  • Assignment Operators
  • Logical Operators
  • Membership Operators
  • Identity Operators
  • Bitwise Operators 

Q48) What are Python decorators?

Decorators are very powerful and a useful tool in Python that allows the programmers to modify the behavior of any class or function. It allows us to wrap another function to extend the behavior of the wrapped function, without permanently modifying it.

# Decorator example  

def decoratorfun():  

    return another_fun  

Q49) In Python, what is pickling and unpickling?

The Python pickle is characterized as a module that acknowledges any Python item and changes over it into a string portrayal. It-dumps the Python object into a record utilizing the landfill work; this procedure is called pickling. 

The way toward recovering the first Python objects from the put-away string representation is called Unpickling. 

Q50) What are the most used looping statements in Python?

For loop and while loop 

Q51) What are Python modules?

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.

Q52) 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

Q53) Write a code to draw the following triangle.

def pyfun(r):

for a in range(r):

print(' '*(r-x-1)+'*'*(2*x+1))  


Q54) State the difference between NumPy and SciPy.


It is a Numerical Python that is used to perform general and efficient calculations on numerical data that is saved in arrays like indexing, reshaping, sorting, etc. It is majorly used to solve linear algebraic functions.


It is a Scientific Python that is a collection of tools that is used to perform various operations like differentiation, integration, etc. It is majorly used to solve algebraic calculations.

Q55) How to write a multi-line comment in Python

If you want to add multiple comments, you have to insert ‘#’ for each line.

For example:

#This is a comment

#written in

#more than just one line

print("Hello, World!")



This is a comment

written in

more than just one line


print("Hello, World!")

Q56) What is Django and list some features.

Django is an advanced-level framework that supports agile growth and clean pragmatic design that is majorly utilized for web development.

Features of Django:

  • Excellent documentation
  • Python web framework
  • SEO optimized
  • High scalability
  • Versatile in nature
  • Offers high security
  • Thoroughly tested
  • Provides rapid Development

Q57) What common security issues are handled by Django?

  • Clickjacking
  • Cross-site scripting and
  • SQL injection

Q58) What are the mandatory files for a Django project?


Q59) Name some commonly used modules in Python.

A Python module is a .py file that contains executable code. The most commonly used Python modules are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

Q60) What is a Lambda function?

The anonymous function is called a Lambda function in Python. Lambda function has a number of parameters but has a single statement.

For example:

a = lambda x,y : x+y

print(a(5, 6))

Q61) Explain docstrings in Python

Docstrings are actually documentation strings that are written within triple quotes. These are not assigned on any variable and are used as general comments too.

For example:


Using docstring as a comment.

This code divides 2 numbers






Q62) How can you add values in an array?

In Python, elements can be added using various functions like append(), extend(), and insert(i,x)

a=arr.array('d', [1.1 , 2.1 ,3.1] )







Q63) Types of inheritance used in Python

There are 4 types of inheritance are used in Python:

  1. Single inheritance
  2. Multi-level inheritance
  3. Hierarchical inheritance
  4. Multiple inheritances

Q64) How can you create a class in Python?

By using a class keyword

class School:

def __init__(self, name): = name



Q65) How can you request a database in Flask?

  • before_request(): Using this we can request a database before only without passing arguments.
  • after_request(): This method is called after requesting the database and also sends the response to the client.
  • teardown_request(): This method is called in the cases where the responses are not guaranteed and the exception is raised. They have no access to modify the request.

Q66) Explain the term monkey patching in Python.

The term monkey patching refers to the dynamic modifications of a class or a module during run-time.

For example:

import m

def monkey_f(self):

print "monkey_f()"

 m.MyClass.f = monkey_f

obj = m.MyClass()


Q67) How can you create an empty class in Python?

When a class doesn’t have any code within its block, is known as the empty class. To create an empty class, the pass keyword is used.

class a:

  &nbsp; pass


print("Name = ",

Q68) Write a program to check if the entered series is Palindrome or not.

a=input("enter sequence")


if a==b:

  &nbsp; print("palindrome")


  &nbsp; print("Not a Palindrome")

Q69) State reasons to use Python NumPy instead of a list.

Following are the reasons:

  • Less memory
  • Fast
  • Convenient

Q70) Write a program to check the memory usage of an object.

import sys
x = 10

Final Words

There are thousands of vacancies available for Python developers and Python experts are expected to be acquainted with the components of Python technologies. The knowledge of how to use Python during interviews can help you understand the deepness of Python programming that will pay dividends during day-to-day development. Python knowledge is essential for students and learners to get great employment opportunities in the future. The knowledge of every small detail about Python is a great approach to solve the problems linked with real-time scenarios. A magical trick here is to read and re-read the questions and their answers to get accustomed to what you will be asked in the Python interview. Let these questions be your gateway to your next job as a Python expert.


If you are planning to learn Python or looking for a lucrative career in Python or data science, then get back to us for the head to toe training in Python. We, at Codegnan, have the full-fledged Python MTA certification training module for the upcoming Pythonists where they will gain an understanding of Python and you will be able to solve logical problems quickly. You will understand the working of various Python libraries like SciPy, NumPy, Matplotlib, Lambda function, etc., and avail them to futureproof your career in various domains of Python like Data Science, Machine Learning, and Artificial Intelligence.

Do you know how much a Python developer earns in India? A Python developer in India earns around 427,293 INR to 1,150,000.

What are you waiting for then? A lucrative and futureproof career in Python is waiting for you! Get back to us, we’ll help you merge with other expert Pythonists.


Trending Certifications at Codegnan

Python for Data Science Certification



MTA Certification - Python for Data Science

555 Learners

200 Hours

Next Batch:
4th Jan | Weekday (Online) | 07:00PM - 09:00PM

Key Skills:
Mathematical Thinking, Critical Thinking

Machine Learning with Python Certification



Codegnan Certification for Machine Learning

431 Learners

50 Hours

Next Batch:
Nov 23rd | Weekday (Online) | 10:00AM - 12:00PM

Key Skills:
Mathematical thinking, Python Programming Skills

Web Development with Python - Django Certification



Codegnan Certification for Django

380 Learners

40 Hours

Next Batch:
Dec 1st | Weekday (Online) | 6:00PM - 7:00PM

Key Skills:
Python Programming Skills

ReactJS Certification



Codegnan Certification for ReactJs

98 Learners

60 Hours

Next Batch:
Nov 30th | Weekday (Online) | 2:00PM - 4:00PM

Key Skills:
HTML, CSS, Java Script

Become a Certified Professional  


Video Reviews