python interview questions

Python Interview Questions and Answers

You are looking for python interview questions and answers or python interview questions for data science, then you are at the right place. Here I have tried to create a collection of top python interview questions with answers which might ask by your interviewer in python interviews. In this Python Interview Questions blog post I have selected the best python interview questions after spending many hours. So, I hope these python interview questions will be helpful for you.

Later I will convert this python interview questions blog post in python interview questions pdf. So let us start by taking a look at some of the most frequently asked Python interview questions with answers.

If you are new and want to learn python from basic, then you can check the below python course from the popular platforms.

 

Besides that, if you have any other doubts regarding Python, feel free to send an email to me or you can comment in the comment box. We will try to solve your problem as soon as possible.

 

Q #1) What is Python? What are the benefits of using Python?

Python is an interpreted, high-level, general-purpose programming language. Python is created by Guido van Rossum and first released in 1991. Basically, Python is designed to be highly readable. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.

 

Q #2) What are the key features of Python?

  • Python is dynamically typed and garbage-collected.
  • It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. You can easily integrate python with C, C++, COM, ActiveX, CORBA, and Java.
  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run.
  • Python interpreters are available for many operating systems.
  • It has a large community. A global community of programmers develops and maintains CPython.
  • You can write code easily using the python but you will find it is often slower than compiled languages ( for example, C language).

 

Q #3) What type of language is python? Programming or scripting?

Python is capable of scripting, but in the general sense, it is considered as a general-purpose programming language.

 

Q #4) Is python a case sensitive language?

Yes, Python is a case sensitive programming language.

 

Q #5) Is indentation required in python?

Yes, Indentation is necessary for Python. Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses the indentation to mark blocks of code. It is one of the distinctive features of Python is its use of indentation to highlighting the blocks of code. Whitespace is used for indentation in Python. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

# See code indentation 
  
site = 'aticleworld'
  
if site == 'aticleworld': 
    print('Hi aticleworld...') 
else: 
    print('Ohh...') 
print('Please visit Aticleworld !')

Output:

Hi aticleworld…
Please visit Aticleworld !

Code Explanation,

The lines print(‘Hi aticleworld…’) and print(‘Ohh…’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. Last print(‘Please visit Aticleworld !’) is not indented, and so it does not belong to the else-block.

 

Q #6) What is self in Python?

self represents the instance of the class. In Python, this is explicitly included as the first parameter. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.

selfpythselfQuestionson interview Questions

 

class human(): 
  
  # init method or constructor 
  def __init__(self, gender, color): 
    self.gender = gender 
    self.color = color 
    
  def show(self): 
    print("Gender is", self.gender ) 
    print("color is", self.color ) 
    
# both objects have different self which 
# contain their attributes 
amlendra = human("male", "white") 
pooja = human("woman", "black") 

amlendra.show()
pooja.show()

Output:

Gender is male
color is white
Gender is woman
color is black

 

Q #7) What is pep 8 in Python?

PEP is an acronym for the Python Enhancement Proposal. PEP is a set of rules that define how Python code must be formatted for maximum readability.

 

Q #8) Can we take any name in place of self?

Yes, we can. But it is advisable to use self because it increases the readability of code.

class human(): 
  
  # init method or constructor 
  def __init__(aticleworld, gender, color): 
    aticleworld.gender = gender 
    aticleworld.color = color 
    
  def show(aticleworld): 
    print("Gender is", aticleworld.gender ) 
    print("color is", aticleworld.color ) 
    
amlendra = human("male", "white") 
pooja = human("Woman", "Black") 

amlendra.show()
pooja.show()

Output:

Gender is male
color is white
Gender is Woman
color is Black

 

Q #9) What is a function in Python Programming?

A function is a set of statements that take inputs, do some specific computation and produce output. function brings modularity to a program and a higher degree of code reusability. Python has given us many built-in functions such as print() and provides the ability to create user-defined functions.

Syntax of Function,

def function_name(parameters):
  """docstring"""
  statement(s)

 

Q #10) Write the steps to define the function in python.

Here are few rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • The code block within every function starts with a colon (:) and is indented.
  • Optional documentation string (docstring) to describe what the function does.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Let us see a python function that finds the even and odd number.

# A simple Python function to check 
# whether data is even or odd 
def evenOdd( data ): 
  if (data % 2 == 0): 
    print "even"
  else: 
    print "odd"

# Function Call 
evenOdd(27) 
evenOdd(6)

Output:

odd
even

 

Q #11) How to call a function in python?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.

 

Q #12) What is __init__ in Python?

__init__  is a constructor of python classes and a reserved method. The __init__ method is called automatically whenever a new object is instantiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.

Here is an example of how to use it.

class Rectangle:
   def __init__(self, length, breadth, unit_cost=0):
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost
   def get_area(self):
       return self.length * self.breadth
   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# breadth = 10 units, length = 16 units, 1 sq unit cost = Rs 100
r = Rectangle(16, 10, 100)
print("Area of Rectangle: %s sq units" % (r.get_area()))
print("Cost of the Area: Rs= %d" % (r.calculate_cost()))

Output:

Area of Rectangle: 160 sq units
Cost of the Area: Rs= 16000

 

Q #13) What is the difference between self and __init__ methods in python Class?

There is the following difference between the self and __init__

self:

self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

__init__:

_init__  is a constructor of python classes and it is called automatically whenever a new object is instantiated.

 

Q #14) What is the return keyword used for in python?

We use the return statement to send the value back to its caller.

 

Q #15) Is It Mandatory For A Python Function To Return A Value?

No, It is not necessary for a function to return any value.

 

Q #16) What Is The Return Value Of The Trunc() Function?

The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.

 

Q #17) What is “Call By Value” in Python?

In, call by value, a parameter acts within the function as a new local variable initialized to the value of the argument (a local copy of the argument). Any changes made to that variable will remain local and will not reflect outside the function.

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value.

 

Q #18) What Is “Call By Reference” In Python?

In, call by reference, the argument variable supplied by the caller can be affected by actions within the called function. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

 

Q #19) How are arguments passed by value or by reference in Python?

Python uses a mechanism, which is known as “Call-by-Object”, sometimes also called “Call by Object Reference” or “Call by Sharing”.

If you pass immutable arguments like integers, strings, or tuples to a function, the passing acts like Call-by-value. It behaves differently if we pass mutable arguments.

Let us see the code,

student={'Amlendra':28,'Pooja':25,'Amitosh':25}
def test(student):
   new={'Apoorv':5}
   student.update(new)
   print("Inside the function",student)
   return
test(student)
print("outside the function:",student)

Output:

Inside the function {‘Amlendra’: 28, ‘Amitosh’: 25, ‘Apoorv’: 5, ‘Pooja’: 25}
outside the function: {‘Amlendra’: 28, ‘Amitosh’: 25, ‘Apoorv’: 5, ‘Pooja’: 25}

Note: One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created.

 

Q #20) What is the output of the below python code?

# Here y is a new reference to same list lst 
def myFun(y): 
  y[0] = 7

# Driver Code (Note that lst is modified 
# after function call. 
lst = [1, 2, 3, 4, 5, 6] 
myFun(lst); 
print(lst)

Output: [7, 2, 3, 4, 5, 6]

 

Q #21) What is the output of the below python code?

def myFun(y): 
 
  y = [1, 2, 3] 

# Driver Code  
lst = [10, 11, 12, 13, 14, 15] 
myFun(lst); 
print(lst)

Output: [10, 11, 12, 13, 14, 15]

Explanation,

When we pass a reference and change the received reference to something else, the connection between passed and received parameter is broken.

 

Q #22) What is the output of the below python code?

def myFun(y): 
  y = 20

# Driver Code
y = 10
myFun(y); 
print(y)

Output: 10

 

Q #23) What is the output of the below python code?

def swap(x, y): 
  temp = x; 
  x = y; 
  y = temp; 

# Driver code 
x = 2
y = 3
swap(x, y) 
print(x) 
print(y)

Output: 10

2
3

 

 

Q #24) How many basic types of functions are available in Python?

Python gives us two basic types of functions.
1. Built-in function.
2. User-defined function. It defines by the user as per the requirement.

The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.

 

Q #25) What are the applications of Python?

Below find the applications of Python:

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

 

 

Q #26) What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be function classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

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

 

Q #27) What are the benefits of Python?

The benefits of Python are as follows:

  • Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process control capabilities and possesses strong integration.
  • Extensive Support for Libraries: Python provides a large standard library that includes areas such as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the programming tasks are already been scripted in the standard library which reduces effort and time.
  • User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to build fast user-friendly data structures.
  • Existence of Third Party Modules: The presence of third party modules in the Python Package Index (PyPI) will make Python capable to interact with other platforms and languages.
  • Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for beginners to learn.

 

Q #28) What are the Python libraries? Name a few of them.

Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn, and many more.

 

Q #29) What is the difference between list and tuples in Python?

List  Tuple
Lists are mutable. They can be changed. Tuples are immutable (tuples are lists which can’t be changed).
Lists are slower than tuples. Tuples are faster than the list.
Syntax: list_1 = [20, ‘aticleworld, 30] Syntax: tup_1 = (20, ‘aticleworld, 30)

 

Q #30) What Does The __ Name __ Do In Python?

The __name__ is a unique variable. Since Python doesn’t expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation.

To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value “__main__.”

 

Q #31) Does Python have a main()method?

The main() is the entry point function which happens to be called first in most programming languages.

Since Python is interpreter-based, so it sequentially executes the lines of the code one-by-one.

Python also does have a Main() method. But it gets executed whenever we run our Python script either by directly clicking it or starts it from the command line.

We can also override the Python default main() function using the Python if statement. Please see the below code.

print("Welcome")
print("__name__ contains: ", __name__)
def main():
    print("Testing the main function")
if __name__ == '__main__':
    main()

Output:

Welcome
(‘__name__ contains: ‘, ‘__main__’)
Testing the main function

 

Q #32) What is the purpose of “end” in Python?

Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.

Let us see an example code, in which I am using the end with the print function.

# This Python program must be run with 
# Python 3 as it won't work with 2.7. 

# Example: Print a space instead of the new line in the end.
print("Let's learn" , end = ' ')  
print("Python") 

# Printing a dot in the end.
print("Learn programming from aticleworld" , end = '.')  
print("com", end = ' ')

Output:

Let’s learn Python
Learn programming from aticleworld.com

 

Q #33) Is the Python platform independent?

Output:

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

 

Q #34) What are Python packages?

Python packages are namespaces that contain multiple modules.

 

Q #35) What are the OOPS concepts available in Python?

Like other programming languages ( JAVA, C++, ..etc), Python is also an object-oriented programming language. It also supports different OOPS concepts. Below we have mentioned the oops concept which supports by Python.

  • Encapsulation.
  • Abstraction.
  • Inheritance.
  • Polymorphism.
  • Data hiding.

 

Q #36) What Is Class In Python?

Python supports object-oriented programming and provides almost all OOP features to use in programs. A Python class is a blueprint for creating objects. It defines member variables and gets their behavior associated with them.

 

Q #37) How to create a class in Python?

In Python, we can create a class by using the keyword “class.” An object gets created from the constructor. This object represents the instance of the class. In Python, we generate classes and instances in the following way:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Amlendra",28)

print(p1.name)
print(p1.age)

In the above example, we have created a class named Person and using the __init__() we are assigning name and age to the newly created object.

 

Q #38) What is the syntax for creating an instance of a class in Python?

An object is created using the constructor of the class. This object will then be called the instance of the class. In Python, we create instances in the following manner

Instance_Name = class(arguments)

 

 

Q #39) How to create an empty class in Python?

An empty class is a class that does not have any code defined within its block. In Python, we create an empty class by the keyword “pass”. The pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.

# Python program to demonstrate 
# empty class 

class Aticleworld: 
  pass

# Driver's code 
obj = Aticleworld() 

print(obj) 

Output:

__main__.Aticleworld object at 0x7fcc56a0d518>

 

Q #40) Explain Inheritance in Python with an example?

Inheritance allows us to define a class that inherits all the methods and attributes from another class. The class that inherits from another class is called a derived class or child class. The class from which we are inheriting is called parent class or base class.

There are many benefits of inheritance in Python, so let us see them:

  • Inheritance provides code reusability, makes it easier to create and maintain an application. So we don’t have to write the same code again and again.
  • It allows us to add more features to a class without modifying it.
  • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
  • Inheritance represents real-world relationships well.

 

Q #41) Does python support multiple inheritances?

Yes, When a child class inherits from multiple parent classes, it is called multiple inheritances.
Unlike Java and like C++, Python supports multiple inheritances. We specify all parent classes as a comma-separated list in the bracket.

 

Q #42)Write a python code that explains the inheritance?

# A Python program to demonstrate inheritance 
# In Python 3.x "class Person" is 
# equivalent to "class Person(object)" 
class Person(object): 
  
  # Constructor 
  def __init__(self, name): 
    self.name = name 

  # To get name 
  def getName(self): 
    return self.name 

  # To check if this person is employee 
  def isEmployee(self): 
    return "No"

# Inherited or Sub class (Note Person in bracket) 
class Employee(Person): 

  # Here we return yes 
  def isEmployee(self): 
    return "Yes"

# Driver code 
emp = Person("Amlendra") # An Object of Person 
print(emp.getName(), emp.isEmployee()) 

emp = Employee("Pooja") # An Object of Employee 
print(emp.getName(), emp.isEmployee()) 

Output:

Amlendra No
Pooja Yes

 

Q #43) What is polymorphism in Python?

Polymorphism is based on the greek words Poly (many) and morphism (forms). So polymorphism means having many forms. In Python, Polymorphism allows us to function overriding ( methods in the child class with the same name as defined in their parent class) and overloading (same name functions with different signatures).

 

Q #44) Write a python code that explains the Polymorphism?

class Bird: 
  def intro(self):
    print("We are birds!") 
  
  def flight(self): 
    print("Wow we can fly but some cannot.")
  
class crow(Bird): 
  def flight(self): 
    print("Crows can fly.") 
  
class ostrich(Bird): 
  def flight(self): 
    print("Ostriches cannot fly.") 
  
obj_bird = Bird() 
obj_cro = crow() 
obj_ost = ostrich() 

obj_bird.intro() 
obj_bird.flight() 

obj_cro.intro() 
obj_cro.flight() 

obj_ost.intro() 
obj_ost.flight() 

Output:

We are birds!
Wow we can fly but some cannot.
We are birds!
Crows can fly.
We are birds!
Ostriches cannot fly.

 

Q #45) Does Python make use of access specifiers?

Python does not have access modifiers. If you want to access an instance (or class) variable from outside the instance or class, you are always allowed to do so. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behavior of private and protected access specifiers. But it doesn’t actually change access privilege.

 

Q #46) Define encapsulation in Python?

Encapsulation is one of the most important aspects of object-oriented programming. Binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.

 

Q #47) What is data abstraction in Python?

In simple words, abstraction can be defined as hiding of unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality. In Python abstraction can be achieved using encapsulation.

 

Q #48) How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

 

Q #49) What is pass in Python?

The pass is a null operation in python. When it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

The pass statement is useful when you don’t write the implementation of a function but you want to implement it in the future. for example,

def addNum(num1, num2):
  # Implementation will go here 
  pass # Pass statement

addNum(2, 2)

 

 

Recommended Post for You

 

Reference: Python faq.