Python Interview Questions

 Python theoretical interview Q&A:

  1. How many versions in Python? and what is the difference in between them?
  2. Describe variable? and how we create variables?
  3. What are Python identifiers? Is there any regulations to make identifiers?
  4. What do you mean by reserved keywords in Python?
  5. Do you know about indentation, and what's the purpose of it?
  6. How the comments in Python will help us? Multiline comments?
  7. Describe operators in Python?
  8. What is the difference between membership operators and identity operators?
  9. What are the control statements in Python? For what purpose they are useful?
  10. Describe if-elif-else?
  11. What do you mean by looping concept and explain different looping techniques?
  12. What is the difference between break & continue statements?
  13. Describe data structures in python? and it's types?
  14. What is the difference between list and tuple?
  15. Classify mutable and immutable data structures in python?
  16. Describe set and it's features?
  17. What is the difference between tuple and set?
  18. What do you mean by frozenset? 
  19. Differentiate hard copy and shallow copy?
  20. What do you mean by dictionary in python and how it is different from other data structures?
  21. Describe the purpose of functions?
  22. Explain global variable and local variable?
  23. What is the difference between functions and anonymous function/ lambda?
  24. How the exception handling will help you in programming?
  25. What do you mean by module in python?
  26. What is the difference between module and library in python?
  27. Describe about inheritance and it's types?
  28. Define polymorphism? and discuss overriding and overloading?
  29. What do mean encapsulation?
  30. Describe data abstraction?


Answers and reference links:

1.How many versions in Python? and what is the difference in between them?
There are two different versions in python: Python 2 and Python 3.
Python 3 is simpler than python 2 

For more information click here: Python 3 vs Python 2

2.Describe variable? and how we create variables?

A variable(string or character) is a reserved memory location,  that stores a value or text. We use equal operator to assign a value, and we can perform numerical and string manipulations by using variable. 

  • Variable name can contain only letters, numbers, and underscore. ( A-Z, a-z, _ , 0-9 )
  • Variable name can starts with letter or underscore 
  • Variable can't start with a number.
  • Reserved keywords can't be used as variable
     Ex: Name = "Ajitha garu",  x = 15,  tuple_1 = (2,5,78,100) 

3.What are Python identifiers? Is there any regulations to make identifiers?
Python identifier is a name that we give to identify a variables, functions, modules, and class. We have to consider the below rules to create an identifier.

  • Variable name can contain only letters, numbers, and underscore. ( A-Z, a-z, _ , 0-9 )
  • Variable name can starts with letter or underscore 
  • Variable can't start with a number.
  • Reserved keywords can't be used as variable.
4.What do you mean by reserved keywords in Python?
The words which are reserved for specific purpose are defined as reserved keywords, We can't these reserved keywords for another purpose. For example you can't create a variable named as TRUE.  In python we have 33 reserved keywords, they are:


5.Do you know about indentation, and what's the purpose of it?
One of the most unique features of Python is its use of indentation to mark blocks of code. Each line of code must be indented by the same amount to denote a block of code in Python. Unlike most other programming languages, indentation is not used to help make the code look pretty. Indentation is required to indicate which block of code a code or statement belongs to.

6.How the comments in Python will help us? Multiline comments?
Comment is a short description which is fallowed by # symbol, and these comments are ignored by python interpreter. Comments will helps to understand the task that performed earlier. There are two types of comments:
  • Single line comment: we use # symbol to write single line comments.
  • Multiple line comment: we use docstrings( ''' ) to create multiple line comments.
7. Describe operators in python?
Operators are special symbols used to perform some operations on values and variables in python. 
Python language supports the following types of operators. 
  • Arithmetic Operators 
  • Comparison or Relational Operators 
  • Assignment Operators 
  • Logical Operators 
  • Membership Operators 
  • Identity Operators
Arithmetic operators:
Comparison operators:
Assignment operators:
Logical operators:
Membership operators:
Identity operators:
   8.What is the difference between membership operators and identity operators?




Membership operators are useful to test if a value is found in a sequence (string, list, tuple, set, or dictionary). There are two membership operators in Python, ‘in’ and ‘not in’.

Identity operators are useful to test if two variables are present on the same part of the memory. There are two identity operators in Python, ‘is’ and ‘is not’.

9. What are the control statements in python? For which purpose they used?
A control structure is the decision making process in programming.
  1. Selection statements allow programmers to check a condition and based on the result will perform different actions. There are two versions of this useful construct: (1) if and (2) if…else.
  2. A loop control statement(iteration) enables us to execute a single or a set of programming statements multiple times until a given condition is satisfied. Python provides two essential looping statements: (1) for (2) while statement.

10. Describe if-elif-else?
The most common type of flow control statement. An if statement's clause will execute if the statement's condition is True. The clause is skipped if the condition is False.

else: An if clause can optionally be followed by an else statement. The else clause is executed only when the if statement's condition is False.

          if  100 % 2 ==0:                                                                if  101 % 2 ==0:

                   return 'Even'                                                                          return 'Even'

           else:                                                                                  else:

                   return 'Odd'                                                                            return 'Odd'

elif: Sometimes, we may have a case where we want one of many possible clauses to execute, In such scenarios we use elif . The elif statement means " else if " , that always follows an if or another elif  statement.

Ex: 

x=100

if  x > 100:

     print( " x is greater than 100 ")

elif x < 100:

     print(" x is less than 100 ")

else:

     print (" x is equal to 100 ")


11. What do you mean by looping concept and explain different looping techniques?Looping concept is try to execute the code multiple times, the loop will iterate as long as the condition is true. We have two types of looping techniques in Python: 

                                                                                             1. for loop and 
                                                                                             2. while loop


For loop:
If we want to execute a block of code only a certain number of times(elements in the data structure or a specified range), we use for loop statement. A for loop is used for  iterating over sequence ( i.e a List, a Tuple, a Set, a Dictionary, and a String ).

While loop:
We can make a block of code execute over and over again with a while statement. The code in a while clause will be executed as long as the while statement's condition is True.


12. What is the difference between break & continue statements?
break:
There is a shortcut to getting the program execution to break out of a  loop's clause early. If the execution reaches a break statement, it immediately exits the while loop's  clause.

continue:
Like break statements, continue statements are used inside loops. When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop and re-evaluates the loop's condition.


13. Describe data structures in python? and it's types?
Data structure is container that stores, organize, and manipulates the data. In python we have four types of data structures as list, tuple, set and dictionary.

List:
List is a data structure in python that holds an organized collection of items. Items with in list always be accessed by index.

Ex:      fruits=[ 'Mango' , 'Banana' , 'Grapes' , 'Apple']

Tuple: 

Tuple is a immutable list, means if it once defined it cannot be modified. Items with in tuple also accessed by index as like list.

Ex: 

days_of_week=('Monday', 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday')

Set:

Set is data structure that contains an unordered collection of unique and mutable objects. Set can perform mathematical operations like Union, Intersection, Difference etc..

Ex:    A={1,5.2,4,3,6}       or    A= set(1,5,2,4,3,6)

Dictionary:

A dictionary holds key-value pairs, which are referred as items while other data types only contains elements.

Ex:      Student_roll number = { 'Raj' : 1 , 'Ram' : 2 , 'Krishna' : 3 }


14. What is the difference between list and tuple?

  • List is a mutable type of data structure, where as tuple is a immutable one. 
  • In list we can add, remove, and replace the values but none of these will perform by tuple. 
  • In list we use square brackets[ ] to create, and in tuple we use parenthesis ( ).
  • Performance wise tuple is faster than list.
15.Describe set and it's features?
Set is data structure that contains an unordered collection of unique and mutable objects. Three key characteristic of set are the following. 
1. The collection of items is unordered.
2. No duplicate items will be stored, which means that each item is unique. 
3. Sets are mutable, which means the items of it can be changed.

Ex:  A={1,5.2,4,3,6}       or    A= set(1,5,2,4,3,6)

An item can be added or removed from sets. Mathematical set operations such as union, intersection, etc., can be performed on Python sets.

16. Classify mutable and immutable data structures in python?
  • We use parenthesis ( ) to create a tuple, but in set we use curly braces { } or set keyword to create sets.
  • Tuple is a ordered collection of elements, where as set is a unordered collection of elements.
  • Sets are mutable type of data structure and tuple is immutable type of data structure.
  • Tuple allows duplicate elements, but set don't allow duplicate elements.

17. What is the difference between tuple and set?
  • To create tuple we use parenthesis () and in set we use curly braces {} or set() keyword
  • Tuple is a ordered collection of elements, but set is an unordered collection of elements.
  • Set is mutable where as tuple is immutable.
  • Set don't allow duplicates but tuple allow duplicates that is repeated elements.

18.What do you mean by frozenset?
Frozenset is a type of set, in which we can't modify the elements once we created. In general sets are mutable in nature, but frozensets are immutable.

19. Differentiate hard copy and shallow copy?
In python we can copy objects in two methods.

1.Hard copy ( Deep copy ):
A hard copy creates new object with new memory address, and the copied object is completely independent of the original object. Any changes made to the copied object will not effect the original object.

2. Shallow copy:
In shallow copy the copied object still pointing to the original object. Any changes made to the copied object will effects the original object.

20. What do you mean by dictionary in python and how it is different from other data structures?
The Python dictionary will have a key and value pair for each item that is part of it. The key and value should be enclosed in curly braces. Each key and value is separated using a colon (:), and further each item is separated by commas (,).

Ex:       Student_roll number = { 'Raj' : 1 , 'Ram' : 2 , 'Krishna' : 3 }

The remaining data structures list, tuple, and set in python can have only values (elements), but dictionary has key-value pairs.

21. Describe functions in python?
 Instead of repeating several lines of code every time you want to perform a particular task, use a function that will allow you to write a block of python code once and then use it as many times. This can help you, reduce the overall length of your program.

To create function, use the def keyword followed by the name of the function. By simply calling the name of the function(you defined) reuse for that particular task.

def function_name():


22. Explain global variable and local variable?

While creating identifiers like functions and classes we create variable, these variables are classified into two categories 1.Global variable and 2. Local variable.

Global variable: The variable which is created with in the program and it is applicable outside  as well as within program

Local variable: The variable which is created in program and it is applicable within program itself. 


23.What is the difference between functions and anonymous function/ lambda?

A function is block of code used to perform particular task. Function is defined with a name and we can use this function as many times we want by just calling function name.

Lambda is also a function without a defined name, hence we call it as anonymous function.


24. How the exception handling will help you in programming?

Any error that happens while a Python program is being executed that will interrupt the expected flow of the program is called as exception. Your program should be designed to handle both expected and unexpected errors

We can handle exceptions in our Python program using try, raise, except, and finally statements.

 Try and except: try clause can be used to place any critical operation that can raise an exception in our program, and an exception clause should have the code that will handle a raised exception.

25. What do you mean by module in python?

Any text file having ".py " extension contains python code is called module. Generally module will contain different python objects like function, classes, variables etc,. We have in-built modules as well as we can create an user defined module with our own requirements. We can use the module whenever we required by simply importing it.

For example to perform any mathematical calculations we use math module(in-built)

import math as m


26. What is the difference between module and library in python?

Module:

Any text file having ".py " extension contains python code is called module. Generally module will contain different python objects like function, classes, variables etc,.

Library:

A library is a collection of related modules or packages.

27. Describe about inheritance and it's types?

Inheritance is inherit the properties of another class. Inheritance will help us code reusability, less code. Here we have two types of classes 1.Parent class and 2. Child class.

Types of inheritance:

Single inheritance: When child class derived from only one parent class

Multiple inheritance: When child class is inherited from multiple parent classes


Multilevel inheritance: In this we have one parent class and one child class and one grand child class.


Hierarchical inheritance: In this more than one child classes are inherit from one parent class.

Hybrid inheritance: It is the combination of all single, multiple, multilevel and hierarchical inheritances


28. Define polymorphism? and Discuss overriding and overloading?

The process of modifying or adding more features to already defined method is called Polymorphism.

Overloading: The process of using one same operator for different use

Ex: we use '+' operator for add numbers as well as to concatenate the strings.

Overriding: In this the method defined in parent class will reuse in child class (inheritance).


29.  Describe Encapsulation?

Encapsulation is  a mechanism of wrapping variables and methods together as a single unit.

The variables in the class will be hidden from other class and can only accessed by the methods of their current class.


30. What is  Data abstraction?
Data abstraction in python is a process of handling complexity by hiding unnecessary information from the user.
For example in social media platforms we chat, share images and etc.. with friends but the users don't know how these operations happening in background.


Comments