Python Interview
Python Interview
Python is a high-level, interpreted programming language known for its simplicity and readability.
Created by Guido van Rossum in the late 1980s, Python supports code readability and a clear syntax
that allows programmers to express concepts in fewer lines of code as compared to other languages.
1. Easy to Learn and Use: Python has a clean, simple, and small syntax that makes it easy for
beginners to understand and write code.
2. Versatile and Cross-Platform: Python can be used for a wide range of applications, including
web development, data analysis, scientific computing, artificial intelligence, machine
learning, automation, and more.
3. Interpreted and Interactive: Python is an interpreted language, which means that the code is
executed line by line without the need for explicit compilation.
4. Large Standard Library: Python comes with a comprehensive standard library that provides a
wide range of modules and functions for common tasks. It offers ready-to-use modules for
file I/O, networking, regular expressions, database access, and much more, reducing the
need for external dependencies.
6. Dynamic Typing: Python uses dynamic typing, which means that you don’t need to explicitly
declare variable types. The type of a variable is determined at runtime based on the assigned
value. This allows for flexibility and faster development but requires attention to type-related
issues.
Question 3: Name some Libraries of Python Programming language and their application?
Answer:
NumPy: It provides operations on multi-dimensional arrays, mathematical functions, and tools for
working with large datasets. In simple words it enables us to perform complex mathematical
operations.
NumPy is mainly used in data analysis, scientific calculations, and machine learning.
Pandas: This library is used for data manipulation and analysis. Pandas offers data structures (such as
DataFrames) and functions for cleaning, transforming and exploring structured data.
Matplotlib: This library for creating static, animated, and interactive visualizations in Python from the
data provided by the user. Matplotlib enables the creation of various plots, charts, and graphs,
making it a go-to choice for data visualization tasks.
TensorFlow: An open-source library for machine learning and deep learning. TensorFlow provides a
flexible ecosystem for building and deploying machine learning models, especially neural networks. It
is widely used in research, production-grade applications, and AI development.
Scikit-learn: A machine learning library that offers a range of algorithms and tools for data mining,
classification, regression, clustering, and dimensionality reduction. Scikit-learn simplifies the
implementation of machine learning models and pipelines.
Beautiful Soup: A library for web scraping and parsing HTML/XML documents. Beautiful Soup makes
it easy to extract data from web pages, navigate the HTML/XML structure, and scrape information for
various applications.
PyTorch: PyTorch is designed to take advantage of GPUs for fast computation in deep learning tasks.
It provides a tensor library that enables efficient data storage and manipulation on GPUs. PyTorch is
widely used in developing and training neural networks.
Question 4: What is the difference between Compiled Languages and Interpreted Languages?
Answer:
In the case of compiled languages, the source code is translated entirely into machine code by a
compiler before execution. The resulting compiled program can be directly executed by the
computer’s processor, providing fast and efficient performance.
Ex – C, C++, and Rust.
And in the case of Interpreted language, an interpreter reads and executes the source code line by
line at runtime. The interpreter translates each line of code into machine code while the program is
running.
Answer: Module is a file containing Python definitions, functions, classes, and variables. It acts as a
container for related code and can be imported into other Python programs using the import
statement. Modules help in modularizing code and promote code reuse.
4. os: Allows interaction with the operating system, providing functions for file operations,
directory handling, etc.
10. sqlite3: Provides a simple and lightweight database interface for SQLite database
Example:
import math
value = [Link]
print("Value of Pi = : ",value)
Answer:
In python, arguments are passed through reference. This means that when a function is called and
an argument is passed, a reference to the object is passed in place of the value itself.
Answer: Floor division in Python is denoted by the double forward slash operator //. It performs
division between two numbers and returns the largest integer less than or equal to the
quotient. Code Ex –
Result = 10 // 3
print(Result)
Output: 3
Answer:
range() function in Python allows to create a sequence of numbers that can be used for iteration. It
can be used to create a range of numbers with a specified start, stop, and step value.
[ i.e. range( start, stop, steps) ]
Code Ex –
for i in range(10):
print(i) #Output: 0 1 2 3 4 5 6 7 8 9
print(j) #Output: 0 2 4 6 8
Allows duplicate Allows duplicate elements. Keys are unique, and values can be Doesn
elements. duplicated. duplica
eleme
Elements are Elements are enclosed in Elements are enclosed in curly braces { }, Eleme
enclosed in square parentheses ( ) or can be with each item consisting of a key and its enclos
brackets [ ]. without any enclosure. value separated by a colon : braces
Ex- fruits = Ex- numbers = (“Twenty”, Ex- assassin = {“name”: “John Wick”, Ex- nu
[“apple”, “banana”, 20, “Thirty”) “age”: 28, “major”: “Self Defence & 2, 3, 4
“orange”, “grape”] Martial Art”}
Question 9: What is the difference between data structures like list, tuples, dictionaries and sets in
python ?
Answer:
Negative indexing allows us to access elements from the end of a sequence by using negative
numbers as their indices.
Last element has an index of -1
Second last has an index of -2
Third last has an index of -3 and so on.
*args (pronounced “star args”) allows you to pass multiple number of arguments to a function
without specifying their names in advance. It collects all the arguments into a tuple, which you can
access within the function.
def prac_function(*args):
print(ARG)
prac_function(1,2,3,4,5,6) #Output: 1 2 3 4 5 6
**kwargs (pronounced “star star kwargs”) allows you to pass multiple number of keyword
arguments to a function. Keyword arguments are like labeled items you put into the bag. **kwargs
collects these labeled items into a dictionary, where the labels (keywords) become the keys and the
values are the corresponding items.
def prac_function(**kwargs):
print(key, value)
sliced = my_list[2:6]
sliced = my_list[-3:]
Question 13: What is the Lambda expressions in Python? Explain with an example.
Answer:
Lambda expressions are a way to quickly create what are known as anonymous functions, basically
just, one-time-use functions that you don’t even really name. You just use them one time and then
never reference them again.
Code Ex-
add = lambda x, y: x + y
result = add(20,15)
print(result) #Output: 35
Answer:
PEP 8 is a guide that helps in writing clean, consistent, and maintainable Python code that is easy to
read and understand. It stands for Python Enhancement Proposal, it specifically provides guidelines
and recommendations on how to format and structure Python code to enhance readability and
reliability of the code.
Some key points of PEP 8 include:
2. Line Length: Limit lines to a maximum of 79 characters to ensure readability, although it can
be extended up to 120 characters in certain cases.
3. Naming Conventions
5. Imports: Import modules on separate lines and follow a specific ordering convention
(standard library modules, third-party modules, local modules).
6. It also provides numerous other guidelines covering various aspects of coding style, including
whitespace, blank lines, operator spacing, and more.
Answer:
.py files:
2. They are human-readable and editable using a text editor or integrated development
environment (IDE).
.pyc files:
1. These files are compiled bytecode files generated by the Python interpreter.
3. The Python interpreter compiles the .py source code into bytecode and saves it as a .pyc file
for efficient execution in subsequent runs.
4. The .pyc files speed up the loading and execution of Python programs since the interpreter
can directly execute the bytecode without the need for recompilation.
Question 16: What are the types of literals in Python?
Answer:
1. Numeric Literal: Numeric literals can be floating-point values, integers, or complex numbers.
2. Character Literal: A character literal consists of a single character enclosed in double quotes.
4. Literal Collections: There are four types of literal collections, including list literals, tuple
literals, set literals, and dictionary literals.
5. String Literal: String literal is created by assigning text to a variable using single or double
quotes. Multiline literals can be formed by enclosing text within triple quotes.
Answer:
Numeric Types:
2. float: Represents floating-point numbers with decimal values (e.g., 3.14, -0.5).
Sequence Types:
1. str: Represents a sequence of characters, also known as strings (e.g., “hello”, ‘world’).
2. list: Represents an ordered collection of items (e.g., [1, 2, 3], [‘apple’, ‘banana’]).
3. tuple: Represents an ordered, immutable collection of items (e.g., (1, 2, 3), (‘a’, ‘b’, ‘c’)).
Mapping Type:
dict: Represents a collection of key-value pairs (e.g., {‘name’: ‘John’, ‘age’: 25}).
Set Types:
Boolean Type:
None Type:
Answer:
Pickling:
1. Pickling is the process of converting a Python object hierarchy into a byte stream.
2. It allows you to save the state of an object or a collection of objects as a file or transfer it
over a network.
3. The resulting byte stream can be stored persistently or transmitted between different
systems.
4. Pickling is commonly used for tasks like caching, serialization, and data persistence.
Unpickling:
1. Unpickling is the process of reconstructing a Python object hierarchy from a byte stream.
2. It is the reverse operation of pickling and allows you to restore the state of the objects.
3. By unpickling, you can retrieve the original object or data structure that was pickled.
4. Unpickling is essential when you want to retrieve and utilize the saved data or objects.
Answer:
1. Memory management in Python is handled by a private heap space. All Python objects and
data structures are stored within this private heap, which remains inaccessible to
programmers. The responsibility of managing this private heap lies with the Python
interpreter.
2. The allocation of heap space for Python objects is handled by Python’s memory manager.
Although programmers do not have direct access to this process, Python’s core API provides
certain tools that can be utilized.
3. Python incorporates an internal garbage collector that is responsible for reclaiming unused
memory. This ensures that memory becomes available within the heap space for future
utilization.
Answer:
Shallow Copy:
Shallow copy creates a new object and then copies the references of the original object’s
elements into the new object.
The new object and the original object share the same elements (references), so changes
made to one object may affect the other.
In a shallow copy, the top-level elements are copied, but the nested objects within them are
not duplicated.
Shallow copies are created using methods like slicing, the `copy()` method, or the `copy`
module.
Deep Copy:
Deep copy creates a new object and recursively copies all the elements and nested objects of
the original object.
The new object is completely independent of the original object, and any changes made to
one object do not affect the other.
Deep copies ensure that all levels of the object hierarchy are duplicated, including nested
objects and their references.
Deep copies are created using the `[Link]()` function from the `copy` module.
Answer:
1. CPython: The default and most widely used Python interpreter. It is written in C and serves
as the reference implementation for the Python language.
2. Jython: An implementation of Python that runs on the Java Virtual Machine (JVM). It allows
seamless integration with Java code and libraries.
4. PyPy: A fast and highly optimized implementation of Python. It utilizes a Just-in-Time (JIT)
compiler to improve execution speed.
5. Stackless Python: A variant of CPython that provides support for micro threads, allowing
lightweight concurrency without the need for traditional operating system threads.
Answer:
Run
def fibonacci(n):
series = [ ]
a, b = 0, 1
[Link](a)
a, b = b, a + b
return series
fibonacci_series = fibonacci(n)
print("Fibonacci series:", fibonacci_series)
Answer:
Django is a high-level, full-featured web Pyramid is a flexible, minimalist web Flask is a lightweight web
framework that follows the batteries framework that follows the “pay only framework that has simplicity
included methodology. for what you need”. and extensibility.
It provides a huge set of built-in features, It provides a core set of tools for It provides the resources for
such as an ORM (Object-Relational building web applications, allowing building web applications but
Mapping), authentication, routing, developers to choose and add keeps the core framework
templating, and admin interface. additional components as needed. minimalistic.
Django is suitable for building complex, Pyramid is highly customizable and Flask allows developers to
database-driven web applications with adaptable, making it suitable for a choose extensions based on
less code and rapid development. wide range of applications, from their specific requirements,
simple to complex. making it highly modular.
It enforces a specific project structure It follows a “traversal” routing system It follows a route-decorator
and follows the Model-View-Controller and supports various templating approach and supports various
(MVC) architectural pattern. engines. templating engines.
Answer:
Dynamically Typed: In dynamically typed languages, variable types are determined at runtime,
meaning that type checking occurs during program execution. Variables can be assigned values of
different types at different points in the program.
Code Ex-
Run
x = 10 # x is an integer
print(x)
print(x)
print(x)
Statically Typed: In statically typed languages, variable types are checked and resolved during
compile-time, before the program is executed. Variables must be explicitly declared with their types,
and type checking is performed at compile-time.
Code Ex-
#include<bits/stdc++.h>
int main ()
int x = 5; // x is an integer
x = "Hello";
return 0;
Question 25: What is OOPs Concepts? Explain all of them with examples.
Answer:
1. Encapsulation:
Encapsulation is the process of hiding the internal implementation details of an object and exposing
only the necessary information. It helps in achieving data security and code maintainability.
Ex-
Run
class Car:
[Link] = brand
[Link] = model
def start_engine(self):
print("Engine started.")
print(my_car.brand)
Output: Ford
my_car.start_engine() #Output: Engine started
2. Inheritance:
Inheritance is a mechanism where a class inherits properties and methods from a parent class. It
allows code reuse and the creation of specialized classes based on more general classes.
Ex-
Run
class Animal:
[Link] = name
def speak(self):
print("Animal speaks.")
class Dog(Animal):
def speak(self):
print("Woof!")
my_dog = Dog("Buddy")
print(my_dog.name)
Output: Buddy
3. Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common base class. It
provides flexibility and extensibility in handling objects of different types.
Ex-
Run
class Shape:
def area(self):
pass
class Rectangle(Shape):
[Link] = width
[Link] = height
def area(self):
return [Link] * [Link]
class Circle(Shape):
[Link] = radius
def area(self):
print([Link]())
4. Abstraction:
Abstraction involves representing essential features of an object while hiding the unnecessary
details. It allows programmers to work with high-level concepts without worrying about
implementation specifics.
Ex-
Run
class Shape(ABC):
def area(self):
pass
class Rectangle(Shape):
[Link] = width
[Link] = height
def area(self):
class Circle(Shape):
[Link] = radius
def area(self):
my_rectangle = Rectangle(4, 5)
my_circle = Circle(3)
print(my_rectangle.area()) #Output: 20
reversed_sequence = sequence[::-1]
if sequence == reverse_sequence:
print("Palindrome Sequence.")
else:
print("Not a Palindrome.")
PIP (Python Package Installer) is the default package manager for Python. It is a command-line tool
that allows you to easily install, manage, and uninstall Python packages from the Python Package
Index (PyPI) or other package repositories.
4. pip freeze > [Link]: Exports a list of installed packages and their versions to a
[Link] file.
Question 28: Elaborate the concept of Dictionaries with the help of Example.
Run
# Creating a dictionary
student = {
"age": 28,
print("Name:", student["name"])
print("Age:", student["age"])
print("Major:", student["major"])
print("University:", student["university"])
Answer:
Docstring is a string literal used to document modules, classes, functions, and methods. It serves as a
documentation tool to describe the purpose, behavior, parameters, return values, and other
important details of the code.
A docstring is enclosed in triple quotes (single or double) and is typically placed as the first line after
the definition of a module, class, function, or method. It can span multiple lines and supports both
single-line and multi-line docstrings.
Run
def hello(name):
"""
This function says hello to the person with the given name.
"""
print(hello("Isabelle"))
Question 30: What are python namespaces? What are their applications?
Answer:
Namespace is a mapping from names (identifiers) to objects. It serves as a system to organize and
provide a unique context for names in a Python program. Namespaces help prevent naming conflicts
and provide a way to access objects in a structured manner.
Python uses namespaces to determine the scope of names. When you use a variable, function, or
any other object, Python looks for that name within the available namespaces to resolve it.
1. Built-in Namespace: It contains the names of built-in functions, exceptions, and objects that
are available by default in Python. Examples include print(), len(), str, etc.
2. Global Namespace: It refers to the names defined at the top level of a module or declared as
global within a function. These names are accessible throughout the module or function.
3. Local Namespace: It represents the names defined within a function. These names are
accessible only within the function’s scope.
4. Class Namespace: It contains the names defined within a class. These names are accessible
within the class and can be accessed using the class name.
Question 38: What is PythonPath?
PYTHONPATH is an environment variable in Python that tells the interpreter where to look for
Python modules and packages.
It is a list of directory paths separated by colons (on Unix-based systems) or semicolons (on
Windows). When you import a module or package, Python searches for it in the directories listed
in PYTHONPATH. It allows you to specify additional directories outside the default ones where
your Python code resides, enabling easy access to custom modules or packages.
Global variables are declared outside any function or block and can be accessed from anywhere
within the program. They have a global scope, meaning they are visible to all functions and
blocks within the program.
Ex:
x = 10
def print_global():
print(x)
print_global()
# Output: 10
Local variables are declared within a function or block and can only be accessed within that
specific function or block. They have a local scope, meaning they are visible and accessible only
within their respective function or block.
Ex:
def print_local():
y = 20
print(y)
print_local()
# Output: 20
Continue, break, and pass are three control flow statements in Python that allow you to change the
flow of your program under certain conditions.
Continue statement: When continue is used inside a loop, it tells Python to skip the current iteration
and move on to the next one. Any code after the continue statement within the loop for that
iteration will be ignored, and the loop will continue with the next iteration.
Break statement: When break is used inside a loop, it tells Python to immediately exit the loop,
regardless of any remaining iterations. Any code after the break statement within the loop will be
skipped, and the program will continue executing from the next statement after the loop.
Pass statement: pass is used as a placeholder when you need to have a statement for syntactic
reasons, but you don’t want to do anything in that part of the code. It doesn’t do anything and is
mainly used to avoid syntax errors when you’re still working on implementing certain parts of your
code.
Class is a blueprint or a template that defines the structure and behavior of objects. It is like a
blueprint for creating multiple instances of similar objects with shared characteristics and
functionalities.
It contains data (in the form of attributes or properties) and behaviors (in the form of methods or
functions) that define the objects’ characteristics and actions. It provides a way to organize related
data and functions into a single unit.
An object, on the other hand, is an instance of a class. It represents a specific entity or item created
based on the class definition. Objects have their own unique state and can interact with other
objects or perform operations defined within the class.
Adding values:
2. extend(): Appends multiple elements from an iterable to the end of the array.
Removing values:
1. remove(): Removes the first occurrence of a specific element from the array.
2. pop(): Removes and returns an element at a specified index from the array.
Django provides a wide range of built-in features and components, reducing the need for external
libraries or packages.
Scalability: Django has proven to be scalable and has been used successfully in handling
high-traffic websites and complex applications.
Larger Community: Django has a large and active community, offering extensive
documentation, tutorials, and reusable packages.
Flask, on the other hand, is a lightweight micro-framework that offers more flexibility and
customization options.
It is suitable for smaller projects, APIs, or situations where simplicity and control are desired. Flask
allows developers to have more control over the architecture and components they use but lacks
some of the built-in functionalities provided by Django.
Conclusion is that Django’s comprehensive feature set, strong community support, and emphasis on
convention-over-configuration make it a preferred choice for many web development projects.
Multithreading can be achieved in various programming languages, including Python, by utilizing the
operating system’s threading capabilities or using libraries that provide threading functionality.
2. Define a task or function: Create a function or task that you want each thread to execute
concurrently. This function represents the work that will be performed by each thread.
3. Create thread objects: Instantiate thread objects from the Thread class provided by the
threading module. Specify the target function or task to be executed by each thread. You can
also pass any required arguments to the target function.
4. Start the threads: Call the start() method on each thread object to start the execution of the
threads. Each thread will begin running concurrently.
Wait for thread completion: If needed, use the join() method on each thread to wait for its
completion. This ensures that the main program doesn’t proceed until all threads have finished their
execution.
Question 3: What are some real life applications of Python ?
Data Science.
Game Development.
Software Development
`__init__` is a special method in Python classes known as the constructor. It is automatically called
when an object of the class is created and is used to initialize the object’s attributes or state.
Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.
print (list1)
print(-10 // 3)
2 ** 3 ** 2
/\/\/\/\/\
str = "vemana"
print(str[2:7:-2])
num = 2E3
print(type(num))
OOPS
1.
What will be the output?
class A:
x=5
a = A()
b = A()
a.x = 10
2.
What will be printed?
class A:
def __init__(self):
print("A")
class B(A):
def __init__(self):
print("B")
obj = B()
A) A
B) B
C) A B
D) Error
3.
What will be the output?
class A:
def show(self):
print("A")
class B(A):
pass
obj = B()
[Link]()
A) A
B) B
C) Error
D) None
4.
What will be printed?
class Test:
def __init__(self):
self.a = 10
obj1 = Test()
obj2 = Test()
obj1.a = 20
print(obj2.a)
A) 10
B) 20
C) Error
D) None
5.
What will be the output?
class A:
val = 1
class B(A):
val = 2
class C(B):
pass
print([Link])
A) 1
B) 2
C) Error
D) None
6.
What will be printed?
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
obj = B()
[Link]()
A) A
B) B
C) A B
D) Error
7.
What will be the output?
class Test:
x = 10
def __init__(self):
self.x = 20
obj = Test()
print(obj.x)
A) 10
B) 20
C) Error
D) None
8.
What will be printed?
class Demo:
def show(self):
print("Hello")
d = Demo()
[Link](d)
A) Hello
B) Error
C) None
D) Demo
9.
What will be the output?
class A:
def show(self):
print("A")
class B:
def show(self):
print("B")
obj = C()
[Link]()
A) A
B) B
C) Error
D) None
10.
What will be printed?
class A:
def __init__(self):
print("Constructor")
obj1 = A()
obj2 = A()
A) Constructor
B) Constructor Constructor
C) Error
D) None
11.
What will be printed?
class A:
x = []
a = A()
b = A()
[Link](1)
print(b.x)
A) []
B) [1]
C) Error
D) None
12.
What will be the output?
class A:
def __init__(self):
self.x = 10
class B(A):
def __init__(self):
super().__init__()
self.x += 5
obj = B()
print(obj.x)
A) 10
B) 15
C) 5
D) Error
13.
What will be printed?
class A:
x=5
a = A()
b = A()
A.x = 10
print(a.x, b.x)
A) 5 5
B) 10 10
C) 5 10
D) Error
14.
What will be printed?
class Demo:
def __init__(self, x):
self.x = x
d = Demo(5)
print(d.x)
A) 5
B) Error
C) None
D) Demo
15.
What will be the output?
class A:
def show(self):
print("A")
class B(A):
pass
b = B()
[Link](b)
A) A
B) B
C) Error
D) None
16.
What will be printed?
class A:
x = 10
def change(self):
self.x = 20
obj = A()
[Link]()
print(A.x)
A) 10
B) 20
C) Error
D) None
17.
What will be the output?
class A:
def show(self):
print("A")
class B(A):
def display(self):
[Link]()
obj = B()
[Link]()
A) A
B) B
C) Error
D) None
18.
What will be printed?
class A:
pass
a = A()
print(type(a))
A) class
B) A
C) <class 'main.A'>
D) Error
19.
What will be the output?
class A:
def __init__(self):
print("Init")
def __del__(self):
print("Del")
obj = A()
del obj
A) Init
B) Del
C) Init Del
D) Error
20.
What will be printed?
class A:
x=5
def __init__(self):
A.x += 1
obj1 = A()
obj2 = A()
print(A.x)
A) 5
B) 6
C) 7
D) Error