0% found this document useful (0 votes)
11 views27 pages

Python Interview

The document provides an introduction to Python, highlighting its features such as simplicity, versatility, and a large standard library. It covers various topics including key libraries, differences between compiled and interpreted languages, and concepts like modules, slicing, and memory management. Additionally, it explains advanced topics like pickling, deep copy vs shallow copy, and PEP 8 guidelines for writing clean code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Python Interview

The document provides an introduction to Python, highlighting its features such as simplicity, versatility, and a large standard library. It covers various topics including key libraries, differences between compiled and interpreted languages, and concepts like modules, slicing, and memory management. Additionally, it explains advanced topics like pickling, deep copy vs shallow copy, and PEP 8 guidelines for writing clean code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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.

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

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

Example:

import math

value = [Link]

print("Value of Pi = : ",value)

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 –

Result = 10 // 3

print(Result)

Output: 3

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 –

for i in range(10):

print(i) #Output: 0 1 2 3 4 5 6 7 8 9

for j in range(0, 10, 2):

print(j) #Output: 0 2 4 6 8

List Tuples Dictionaries Sets

Ordered collection Ordered collection of Collection of key-value pairs. Unord


of items. items. And Unordered (no specific order of collecti
elements). unique

Mutable (can be Immutable (cannot be Mutable Mutab


modified after modified after creation).
creation).

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 ?

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.

def prac_function(*args):

for ARG in 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):

for key, value in [Link]():

print(key, value)

prac_function(Name='Viraj', Age=22, City='Lucknow')

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-

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sliced = my_list[2:6]

print(sliced) #Output: [3, 4, 5, 6]

# Slicing with negative indices to get the last three elements

sliced = my_list[-3:]

print(sliced) #Output: [8, 9, 10]

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

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

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.

Answer:

Run

def fibonacci(n):

series = [ ]

a, b = 0, 1

while len(series) < n:

[Link](a)

a, b = b, a + b

return series

n = int(input("Enter number of terms in the Fibonacci series: "))

fibonacci_series = fibonacci(n)
print("Fibonacci series:", fibonacci_series)

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

Answer:

Django Pyramid Flask

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.

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-

Run

# Dynamically typed language example (Python)

x = 10 # x is an integer

print(x)

x = "Ten" # x is now a string

print(x)

x = [10, 20, 30] # x is now a list

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>

using namespace std;

int main ()

int x = 5; // x is an integer

cout << x << endl;

x = "Hello";

cout << x << endl;

return 0;

// Error: invalid conversion from 'const char*' to 'int'

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:

def __init__(self, brand, model):

[Link] = brand

[Link] = model

def start_engine(self):

print("Engine started.")

my_car = Car("Ford", "Mustang")

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:

def __init__(self, name):

[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

my_dog.speak() #Output: Woof!

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):

def __init__(self, width, height):

[Link] = width

[Link] = height

def area(self):
return [Link] * [Link]

class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14 * [Link] ** 2

shapes = [Rectangle(4, 5), Circle(3)]

for shape in shapes:

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

from abc import ABC, abstractmethod

class Shape(ABC):

def area(self):

pass

class Rectangle(Shape):

def __init__(self, width, height):

[Link] = width

[Link] = height

def area(self):

return [Link] * [Link]

class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14 * [Link] ** 2

my_rectangle = Rectangle(4, 5)

my_circle = Circle(3)
print(my_rectangle.area()) #Output: 20

print(my_circle.area()) #Output: 28.26

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

sequence = input ("Enter a sequence = ")

reversed_sequence = sequence[::-1]

if sequence == reverse_sequence:

print("Palindrome Sequence.")

else:

print("Not a Palindrome.")

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 > [Link]: Exports a list of installed packages and their versions to a
[Link] file.

5. pip install -r [Link]: Installs packages listed in a [Link] file.

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

Run

# Creating a dictionary

student = {

"name": "John Wick",

"age": 28,

"major": "Martial Arts and Self Defence.",

"university": "Shaolin University"

# Accessing dictionary values

print("Name:", student["name"])

print("Age:", student["age"])
print("Major:", student["major"])

print("University:", student["university"])

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.

Run

def hello(name):

"""

This function says hello to the person with the given name.

Parameters: name (str): The name of the person to be greeted.

Returns: str: A greeting message.

"""

return "Hello, " + 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.

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

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

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

1. What is the output?


x = []
if x:
print (x, "True)
else :
print (x," False")

2. What is the output?


P = (3,5)
Q=0
R = False
if P or Q and R :
print "True "
else:
print "False "

3. What is the output?


list1 = [“ABC,”XYZ,”PQR”]
for i in listl :
[Link]( )

print (list1)

4. What is the output?


list1 = ["abc","123"]
for i in list1:
[Link] (i)
print(list1)

5. Guess the output of the following Python code:

print(-10 // 3)

6. What is the output of the following expression in Python?

2 ** 3 ** 2

7. Write a Python statement to print the following output:

/\/\/\/\/\

8. Guess the output of the following Python code:

str = "vemana"
print(str[2:7:-2])

9. What is the output of the following Python code?

my_dict = {"jay":65, "viru":54, "jay":45}


print(len(my_dict))

10. What is the output of the following Python code?

num = 2E3
print(type(num))

11. What happens when the following Python code is executed?

for i in 674 < 3:


print(i)

5. What is the output?


6. What is the output?
7. What is the output?
8. What is the output?
9. What is the output?
10. What is the output?
11. What is the output?
12. What is the output?
13. What is the output?

OOPS
1.
What will be the output?
class A:
x=5

a = A()
b = A()

a.x = 10

print(A.x, a.x, b.x)


A) 5 10 5
B) 10 10 10
C) 5 5 5
D) 10 5 5

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")

class C(A, B):


pass

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

You might also like