0% found this document useful (0 votes)
3 views24 pages

Python interview qustions

The document provides an introduction to Python, highlighting its simplicity, readability, and versatility for various applications such as web development and data analysis. It includes key features, benefits, and commonly used libraries, along with a series of interview questions and answers covering Python concepts, data structures, and object-oriented programming principles. The document serves as a comprehensive guide for beginners and those preparing for Python-related interviews.

Uploaded by

nidhiboriwar1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views24 pages

Python interview qustions

The document provides an introduction to Python, highlighting its simplicity, readability, and versatility for various applications such as web development and data analysis. It includes key features, benefits, and commonly used libraries, along with a series of interview questions and answers covering Python concepts, data structures, and object-oriented programming principles. The document serves as a comprehensive guide for beginners and those preparing for Python-related interviews.

Uploaded by

nidhiboriwar1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

Introduction To Python

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.

Here are some key features of Python:

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.

5. Third-Party Ecosystem: Python has a thriving ecosystem of third-party libraries and


frameworks maintained by the community. These libraries extend Python’s
capabilities and offer specialized tools for specific domains, such as Django and Flask
for web development, NumPy and Pandas for data manipulation, TensorFlow and
PyTorch for machine learning, and many others.

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.

Python Interview Questions


Question 1: Tell something about Python ?

Answer: Python is a general-purpose, high-level, and interpreted programming


language. Python supports objects, modules, exception-handling, threads, and automatic
memory management which help in solving real-world problems with less coding.

Question 2: What are the benefits of using Python?

Answer: Python benefits:

1. Readable and simple syntax.


2. Large standard library.

3. Wide variety of third-party libraries and frameworks.

4. Easy integration with other languages.

5. Powerful for data analysis and scientific computing.

6. Ideal for automation and scripting.

Question 3: Name some Libraries of Python Programing 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.

Ex- Python, JavaScript, and Ruby.

Question 5: What is a module in Python with example?

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.

“Import” is used to get all functionalities of any particular module.

Ex-
Python provides a wide range of built-in modules that offer various functionalities like:

1. math: Provides mathematical functions and constants.

2. random: Offers functions for generating pseudo-random numbers.

3. datetime: Enables manipulation of dates, times, and time intervals.

4. os: Allows interaction with the operating system, providing functions for file
operations, directory handling, etc.

5. sys: Provides access to system-specific parameters and functions.

6. json: Enables encoding and decoding of JSON data.

7. re: Provides regular expression matching operations.

8. csv: Offers functionality for reading and writing CSV files.

9. urllib: Allows making HTTP requests and working with URLs.

10. sqlite3: Provides a simple and lightweight database interface for SQLite database

Question 6: In python, arguments are passed by reference or 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.

Question 7: What is the use of Floor Division (//) in python?


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 –

Question 8: What is the use Range function in python ?

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.

Question 11: What are *args and **kwargs in python?

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 12: What is Slicing ?

Answer: Slicing is a technique used to extract a part or a subsequence of a sequence, such


as a string, list, or tuple. It allows you to retrieve a specific range of elements or specific
element from the sequence based on indices.

Basic syntax for slicing = “sequence_name[start:stop:step]”


Code Ex-

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-

Question 14: What is PEP 8 ?

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.

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

4. Function and Variable Names

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.

Question 15: What are .py and .pyc files ?

Answer: py files:

1. These files contain Python source code written in plain text.

2. They are human-readable and editable using a text editor or integrated development
environment (IDE).

3. Python source code is typically saved with the .py extension.

.pyc files:

1. These files are compiled bytecode files generated by the Python interpreter.

2. They are not human-readable and cannot be edited directly.

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.

3. Boolean Literal: The boolean literals are True or False.

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.

Question 17: What are some built in data types in python ?

Answer: Numeric Types:

1. int: Represents integer values (e.g., 1, 5, -10).

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:

set: Represents an unordered collection of unique elements (e.g., {1, 2, 3}).

Boolean Type:

bool: Represents the truth values True and False.

None Type:

None: Represents the absence of a value or the null value.

Question 18: What is pickling and Unpickling in Python ?

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.

Question 19: How memory is managed in python programming language ?

Answer: In Python, memory management operates in the following manner:

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.

Question 20: What are Deep Copy and Shallow Copy ?

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 `copy.deepcopy()` function from the `copy`
module.

Python OOPS Interview Questions


Question 21: List some common Python interpreters.

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.

3. IronPython: An implementation of Python targeting the .NET framework. It provides


integration with the .NET ecosystem and allows Python code to interact with .NET
languages 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.

6. MicroPython: A lightweight implementation of Python specifically designed for


microcontrollers and embedded systems. It provides a reduced subset of the Python
language to optimize for limited resources.

Question 22: Write a program to produce the Fibonacci series in Python.

Question 23: Differentiate between Pyramid, Django, and Flask.


Question 24: What is Dynamically typed and Statically typed languages ?

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:

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-

Question 26: Write a python program to checks if a sequence is a Palindrome or not.


Question 27: What is PIP ? Name some common PIP Command.

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.

Some Common PIP Command are:

1. pip install package_name: Installs a Python package.

2. pip uninstall package_name: Uninstalls a Python package.

3. pip list: Lists all installed packages.

4. pip freeze > requirements.txt: Exports a list of installed packages and their versions
to a requirements.txt file.

5. pip install -r requirements.txt: Installs packages listed in a requirements.txt file.

Question 28: Elaborate the concept of Dictionaries with the help of Example.

Question 29: What is docstring in Python?

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 ?

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.

Here are a few types of namespaces in Python:

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.

Python Libraries Interview Questions


Question 31: Write a program in Python to check if a number is prime.
Question 32 : Python program to print following ‘*’ pattern:
*
**
***
****
*****

Question 33 : Python program to print following ‘*’ pattern:


****
***
**
*

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:

*
**
***
****
*****

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.

Question 39: What are Global and Local Variable ?

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:

Question 40: Make a Binary search program in Python


Python Interview Questions for Experienced
Question 41: Make a linear search program in python.

Question 42: What is map() function ?

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.

Question 43: How does continue, break, and pass work?

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.

Question 44: What are Classes and Objects ?

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.

Question 45: Write a python code to illustrate classes and object.

Questi
on 46: How to add values or remove values to a python array?
Adding values:

1. append(): Adds an element to the end of the array.

2. extend(): Appends multiple elements from an iterable to the end of the array.

3. insert(): Inserts an element at a specific index within 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.

3. del statement: Deletes an element or a slice of elements from the array.

Question 47: Which python framework is best flask or django ?

Django provides a wide range of built-in features and components, reducing the need for
external libraries or packages.

 Rapid development: Django’s high-level abstractions and conventions simplify the


development process, allowing you to build applications quickly.

 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.

 Better Security Module: Django incorporates security features by default, including


protection against common vulnerabilities.

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.

Question 48: What is multi threading and how it can be achieved ?

Multithreading is a programming technique that allows multiple threads of execution to run


concurrently within a single process. A thread is a lightweight unit of execution within a
program that can perform tasks independently.
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.

Here are the basic steps to achieve multithreading in Python:

1. Import the threading module: In Python, multithreading is facilitated by the built-in


threading module. Import the module to gain access to its classes and functions.

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

2. DSA Based Coding

3. File Handling

4. Libraries

5. Supported Frameworks
.etc.

Question 2: In an Interview how do we explain why we chose Python ?

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.

Question 3: What are some real life applications of Python ?

Python is widely used for the following fields:

 Web Scraping Applications.

 Data Science.

 Artificial Intelligence and Machine Learning.

 Game Development.

 Software Development

 Web Development, etc.

Question 4: What is __init__ function ?

`__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.

Question 5: Why is Python best for scripting?

Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.

You might also like