This article contains 100 most frequently asked questions on Python Programming language. These questions are extracted from various interview experiences, held at various locations and companies.
Download the e-books of Interview Questions : here
SET 1 – Q1 – Q10
Q.What do you know about Python ?
A. Python is an interpreted, high level and object oriented programming language. Python is easy to understand and develop.
Q. Who developed Python ?
A. Python was developed by Guido Van Rossum.
Q. Why Python was named as “Python” ?
A. G.V Rossum picked the name “Python” from the famous TV show, Monty Python’s Flying Circus and rest is history.
Q. Python is “dynamically typed”. Explain.
A. In Python, unlike C/C++, we do not need to declare anything. Assignment statements binds a name to an object, and object can be of any type. If a name is assigned to an object of one type, then later, it may be assigned to an object of another type. It means that Python is dynamically typed.
Q. Is Python a scripting language ?
A. A scripting language is a programming language that does not use a compiler for executing the source code. Rather, it uses an interpreter to translate source code to machine code on the go. Python is capable of scripting but, is considered to be a general purpose language. General purpose programming language has wide range of application domains.
Q. What is Byte code ?
A. When a python code is compiled, a file (set of instructions ) is generated. this is referred to as Byte code. It is Byte code only, which makes python platform independent. Further, this byte code is converted to machine code using Interpreter.
Q. What are flavors of Python?
A. Python flavors refers to the different types of Python compilers. Some flavors are cpython, jython, ironpython, PyPy.
Q. What is CPython ?
A. This is the standard python compiler implemented in C language.
Q. Do you what is Jython ?
A. This is the implementation of Python programming language which is designed to run on Java platform.
Q. Highlight the difference between C & Python ?
SET 2 – Q11 – Q20
Q. Highlight the difference between Java & Python ?
Q. What are builtin datatype in Python ?
A. None, int, float, complex, bool, str, bytes, list, tuple, range etc.
Q. You are given a mathematical expression in the form of string, write a python code to solve it.
A. Do it with the help of eval() function.
Q. Give a brief explanation about list and tuple ?
A. Lists are mutable(can be changed) whereas Tuples are immutable(can’t be changed). Tuples are faster than lists.
General format for tuple : (4,5,6,9)
General format for list : [4,5,6,9]
Q. Why tuples are faster than lists ?
A. Tuples are stored in single block of memory whereas Lists are stored in two blocks, first block for object related information and second block for the value. Hence, tuples are faster than list.
Q. Differentiate between list and tuple ?
A. Tuple uses less memory whereas lists uses more memory. We can’t modify tuples but lists can be modified.Tuples are faster than lists.
Q. What is PEP 8 ?
A. It is Python Enhancement Proposal. It refers to the formatting of python code for maximum readability and understandability.
Q. Explain memory management in Python ?
A. Memory Management in Python is managed by Python Private heap space. All python objects and data structures are stored in heap area. Programmers do not have any direct access to private heap area, interpreter takes care of it.
Q. Explain Garbage Collection in Python ?
A. Python has the concept of inbuilt garbage collector. It recycles all the unused memory so that they get available for future use.
Q. What is PYTHON PATH ?
A. It is an environment variable which we can use to set the additional directories, where modules and packages are looked for.
For MAC :
1. Open Terminal.app;
2. Open the file ~/.bash_profile in your text editor – e.g. atom ~/.bash_profile;
3. Add the following line :
export PYTHONPATH=”/Users/my/code” and save it.
For LINUX :
1. Open your terminal;
2. Open the file ~/.bashrc in your text editor – e.g. atom ~/.bashrc;
3. Add the following line to the end:
export PYTHONPATH=/home/my/code and save it.
SET 3 – Q21 – Q30
Q. What are python modules ?
A. Python modules are .py files containing python executable code. Some builtin modules are math, random, sys, json, itertools.
Q. What do you mean by JSON ?
Q. Explain the role of loads() & dumps() methods of JSON module.
A. loads() -> for parsing json text/string.
dumps() -> for converting python code to json string.
Q. What is the role of ord() method ?
A. It is used to change a character to integer.
Q. What the basic difference between list & array ?
A. Arrays have similar type of elements whereas list have dynamic type elements.
Q. Explain the role of __init()__ method ?
A. It is predefined method in python classes. This method is called when any object is created from a class, it basically initializes the attributes of a class.
Q. What are anonymous functions ?
A. Lambda functions are popularly called as anonymous functions. Such methods generally have multiple parameters but single statement.
For example :
a = lambda x,y : x+y
print(a(6,8)) will result in 14.
Q. What is self ?
A. It is an object or an instance of a class,which is explicitly included as first argument.
Q. What is pass keyword ?
A. Pass is a non operational statement. It actually does nothing.
Q. What is continue keyword ?
A. The continue statement skips all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
SET 4 – Q31 – Q40
Q. How we can generate randomize elements of lists ?
A. We can do this with the help of shuffle() method, present in random module.
Q. Differentiate between range and xrange ?
Q. How pickling works ?
A. Pick an object, convert it to string and then dump it into file, this defines the process of pickling.
Q. What are Generator functions ?
A. It is just like a normal function which generates a value using yield keyword.
def simgen(): yield 1 yield 4 yield 9x=simgen() print(x.__next__())
output : 1
Generator object is a python iterator.
Q. What are decorators ?
A. Decorators provide a simple and easy syntax for calling higher-order functions. In other words, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. It is referred to as meta programming.
Q. Tell me the role of ‘is’, ‘not’, ‘in’ keyword ?
A. is : return true if both operands are equal else false.
not : returns inversion of boolean value.
in : checks for the presence of an element in a list or any other datatype.
Q. Analyze the role of help() ?
A. It is used to display the documentation of modules, functions, classes, keywords etc.
Q. Analyze the role of dir() ?
A. It returns the list of all valid attributes.
Q. Give general syntax for ternary operator ?
A. [ on true ] if [ expression ] else [ on false ]
Example : “odd” if n%2==1 else “even”
Q. What are *args & **kwargs ?
A. *args -> It is used when we need to pass unspecified number of paramenters within a method.
**kargs -> It is used when we need to pass unspecified number of paramenters within a method but usually used in dictionaries.
SET 5 – Q41 – Q50
Q. How we can delete files in Python ?
Q. Explain docstring ?
A. A String written in triple quotes, which generally gives a complete introduction of class.
Q. What are different types of variables in Python ?
A. Instance variable, Static variable, Class variable.
Q. Explain Instance variable ?
A. Variables whose seperate copy is created in every instances, are instance variable. Ex. If z is an instance variable, and we create 2 instances, then there will 2 different copies of z in these 2 instances. Modification of one variable will not effect other copies.
Q. How we can access instance variable ?
A. With the help of dot (.) operator.
Q. What are instance methods ?
A. Methods that acts on the instances of a class are known as instance methods. They generally use self as their first parameter, which refers to the location of that instance in memory.
Q. Explain Static variable ?
A. They are also referred to as Class variables. In these type of variables, only single copy is available.
Q. What is namespace ?
A. A memory block, where names are mapped to objects.
Q. Explain me the role of Constructor ?
A. It is defined as the special method for initializing instance variable. Constructor is called at the time of creating objects.
Q. Explain Static methods ?
A. They are simple methods with no self argument. They work on class attributes not on instance attributes. They can be called through both class and instance.
SET 6 – Q51 – Q60
Q. Explain Abstract methods ?
A. Abstract methods are the methods, that does not have any body, and are further refined in the subclasses. Abstract methods are generally written with decorator @abstractmethod above them.
Q. Abstract class contains only abstract methods. True ?
A. No, it can also contain concrete methods.
Q. In Python, is it possible to write abstract method with body also ?
Q. Can we create instances of Abstract class ?
Q. Can we have nested class in Python ?
A. Yes, we can have nested class in Python.
Q. What do know about MRO ?
A. It is Method Resolution Order.It is the order in which Python looks for a method in a hierarchy of classes. Starting from current class, searching in parent class in depth first, left to right fashion, without searching same class twice.
Q. What is method overloading ?
A. It refers to the two or more methods having same method name but different parameters as well as body.
Q. What is method overriding w.r.t classes ?
A. Whenever a method in a subclass is defined with same definition as that of a method in base class, then this method is said to be overrided. This explains overriding mechanism.
Q. What is an Interface ?
A. Interface can be defined as the abstract class containing no concrete methods.
Q. What is Duck Duck Typing ?
A. In this, object type is not checked while invoking method or object. Python uses duck duck typing.
SET 7 – Q61 – Q70
Q. What are Exceptions ?
A. Exceptoins are run time errors that can be handled by a programmer. All these exceptions are represented as classes.
Q. Can you name some Exceptions that may occur during execution of a program ?
A. Arithmetic Exception, Type Error, Syntax Error, Assertion Error, EOF Error.
Q. How can we handle exceptions in Python ?
A. Using try, except, and finally.
Q. How a code behaves inside a finally block ?
A. Finally block is executed every time.
Q. Tell me the situation when finally block will not be executed ?
A. When we use sys.exit().
Q. What do you mean by monkey patching ?
A. Whenever a class is dynamically modified, then, it is known as monkey patching.
Q. What do you know about Numpy Package ?
A. It is a general purpose array processing package. It provides a high performance multidimensional array object and tools for working with these arrays. It is a fundamental package for scientific computing with python. It is used for fast searching, statistics, algebra, histogram etc.
Q. What are axes ?
A. In Numpy, dimensions are called axes. The number of axes, are referred to as rank.
Q. What is the role of strip() ?
A. strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed.
Q. What is the role of split() ?
A. It splits a string into a list where each word is a list item.
SET 8 – Q71 – Q80
Q. What is the concept of dictionary in python ?
A. Dictionary is an unordered collection of data items, it is used to store data values like a map.
It usually stores the data in the form of key-value pairs.
Q. How we can access key,values in python dictionary ?
Q. How to run a python program on Linux ?
A. Python 2 : python <filename>.py
Python 3 : python3 <filename>.py
Q. Explain the role of setTrace() method ?
A. It is present in sys module, responsible for monitoring the code flow of a program.
Q. Explain the concept of enumerate() ?
A. It is used to iterate through a sequence, it retrieves index as well as value at same time.
Q. Write python code for reading a file ?
Q. Why do we use with statement in file handling ?
A. It will auto close, a file it opens.
Q. Explain the purpose of tell() & seek() ?
A. tell() : It is knowing the position of file pointer.
seek() : It sets the new position of pointer.
Q. What is the role of encode() ?
A. It is to convert a string to byte.
Q. Explain regex ?
A. Python has a built-in package called re , which can be used to work with Regular Expressions.
SET 9 – Q81 – Q90
Q. Write a python code for retrieving all words starting with ‘a’ from a string ” mystring “.
A. res = re.findall(r ‘ a[\w]* ‘, mystring)
Q. What is a Thread ?
A. Thread is a smallest executable unit.
Q. How we can create threads in Python ?
Q. What is GIL ?
A. It is Global Interpreter Lock. It does not allow more than one thread to execute at a time.
Q. What are Daemon Threads ?
A. Daemon Threads are the threads that run continously. They are used for big processing system.
Q. How can we send email through Python code ?
Q. Write python code for connecting to database ?
Q. Write python program for finding unique words in a string.
Some questions on Object Oriented Programming
Q. Explain OOPS methodology ?
A. The entire OOPS methodology has been derived from a single root called object. In OOPS, all programs involve creation of classes and object. Five important features of OOPS are :
1. Classes & Objects
Q. What is Procedural oriented programming ?
A. It is the methodology where programming is done using procedures & functions.
SET 10 – Q91 – Q101
Q. Is Python an object oriented or object based programming language ?
Q. Explain Encapsulation with example ?
A. Encapsulation is a mechanism where the data and the code that act on the data will bind together.
Example : Class is an example of encapsulation. As class is the collection of data members and member functions, hence class binds them together.
Q. Explain Abstraction with example ?
A. Abstraction refers to the act of hiding the background details and providing only necessary details to the user.
Example : Let us the example of a car. While driving car, driver(user) only knows basic operations like gearing system, brakes, but is totally unaware about the internal happenings and processes. This is abstraction.
Q. Explain Polymorphism with example ?
A. Polymorphism represents the ability to assume several different forms of a program.
Example : Overloading of methods is an example of Polymorphism. Other examples include, abstract classes and interfaces.
Q. Explain Inheritance with example ?
A. Inheritance refers to the process in which child class inherits the properties of its parent class.
Example : Suppose we are having two classes A and B, so
class B(A) -> Child class B, is inheriting the property of its parent class A.
Some questions on Advanced Python
Q. What is Flask ?
A. Flask is a light weighted web micro framework, It is used to build web applications with Python.
Q. What is Django ?
A. It is an open source framework, to ease up the creation of complex database oriented websites.
Django contains prewritten code, unlike flask.
Q. What is Pyramid ?
A. It is a web framework for larger applications, they are heavily configurable.
Q. Explain SciPy ?
A. All numerical code resides inside SciPy. It is used for large and complex algebraic functions.
Q. What is use of MatplotLib ?
A. It provides basic 3D plotting.
Q. What is the role of PyChecker ?
A. PyChecker is the tool that help us find bugs or perform static analysis of code.
So, these are the 100 most asked interview questions on Python Programming Language.
We, at CODE OF GEEKS, wish you all the best for your upcoming future.