Python interview qustions
Python interview qustions
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.
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 Programing language and their application?
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.
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.
Ex-
Python provides a wide range of built-in modules that offer various functionalities like:
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
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: 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 –
Question 9: What is the difference between data structures like list, tuples, dictionaries
and sets in python ?
Question 10: What is a Negative Index in Python? Give an Example.
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.
Answer: *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.
**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.
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-
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:
1. Indentation: Use 4 spaces for indentation to improve code readability.
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.
Answer:
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.
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.
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:
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.
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.
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 `copy.deepcopy()` 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.
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: 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-
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-
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-
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-
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-
4. Abstraction:
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 > requirements.txt: Exports a list of installed packages and their versions
to a requirements.txt file.
Question 28: Elaborate the concept of Dictionaries with the help of Example.
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.
Ques
tion 30: What are python namespaces ? What are their applications ?
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.
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 34 : Write a python program to perform bubble sort for given array.
Question 35 : Write a python program to perform merge sort for given array.
Question 36 : Write a python program to perform merge sort for given array.
Ques
tion 37 : Write a python program to print Star (*) Triangle:
*
**
***
****
*****
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
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:
map() function in Python is a built-in function that allows you to apply a specified function
to every item in one or more iterable objects, such as lists, tuples, or strings. It takes in two
or more arguments: the function to be applied and the iterable(s) on which the function
should operate.
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.
Questi
on 46: How to add values or remove values to a python array?
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.
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 49: Write the python code to perform Write and Read operation in Python ?
Question 50: Write the python code to append operation in existing file ?
FAQs related to Python Technical Interview
Question 1: What questions are asked in Technical Interview in Python Programming
Language?
The common topics that are included in Python Technical Interview are:
1. Basic Syntax
3. File Handling
4. Libraries
5. Supported Frameworks
.etc.
Due to its clean, simple and small syntax with Wide variety Libraries Support makes Python
easy – to – learn language. It is Dynamically Typed Languages which makes it more easier
language to understand.
Data Science.
Game Development.
Software Development
Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.