Python is the top most programming language these days. I have wrote a lot of python tutorials, here I am providing Python Interview Questions and Answers that will help you in python interview. These python interview questions are good for beginners as well as experienced programmers. There are coding questions too to brush up your coding skills.
Python Interview Questions
Python is getting a lot of attention, specially in the field of data science, pen testing, scientific and mathematical algorithm development, machine learning, artificial intelligence etc.
I have been working on Python for more than 5 years now, all these python interview questions are coming from my learning on the job as well as the interviews I have taken for Python developers role. You should bookmark this post as I will keep on adding more interview questions to this list in future.
- What is Python? What are the benefits of using Python?
- What is Python? What are the benefits of using Python?
- What is PEP 8?
- What are the differences between Python 2.x and Python 3.x?
- Why do you need to make your code more readable?
- How many Keywords are there in Python? And why should we know them?
- What are the built-in data-types in Python?
- How many types of operators Python has? Give brief idea about them
- What is the output of the following code and why?
- What is PEP 8?
- What should be the output of the following code and why?
- What is the statement that can be used in Python if the program requires no action but requires a statement syntactically?
- What are the advantages of Python Recursion?
- What are the disadvantages of Python Recursion?
- What is lambda in python?
- Why don’t Python lambda have any statement?
- What do you understand by Python Modules?
- A module print_number given, what will be the output of the following code?
- What do you understand by Python Package?
- What will be the output of the following code?
- Will this code output any error? Explain.
- What will be the output of the following code?
- What will be the output of the following code2? Explain
- What is namespace in Python?
- Why do we need Python Directories
- How to get current directory using Python?
- Why Should We Use File Operation?
- Why should we close files?
- What are python dictionaries?
- What are the differences between del keyword and clear() function?
- What is Python Set?
- How will you convert a string to a set in python?
- What a blank curly brace initialize? A dictionary or a set?
- Explain split() and join() function.
- What is Python Decorator?
- What do you understand by Python Generator?
- What do you understand by Python iterator and Iterable elements?
- What do you know about iterator protocol?
- What will be output of the following code? Explain (Python Inheritance)
- Why do we need operator overloading?
- What is the difference between tuples and lists in Python?
- How to compare two list?
- How can you sort a list?
- How can you sort a list in reverse order?
- How will you remove all leading and trailing whitespace in string?
- How can you pick a random item from a list or tuple?
- How will you change case for all letters in string?
- In Python what is slicing?
- How will you get a 10 digit zero-padded number from an original number?
- What is negative index in Python?
Python Interview Questions and Answers
What is Python? What are the benefits of using Python?
Python is a high level object-oriented programming language. There are many benefits of using Python. Firstly, Python scripts are simple, shorter, portable and open-source. Secondly, Python variables are dynamic typed. So you don’t need to think about variable type while coding. Thirdly, Python classes has no access modifiers which Java have. So, you don’t need to think about access modifiers. Lastly, Python provides us different library, data-structure to make our coding easier.
Does Python use interpreter or compiler? What’s the difference between compiler and interpreter?
Python uses interpreter to execute its scripts. The main difference between an interpreter and a compiler is, an interpreter translates one statement of the program to machine code at a time. Whereas, a compiler analyze the whole script and then translate it to machine code. For that reason the execution time of whole code executed by an interpreter is more than the code executed by compiler.
What is PEP 8?
Basically PEP 8 is a style guide for coding convention and suggestion. The main objective of PEP 8 is to make python code more readable.
What are the differences between Python 2.x and Python 3.x?
Python 2.x is an older version of Python while Python 3.x is newer. Python 2.x is legacy now but Python 3.x is the present and future of this language. The most visible difference between them is in print statement. In Python 2 it is print “Hello” and in Python 3, it is print (“Hello”).
Why do you need to make your code more readable?
We need to make our code more readable so that other programmer can understand our code. Basically for a large project, many programmers work together. So, if the readability of the code is poor, it will be difficult for other to improve the code later.
How many Keywords are there in Python? And why should we know them?
There are 33 keywords in Python. We should know them to know about their use so that in our work we can utilize them. Another thing is, while naming a variable, the variable name cannot be matched with the keywords. So, we should know about all the keywords.
What are the built-in data-types in Python?
The built-in data-types of Python are
Among them, the first three are immutable and the rest are mutable. To know more, you can read our
Python Data Types tutorial.
How many types of operators Python has? Give brief idea about them
Python has five types of operators. They are
- Arithmetic Operators : This operators are used to do arithmetic operations
- Comparison Operators : This operators are used to do compare between two variables of same data-type.
- Bitwise Operators : This kind of operators are used to perform bitwise operation between two variable
- Logical Operators : This operators performs logical AND, OR, NOT operations among two expressions.
- Python Assignment Operators : This operators are used to perform both arithmetic and assignment operations altogether.
Read more at Pytho
n Operators tutorial.
What is the output of the following code and why?
a = 2 b = 3 c = 2 if a == c and b != a or b == c: print("if block: executed") c = 3 if c == 2: print("if block: not executed")
The output of the following code will be
if block: executed
This happens because logical AND operator has more precedence than logical OR operator. So a == c expression is true and b != a is also true. So, the result of logical AND operation is true. As one variable of OR operation is true. So the result of Logical operation is also true. And that why the statements under first if block executed. So the value of variable c changes from 2 to 3. And, As the value of C is not true. So the statement under second block doesn’t execute.
Write a program that can determine either the input year is a leap year or not
The following code will determine either the input year is a leap year or not.
try: print('Please enter year to check for leap year') year = int(input()) except ValueError: print('Please input a valid year') exit(1) if year % 400 == 0: print('Leap Year') elif year % 100 == 0: print('Not Leap Year') elif year % 4 == 0: print('Leap Year') else: print('Not Leap Year')
Below image shows the sample output of above program.
What should be the output of the following code and why?
a = 10 while a > 0: print(a) else: print('Now the value of a is ',a); break
The following code will result in SyntaxError. Because the break statement is not in a loop. It should be under the scope of a loop.
What is the statement that can be used in Python if the program requires no action but requires a statement syntactically?
Python pass statement can be used if the program requires no action but requires a statement syntactically. Python pass statement has no action. But it is a statement. Read more at python pass statement tutorial.
What are the advantages of Python Recursion?
Implementing something using Python recursion requires less effort. The code we write using recursion will be comparatively smaller than the code that is implemented by loops. Again, code that are written using recursion are easier to understand also.
What are the disadvantages of Python Recursion?
Python recursion requires more function call. Each function call stores some state variable to the program stack. If your code requires too many function calls, it will consumes too much memory. So, there may be some possibilities of causing memory overflow if your code is not that much efficient. Again, it takes some time to call a function, if the task of the function is done, the it recall the parent function which also cause some time to re-execute the parent function from the previous state. So, recursive function consumes more time to perform it’s task.
For examples, see our Python Recursion example.
What is lambda in python?
Python lambda is a single expression anonymous function which has no name. Therefore, we can use Python lambda for a small scope of program.
Why doesn’t Python lambda have any statement?
Python lambda doesn’t have any statement because statement does not return anything while an expression returns some value. The basic syntax of python lambda is
lambda arguments : expression
The value of the expression for those arguments is returned by Python lambda.
To know more with examples, read our Python Lambda tutorial.
What do you understand by Python Modules?
A file containing Python definitions and statements is called a python module. So naturally, the filename is the module name which is appended with the suffix .py.
A module print_number given, what will be the output of the following code?
# module name: print_number def printForward(n): #print 1 to n for i in range(n): print(i+1) def printBackwards(n): #print n to 1 for i in range(n): print(n-i)
from print_number import printForward as PF PF(5)
The output of the program will be like this.
1 2 3 4 5
Because PF refers the function printForward. So it passes the argument to the function and the result will be like given one.
Read our tutorial on Python modules to have clear idea on this.
What do you understand by Python Package?
Python package is a collection of modules in directories that give a package hierarchy. More elaborately, python packages are a way of structuring python’s module by using “dotted module names”. So A.B actually indicates that B is a sub module which is under a package named A.
What will be the output of the following code? Explain the output
print(10) print(0x10) print(0o10) print(0b10)
The output of the following code will be:
10 16 8 2
0x10 is a hexadecimal value which decimal representation is 16. Similarly
0o10 is a octal value and
0b10 is a binary value.
Will this code output any error? Explain.
a = 3 + 4j
This will not produce any error. Because
3 + 4j is a complex number. Complex number is a valid data-type in Python.
Read more at Python Number tutorial for more details.
What will be the output of the following code?
def func(): try: return 1 finally: return 2 print(func())
The code will output 2. Because whatever statements the try block has, the finally block must execute. So it will return two.
What will be the output of the following code2? Explain
def func(): a = 2 try: a = 3 finally: return a return 10 print(func())
The code will output 3. As no error occurs, the try block will execute and the value a is changed from 2 to 3. As the return statement of
finally block works. The last line of the function will not execute. So the output will be 3, not 10.
What is namespace in Python?
Namespace is the naming system to avoid ambiguity and to make name uniques. Python’s namespace is implemented using Python Dictionary. That means, Python Namespace is basically a key-value pair. For a given key, there will be a value.
Why do we need Python Directories?
Suppose, you are making some a software using Python where you need to read/write files from different directories. The directories can be dynamic so that you cannot fix the directory from your code, rather you need to choose the directory dynamically. After choosing the directory, you may have to create a new directory or write a file or read a file from that directory. To do so, Python has introduced this facility.
How to get current directory using Python?
To get current Directory in Python, we need to use
os module. Then, we can get the location of the current directory by using
getcwd() function. The following code will illustrate the idea
import os #we need to import this module print(os.getcwd()) #print the current location
To get more examples, see our tutorials on Python Directories.
Why Should We Use File Operation?
We cannot always rely on run-time input. For example, we are trying to solve some problem. But we can’t solve it at once. Also, the input dataset of that problem is huge and we need to test the dataset over and over again. In that case we can use Python File Operation. We can write the dataset in a text file and take input from that text file according to our need over and over again.
Again, if we have to reuse the output of our program, we can save that in a file. Then, after finishing our program, we can analysis the output of that program using another program. In these case we need Python File Operation. Hence we need Python File Operation.
How to close file? Why should we close files?
To close a file in Python we should use
close() function. Mainly there is two reasons why we should close files after use. Firstly, Python does not promise that it will close the files for us. The operating system does, when the program exits. If your program does something else for a while, or repeats this sequence of steps dozens of times, we could run out of resources, or overwrite something. Second, some operating system platforms won’t let the same file be simultaneously open for read-only and for write. So, if the two filenames happened to be the same file, we might get an error trying to write without having closed the input file.
To know more, see our tutorial on Python File.
What are python dictionaries?
Python dictionary is basically a sequence of key-value pair. This means, for each key, there should be a value. All keys are unique. We can initialize a dictionary closed by curly braces. Key and values are separated by semicolon and and the values are separated by comma.
What are the differences between del keyword and clear() function?
The difference between
del keyword and
clear() function is, del keyword remove one element at a time. But clear function removes all the elements. The syntax to use the
del keyword is:
While the syntax for
clear() function is:
To know more see our tutorial on Python Dictionary.
What is Python Set?
Python Set is an unordered collection of unique elements. Suppose you have a list and you need only the unique items of the list you can use Python Set. Similarly, if you need only unique items from input, Python set can help you to do so. You can add or delete items from it.
You can initialize a set by placing elements in between curly braces.
How will you convert a string to a set in python?
We can convert a string to a set in python by using
set() function. For examaple the following code will illustrate the idea
a="Peace" b = set(a) print(b)
What a blank curly brace initialize? A dictionary or a set?
Well, both Python Dictionary and Python Set requires curly braces to initialize. But a blank curly brace or curly brace with no element, creates a dictionary. To create a blank set, you have to use
Explain split() and join() function.
As the name says, Python’s
split() function helps to split a string into substrings based on some reference sequence. For example, we can split Comma Separated Values(CSV) to a list. On the other hand,
join() function does exactly the opposite. Given a list of values you can make a comma separated values using join function.
What is Python Decorator?
Python decorator is a function that helps to add some additional functionalities to an already defined function. Python decorator is very helpful to add functionality to a function that is implemented before without making any change to the original function. Decorator is very efficient when want to give an updated code to an existing code.
What do you understand by Python Generator?
Python generator is one of the most useful and special python function ever. We can turn a function to behave as an iterator using python generator function. So, as similar to the iterator, we can call the next value return by generator function by simply using
What do you understand by Python iterator and Iterable elements?
Most of the objects of Python are iterable. In python, all the sequences like Python String, Python List, Python Dictionary etc are iterable. On the other hand, an iterator is an object which is used to iterate through an iterable element.
What do you know about iterator protocol?
Python Iterator Protocol includes two functions. One is iter() and the other is next().
iter() function is used to create an iterator of an iterable element. And the
next()function is used to iterate to the next element.
What will be output of the following code? Explain
class A: def __init__(self): self.name="John" self.age = 23 def getName(self): return self.name class B: def __init__(self): self.name="Richard" self.id = '32' def getName(self): return self.name class C(A, B): def __init__(self): A.__init__(self) B.__init__(self) def getName(self): return self.name C1 = C() print(C1.getName())
The output to the given code will be Richard. The name when printed is ‘Richard’ instead of ‘John’. Because in the constructor of C, the first constructor called is the one of A. So, the value of name in C becomes same as the value of name in A. But after that, when the constructor of B is called, the value of name in C is overwritten by the value of name in B. So, the name attribute of C retains the value ‘Richard’ when printed.
Why do we need operator overloading?
We need Python Operator Overloading to compare between two objects. For example all kind of objects do not have specific operation what should be done if plus(+) operator is used in between two objects. This problem can be resolved by Python Operator Overloading. We can overload compare operator to compare between two objects of same class using python operator overloading.
What is the difference between tuples and lists in Python?
The main differences between lists and tuples are, Python List is mutable while Python Tuples is immutable. Again, Lists are enclosed in brackets and their elements and size can be changed, while tuples are enclosed in parentheses and cannot be updated.
How to compare two list?
Two compare we can use
cmp(a,b) function. This function take two lists as arguments as
b. It returns -1 if a<b, 0 if a=b and 1 if a>b.
How can you sort a list?
We can sort a list by using
sort() function. By default a list is sorted in ascending order. The example is given
How can you sort a list in reverse order?
We can sort a Python list in reverse order by using
sort() function while passing the value for key
’sorted’ as false. The following line will illustrate the idea.
How will you remove all leading and trailing whitespace in string?
Removing all leading whitespace can be done my by using
rstrip() function. On the other hand, all trailing whitespace can be removed by using
lstrip() function. But there is another function by which the both operation can be done. That is,
How can you pick a random item from a list or tuple?
You can pick a random item from a list or tuple by using
random.choice(listName) function. And to use the function you have import
How will you toggle case for all letters in string?
To toggle case for all letters in string, we need to use
swapcase() Then the cases of all letters will be swapped.
In Python what is slicing?
Python slicing is the mechanism to select a range of items from a sequence like strings, list etc.
The basic syntax of of slicing is listObj[start:end+1], here the items from
end will be selected.
How will you get a 10 digit zero-padded number from an original number?
We can get a 10 digit zero-padded number from an original number by using
rjust() function. The following code will illustrate the idea.
num = input('Enter a number : ') print('The zero-padded number is : ', str(num).rjust(10, '0'))
What is negative index in Python?
There are two type of index in python. Non-negative and negative. Index 0 addresses the first item, index 1 address the second item and so on. And for the negative indexing, -1 index addresses the last item, -2 index addresses the second last item and so on.
So, That’s all for python interview questions and answers. We wish you success on python interview. Best of Luck!