You are on page 1of 29

What isDictionaries?Explain following functionswith example.

i) len()
) cmp( )
iii) update( )
iv) get()

In programming, a dictionary is a data structure that stores a collection


of key-value pairs. Each key in the dictionary maps to a specific value,
and the keys are unique within the dictionary. Dictionaries are also
known as associative arrays, maps, or hashmaps in other programming
languages. They provide a way to efficiently retrieve values based on
their corresponding keys.

Python is a programming language that supports dictionaries. Let's


explore the functions you mentioned with examples:

i) len():
The len() function is used to get the number of items in a dictionary,
i.e., the count of key-value pairs present in the dictionary.

Example:

python
Copy code
# Creating a dictionary
my_dict = {'apple': 3, 'banana': 6, 'orange': 4, 'grape': 12}

# Getting the number of items in the dictionary using len()


dict_length = len(my_dict)

print("Number of items in the dictionary:", dict_length) # Output: 4


ii) cmp():
In Python 2, cmp() was used to compare two dictionaries. It returned -1
if the first dictionary was smaller, 0 if both were equal, and 1 if the
first dictionary was larger. However, starting from Python 3, cmp() is no
longer available. Instead, you can use comparison operators like <, <=,
>, >=, ==, and != to compare dictionaries.

Example (for Python 2 only):

python

# Dictionary 1
dict1 = {'a': 1, 'b': 2, 'c': 3}

# Dictionary 2
dict2 = {'a': 1, 'b': 2, 'c': 3}

# Compare dictionaries (Python 2 only)


result = cmp(dict1, dict2)

print("Comparison result:", result) # Output: 0 (both dictionaries are


equal)
iii) update():
The update() method is used to update or add multiple key-value pairs to
a dictionary at once. It takes another dictionary (or an iterable of key-
value pairs) as an argument and adds or updates the keys and their
corresponding values in the original dictionary.

Example:

python

# Original dictionary
my_dict = {'apple': 3, 'banana': 6}

# Dictionary to update with


new_data = {'orange': 4, 'grape': 12}

# Updating the original dictionary with the new data


my_dict.update(new_data)

print("Updated dictionary:", my_dict)


# Output: {'apple': 3, 'banana': 6, 'orange': 4, 'grape': 12}
iv) get():
The get() method is used to retrieve the value of a specified key from
the dictionary. It takes the key as the argument and returns the
corresponding value. If the key is not found in the dictionary, it can
return a default value provided as the second argument (optional).

Example:

python
Copy code
# Dictionary
my_dict = {'apple': 3, 'banana': 6, 'orange': 4, 'grape': 12}

# Retrieving the value for the key 'orange'


orange_count = my_dict.get('orange')

print("Number of oranges:", orange_count) # Output: 4

# Retrieving the value for a non-existing key with a default value


mango_count = my_dict.get('mango', 0)

print("Number of mangoes:", mango_count) # Output: 0 (since 'mango' key


is not present, the default value 0 is returned)
These are some of the essential functions and methods for working with
dictionaries in Python. Dictionaries are powerful data structures that
allow you to efficiently store, retrieve, and update data using unique
keys.
_________________________________________________________________________
________________________________________________
Q.2) Discuss inheritance in Python programming language. Write a Python
program to demonstrate
the use of super() function.
Inheritance is an essential object-oriented programming concept that
allows a class to inherit the properties and behaviors of another class.
The class that inherits from another class is called the "subclass" or
"derived class," and the class being inherited from is called the "base
class" or "parent class." Inheritance promotes code reusability and
enables creating hierarchical relationships between classes.

In Python, you can create a subclass by specifying the base class name in
parentheses after the subclass name when defining the class. The subclass
can then access the attributes and methods of the base class using the
super() function or directly through the instance of the base class.

Let's demonstrate inheritance with an example:

python
Copy code
# Base class
class Animal:
def __init__(self, name):
self.name = name

def make_sound(self):
pass

# Subclass Dog inheriting from Animal


class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the __init__() method of the base
class
self.breed = breed

def make_sound(self):
return "Woof!"

# Subclass Cat inheriting from Animal


class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # Call the __init__() method of the base
class
self.color = color

def make_sound(self):
return "Meow!"

# Creating instances of the subclasses


dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Gray")

# Accessing attributes and methods of the subclasses and the base class
print(f"{dog.name} is a {dog.breed} and says {dog.make_sound()}")
# Output: Buddy is a Golden Retriever and says Woof!

print(f"{cat.name} is {cat.color} and says {cat.make_sound()}")


# Output: Whiskers is Gray and says Meow!
_________________________________________________________________________
____________________________________________
Q.3) Write Python code to find all indices of a substring in the given
string
To find all indices of a substring in a given string, you can use a
simple loop and string manipulation in Python. Here's a function that
does just that:

python
Copy code
def find_all_indices(string, substring):
indices = []
start = 0
while True:
index = string.find(substring, start)
if index == -1:
break
indices.append(index)
start = index + 1
return indices
You can use this function by passing the main string and the substring
you want to find:

python
Copy code
main_string = "ababababab"
substring = "ab"
result = find_all_indices(main_string, substring)
print(result)
This will output: [0, 2, 4, 6, 8], which are the indices of all
occurrences of the substring "ab" in the given main string "ababababab".
_________________________________________________________________________
__________________________________________________________
Q.4) Write python code to demonstrate/perform basic CRUD operations with
MongoDB and python

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/") # Update the
connection string accordingly
database_name = "mydatabase" # Replace 'mydatabase' with the name of
your database
collection_name = "mycollection" # Replace 'mycollection' with the name
of

your collection

# Create (Insert) operation


def create_document(data):
db = client[database_name]
collection = db[collection_name]
insert_result = collection.insert_one(data)
return insert_result.inserted_id

# Read (Retrieve) operation


def read_document(query):
db = client[database_name]
collection = db[collection_name]
return collection.find(query)

# Update operation
def update_document(query, new_data):
db = client[database_name]
collection = db[collection_name]
update_result = collection.update_many(query, {"$set": new_data})
return update_result.modified_count

# Delete operation
def delete_document(query):
db = client[database_name]
collection = db[collection_name]
delete_result = collection.delete_many(query)
return delete_result.deleted_count

# Example usage
if __name__ == "__main__":
# Create (Insert) example
data_to_insert = {"name": "John", "age": 30, "email":
"john@example.com"}
inserted_id = create_document(data_to_insert)
print("Inserted document ID:", inserted_id)

# Read (Retrieve) example


query = {"name": "John"}
result = read_document(query)
for document in result:
print("Retrieved document:", document)

# Update example
update_query = {"name": "John"}
new_data = {"age": 31}
updated_count = update_document(update_query, new_data)
print("Updated documents count:", updated_count)

# Read (Retrieve) after update


result = read_document(query)
for document in result:
print("Retrieved document after update:", document)

# Delete example
delete_query = {"name": "John"}
deleted_count = delete_document(delete_query)
print("Deleted documents count:", deleted_count)

_________________________________________________________________________
__________________________________
Q.5) a)What isfile? Explain different modesin which file can be open.
b)Write Python code to create a text file and perform read and write
operations on it

ChatGPT
a) isfile function:
In Python, isfile is a method in the os.path module that checks whether a
given path is a regular file or not. It returns True if the path points
to a regular file, and False otherwise. A regular file is a file that
contains data and is not a directory or a special file (e.g., device
file).

Different modes in which a file can be opened:


When working with files in Python, you can open a file in different
modes, depending on the type of operations you want to perform. The
common modes are:

Read Mode ('r'): Opens the file for reading. If the file does not exist,
it will raise a FileNotFoundError. This is the default mode if no mode is
specified.

Write Mode ('w'): Opens the file for writing. If the file already exists,
it truncates its content. If the file does not exist, it creates a new
file.

Append Mode ('a'): Opens the file for writing but does not truncate the
existing content. Instead, it appends new data at the end of the file. If
the file does not exist, it creates a new file.

Read and Write Mode ('r+'): Opens the file for both reading and writing.
The file pointer is at the beginning of the file.

Write and Read Mode ('w+'): Similar to 'r+', but it truncates the file if
it already exists.

Append and Read Mode ('a+'): Opens the file for reading and writing, but
the file pointer is at the end of the file. It does not truncate the
file, and new data will be added at the end.

b) Python code to create a text file and perform read and write
operations:

python
Copy code
def create_and_write_to_file(file_path):
# Create a new text file and write data to it
with open(file_path, 'w') as file:
file.write("Hello, this is a text file.\n")
file.write("We are writing data to it.\n")
file.write("You can read this data later.\n")

def read_from_file(file_path):
# Read data from the file
with open(file_path, 'r') as file:
content = file.read()
print("File content:")
print(content)

if __name__ == "__main__":
file_path = "example.txt"

# Create and write to the file


create_and_write_to_file(file_path)

# Read from the file and display the content


read_from_file(file_path)
This code will create a file named "example.txt" in the same directory as
the Python script and write some data to it. Then, it will read the data
from the file and print its content. The output will be:

kotlin
Copy code
File content:
Hello, this is a text file.
We are writing data to it.
You can read this data later.

_________________________________________________________________________
________________________________________________________

Q.6) What is lists? Explain insert, append, extend, remove functions


related to list along with example

In Python, a list is a versatile data structure used to store a


collection of items. Lists are ordered and mutable, meaning you can
change, add, or remove elements after creating the list. Lists are
defined using square brackets [], and elements inside the list are
separated by commas.

Here are some commonly used list methods:

insert(index, element): This method is used to insert an element at a


specific index in the list. The elements after the specified index will
be shifted to accommodate the new element.

# Example of insert()
fruits = ['apple', 'banana', 'orange']
fruits.insert(1, 'grapes')
print(fruits)
# Output: ['apple', 'grapes', 'banana', 'orange']
append(element): This method is used to add an element to the end of the
list.
python
Copy code
# Example of append()
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
# Output: [1, 2, 3, 4]
extend(iterable): This method is used to extend the list by appending
elements from an iterable (e.g., another list or a tuple) to the end of
the current list.
python
Copy code
# Example of extend()
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
# Output: [1, 2, 3, 4, 5, 6]
remove(element): This method is used to remove the first occurrence of
the specified element from the list. If the element is not found, it will
raise a ValueError.
python
Copy code
# Example of remove()
fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
print(fruits)
# Output: ['apple', 'orange']
_________________________________________________________________________
_________________________________________________________________________
___________

Q.7)Write python code to convert the last character of each word in the
string touppercase

ChatGPT
You can achieve this by splitting the string into words, converting the
last character of each word to uppercase, and then joining the words back
into a string. Here's a Python code to do that:

python
Copy code
def convert_last_char_to_uppercase(input_string):
words = input_string.split()
converted_words = []

for word in words:


if len(word) > 1:
converted_word = word[:-1] + word[-1].upper()
else:
converted_word = word.upper()
converted_words.append(converted_word)

return ' '.join(converted_words)

# Example usage
input_string = "hello world this is a sample string"
result = convert_last_char_to_uppercase(input_string)
print(result)
Output:

vbnet
Copy code
hellO worlD thiS iS a samplE strinG

_________________________________________________________________________
________________________________________________________________

.8) How will you add an index, row or column to a pandas DataFrame?
Explain with example.

In Pandas, you can add an index, row, or column to a DataFrame using


different methods. Let's go through each scenario with examples:

Adding an Index:
By default, Pandas DataFrame has a numeric index starting from 0.
However, you can set a different column as the index or add a custom
index to the DataFrame.

import pandas as pd

# Example DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)

# Set 'Name' column as the index


df.set_index('Name', inplace=True)

print(df)
Output:

markdown
Copy code
Age City
Name
Alice 25 New York
Bob 30 London
Charlie 35 Paris
Adding a Row:
To add a new row to a DataFrame, you can use the loc attribute and assign
values to it.
python
Copy code
# Add a new row to the DataFrame
new_row = pd.Series({'Age': 40, 'City': 'Tokyo'}, name='Dave')
df = df.append(new_row)

print(df)
Output:

markdown
Copy code
Age City
Name
Alice 25 New York
Bob 30 London
Charlie 35 Paris
Dave 40 Tokyo
Adding a Column:
To add a new column to the DataFrame, you can directly assign values to
it.
python
Copy code
# Add a new column to the DataFrame
df['Country'] = ['USA', 'UK', 'France', 'Japan']

print(df)
Output:

markdown
Copy code
Age City Country
Name
Alice 25 New York USA
Bob 30 London UK
Charlie 35 Paris France
Dave 40 Tokyo Japan

_________________________________________________________________________
________________________________________________________

Q9) a)What isfile?Explain different modesin which the file can be opened.
b)Write python code to create a file; and perform read and write
operationon it

a) isfile function:
In Python, isfile is a method in the os.path module that checks whether a
given path is a regular file or not. It returns True if the path points
to a regular file, and False otherwise. A regular file is a file that
contains data and is not a directory or a special file (e.g., device
file).

Different modes in which a file can be opened:


When working with files in Python, you can open a file in different
modes, depending on the type of operations you want to perform. The
common modes are:

Read Mode ('r'): Opens the file for reading. If the file does not exist,
it will raise a FileNotFoundError. This is the default mode if no mode is
specified.
Write Mode ('w'): Opens the file for writing. If the file already exists,
it truncates its content. If the file does not exist, it creates a new
file.

Append Mode ('a'): Opens the file for writing but does not truncate the
existing content. Instead, it appends new data at the end of the file. If
the file does not exist, it creates a new file.

Read and Write Mode ('r+'): Opens the file for both reading and writing.
The file pointer is at the beginning of the file.

Write and Read Mode ('w+'): Similar to 'r+', but it truncates the file if
it already exists.

Append and Read Mode ('a+'): Opens the file for reading and writing, but
the file pointer is at the end of the file. It does not truncate the
file, and new data will be added at the end.

b) Python code to create a file and perform read and write operations:

def create_and_write_to_file(file_path):
# Create a new file and write data to it
with open(file_path, 'w') as file:
file.write("Hello, this is a text file.\n")
file.write("We are writing data to it.\n")
file.write("You can read this data later.\n")

def read_from_file(file_path):
# Read data from the file
with open(file_path, 'r') as file:
content = file.read()
print("File content:")
print(content)

if __name__ == "__main__":
file_path = "example.txt"

# Create and write to the file


create_and_write_to_file(file_path)

# Read from the file and display the content


read_from_file(file_path)
This code will create a file named "example.txt" in the same directory as
the Python script and write some data to it. Then, it will read the data
from the file and print its content. The output will be:

kotlin

File content:
Hello, this is a text file.
We are writing data to it.
You can read this data later.
_________________________________________________________________________
_________________________________________________________________________
_

Q.10) What is Inheritance? Explain multiple inheritance and multilevel


inheritancewith example.
ChatGPT
Inheritance is a fundamental concept in object-oriented programming (OOP)
where a class (known as the derived class or subclass) can inherit
properties and behaviors from another class (known as the base class or
superclass). The subclass can reuse the code and functionality of the
base class, which promotes code reusability and helps create a
hierarchical relationship between classes.

Multiple Inheritance:
Multiple inheritance occurs when a subclass inherits from more than one
base class. In Python, a class can inherit from multiple base classes,
and it allows the subclass to access the attributes and methods of all
the base classes.

Example of Multiple Inheritance:

# Base class A
class A:
def method_A(self):
print("This is method A from class A")

# Base class B
class B:
def method_B(self):
print("This is method B from class B")

# Subclass C inherits from both classes A and B


class C(A, B):
pass

# Create an object of class C


obj_C = C()

# Access methods from both base classes


obj_C.method_A()
obj_C.method_B()
Output:

This is method A from class A


This is method B from class B
In this example, we have three classes: A, B, and C. Class C inherits
from both classes A and B, forming multiple inheritance. As a result, the
object obj_C can access methods from both base classes A and B.

Multilevel Inheritance:
Multilevel inheritance occurs when a subclass inherits from another
class, which, in turn, is a subclass of some other class. This forms a
chain-like structure of inheritance.

Example of Multilevel Inheritance:

python
Copy code
# Base class A
class A:
def method_A(self):
print("This is method A from class A")

# Subclass B inherits from class A


class B(A):
def method_B(self):
print("This is method B from class B")

# Subclass C inherits from class B


class C(B):
def method_C(self):
print("This is method C from class C")

# Create an object of class C


obj_C = C()

# Access methods from all levels of inheritance


obj_C.method_A()
obj_C.method_B()
obj_C.method_C()
Output:

kotlin
Copy code
This is method A from class A
This is method B from class B
This is method C from class C

_________________________________________________________________________
_________________________________________________________________________
______________

Q.11) What is Numpy array? How to create NumPy array. Explain with
example.
ChatGPT
NumPy (Numerical Python) is a popular Python library that provides
support for large, multi-dimensional arrays and matrices, along with a
collection of mathematical functions to operate on these arrays
efficiently. NumPy arrays are more efficient than Python lists,
especially for numerical computations, as they allow vectorized
operations.
To create a NumPy array, you first need to import the NumPy library.
Then, you can create an array using various methods provided by NumPy,
such as numpy.array(), numpy.zeros(), numpy.ones(), numpy.arange(), etc.

Here are some examples of creating NumPy arrays:

python
Copy code
import numpy as np

# Create a 1-dimensional NumPy array from a Python list


arr1 = np.array([1, 2, 3, 4, 5])
print("1D array:")
print(arr1)

# Output: [1 2 3 4 5]

# Create a 2-dimensional NumPy array from a nested Python list


arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D array:")
print(arr2)

# Output:
# [[1 2 3]
# [4 5 6]]

# Create a 3x3 array of all zeros


zeros_array = np.zeros((3, 3))
print("\nZeros array:")
print(zeros_array)

# Output:
# [[0. 0. 0.]
# [0. 0. 0.]
# [0. 0. 0.]]

# Create a 3x3 array of all ones


ones_array = np.ones((3, 3))
print("\nOnes array:")
print(ones_array)

# Output:
# [[1. 1. 1.]
# [1. 1. 1.]
# [1. 1. 1.]]

# Create a 1-dimensional array with a range of values


range_array = np.arange(1, 10, 2) # Start from 1, end at 9 (exclusive),
step size = 2
print("\nRange array:")
print(range_array)

# Output: [1 3 5 7 9]
_________________________________________________________________________
_________________________________________________________________________
_

Q.12) How to Delete Indices, Rows or Columns From a Pandas Data Frame?
ChatGPT
To delete indices, rows, or columns from a Pandas DataFrame, you can use
various methods and functions based on the specific operation you want to
perform. Here are some common methods to achieve this:

Deleting Indices:
Pandas DataFrames have an index attribute that represents the row labels
(indices). You can use the drop method to remove specific indices from
the DataFrame.

import pandas as pd

# Example DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)

# Set 'Name' column as the index


df.set_index('Name', inplace=True)

# Delete a specific index (row) using the drop method


df.drop('Bob', inplace=True)

print(df)
Output:

markdown

Age City
Name
Alice 25 New York
Charlie 35 Paris
Deleting Rows:
You can use the drop method with the axis parameter set to 0 to delete
rows based on their indices.

# Example DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)

# Delete a specific row using the drop method with axis=0


df.drop(1, inplace=True) # Index 1 corresponds to the second row ('Bob')

print(df)
Output:
markdown
Copy code
Name Age City
0 Alice 25 New York
2 Charlie 35 Paris
Deleting Columns:
You can use the drop method with the axis parameter set to 1 to delete
columns from the DataFrame.

# Example DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)

# Delete the 'Age' column using the drop method with axis=1
df.drop('Age', axis=1, inplace=True)

print(df)
Output:

markdown

Name City
0 Alice New York
1 Bob London
2 Charlie Paris

_________________________________________________________________________
_________________________________________________________________________
______________

Q.13) Define the different ways a dataframe can be created in Pandas with
example.
ChatGPT
Pandas provides several ways to create a DataFrame, which is a 2-
dimensional data structure to store and manipulate tabular data. Here are
different ways to create a DataFrame in Pandas with examples:

From a Dictionary:
You can create a DataFrame from a Python dictionary, where keys represent
column names, and values represent column data.
python
Copy code
import pandas as pd

# Example DataFrame from a dictionary


data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
}

df = pd.DataFrame(data)
print(df)
Output:

markdown
Copy code
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Paris
From a List of Lists:
You can create a DataFrame from a list of lists, where each inner list
represents a row of data.
python
Copy code
import pandas as pd

# Example DataFrame from a list of lists


data = [
['Alice', 25, 'New York'],
['Bob', 30, 'London'],
['Charlie', 35, 'Paris']
]

df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])

print(df)
Output:

markdown
Copy code
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Paris
From a List of Dictionaries:
You can create a DataFrame from a list of dictionaries, where each
dictionary represents a row of data, and keys represent column names.
python
Copy code
import pandas as pd

# Example DataFrame from a list of dictionaries


data = [
{'Name': 'Alice', 'Age': 25, 'City': 'New York'},
{'Name': 'Bob', 'Age': 30, 'City': 'London'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Paris'}
]

df = pd.DataFrame(data)

print(df)
Output:
markdown
Copy code
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Paris
From a CSV or Excel File:
You can also create a DataFrame by reading data from a CSV file or an
Excel file using Pandas read_csv and read_excel functions.
Example using CSV:

python
Copy code
import pandas as pd

# Read data from a CSV file and create a DataFrame


df = pd.read_csv('data.csv')

print(df)
Example using Excel:

python
Copy code
import pandas as pd

# Read data from an Excel file and create a DataFrame


df = pd.read_excel('data.xlsx')

print(df)

_________________________________________________________________________
_____________________________________________________________

Q.14) What is NoSQL database? Compare SQL Vs NoSQL .

ChatGPT
NoSQL (Not Only SQL) database is a type of database management system
that provides a non-relational data model for storing and retrieving
data. Unlike traditional SQL (Structured Query Language) databases, NoSQL
databases do not use a fixed schema and are more flexible in handling
unstructured or semi-structured data. NoSQL databases are designed to
scale horizontally and can handle large amounts of data and high
read/write workloads.

Comparison of SQL and NoSQL databases:

Data Model:
SQL: SQL databases use a structured data model based on tables with fixed
schemas. Each row in the table represents a record, and each column
represents a specific attribute of that record.
NoSQL: NoSQL databases use various data models like key-value, document,
column-family, or graph. The data model can be more flexible and dynamic,
allowing for schemaless storage and handling of complex, nested, or
unstructured data.
Schema:
SQL: SQL databases have a fixed schema, meaning the table structure must
be defined beforehand, and all records must adhere to that structure.
NoSQL: NoSQL databases have a dynamic schema, allowing for the addition
or removal of fields in documents or columns in column-family databases
without affecting other records.
Scaling:
SQL: SQL databases are generally vertically scalable, meaning they are
optimized for running on a single server with increasing hardware
resources (CPU, RAM, etc.).
NoSQL: NoSQL databases are horizontally scalable, meaning they can
distribute data across multiple servers and handle large-scale data and
traffic by adding more nodes to the cluster.
Joins:
SQL: SQL databases support complex queries using JOIN operations to
combine data from multiple tables.
NoSQL: NoSQL databases do not typically support JOIN operations, as data
is denormalized to improve query performance.
Transactions:
SQL: SQL databases support ACID (Atomicity, Consistency, Isolation,
Durability) transactions, ensuring data integrity and reliability.
NoSQL: NoSQL databases may not always support ACID transactions,
depending on the specific database type. Some NoSQL databases offer
eventual consistency, where data may not be immediately consistent across
all nodes.
Use Cases:
SQL: SQL databases are well-suited for applications with structured data
and complex relationships, such as transactional systems, financial
applications, and traditional business applications.
NoSQL: NoSQL databases are suitable for applications with unstructured or
semi-structured data, high-volume web applications, big data analytics,
real-time applications, and scenarios requiring rapid scaling.

_________________________________________________________________________
_________________________________________________________________________
___

a) Lambda Function

ChatGPT
In Python, a lambda function (also known as an anonymous function) is a
small and simple function that can have any number of arguments but only
one expression. Lambda functions are defined using the lambda keyword,
followed by the list of arguments, a colon :, and the expression to be
evaluated. They are particularly useful when you need a quick, throwaway
function without the need to give it a formal name.

The general syntax of a lambda function is:

python
Copy code
lambda arguments: expression
Lambda functions are typically used when you need a short function for a
specific task, such as in filtering, mapping, or sorting operations.

Example 1: Simple addition using a lambda function

python
Copy code
add = lambda x, y: x + y
result = add(5, 10)
print(result) # Output: 15

_________________________________________________________________________
_________________________________________________________________________
__

a)Explainthe concept of user define dexceptions with suitableexample.


User-defined exceptions are ones that the developer writes in their code
to address particular errors. These exceptions are defined by creating a
new class that inherits from the Exception class or one of its
subclasses.

example:
try:
a=int(input("enter a number"))
b=int(input("enter a number"))
c=a/b
print(f'divisio of {a} and {b} is {c}')
except:
print("we can not devide by zero")

b)How will u create a seriesfrom dictionary in Pandas.

In Pandas, you can create a Series from a dictionary using the


pd.Series() constructor. The keys of the dictionary will become the index
labels of the Series, and the values of the dictionary will become the
data elements of the Series.

syntax:
import pandas as pd

my_dict = {'key1': value1, 'key2': value2, 'key3': value3, ...}


my_series = pd.Series(my_dict)

example:
import pandas as pd

# Sample dictionary
population_dict = {
'USA': 331002651,
'China': 1439323776,
'India': 1380004385,
'Brazil': 212559417,
'Pakistan': 220892340
}
# Creating a Series from the dictionary
population_series = pd.Series(population_dict)

# Displaying the Series


print(population_series)

c)Discuss the following methods supported by compiled regular


expression objects.
a) search() b) match() c) findall()

In Python, regular expressions are implemented using the re module. When


you compile a regular expression pattern using re.compile(), it creates a
compiled regular expression object that can be used to perform various
pattern matching operations. The compiled regular expression object
provides several useful methods for working with patterns:

a) search(): This method is used to search for the first occurrence of a


pattern in a given string. It returns a match object if the pattern is
found, otherwise, it returns None.

Example:
import re

pattern = re.compile(r'\d+')
text = 'The price of the product is $100.'

result = pattern.search(text)
if result:
print(f"Found: {result.group()}") # Output: Found: 100
else:
print("Pattern not found.")
b) match(): This method is similar to search(), but it only searches for
the pattern at the beginning of the string. It returns a match object if
the pattern is found at the start of the string, otherwise, it returns
None.
Example:
import re

pattern = re.compile(r'\d+')
text = '100 dollars is the cost of the product.'

result = pattern.match(text)
if result:
print(f"Found: {result.group()}") # Output: Found: 100
else:
print("Pattern not found.")
c) findall(): This method is used to find all occurrences of a pattern in
a given string and returns the matches as a list.

_________________________________________________________________________
_______________________________________________________
Write short note on following

a) The dir() Function:

In Python, the dir() function is a powerful built-in function used to get


a list of valid attributes (methods, functions, classes, variables, etc.)
of any object. When you pass an object as an argument to the dir()
function, it returns a sorted list of names in the object's namespace. If
no object is provided, dir() returns a list of names in the current
module's namespace.

Example:
# Example of using dir() function with a list object
my_list = [1, 2, 3]
print(dir(my_list))
b) Features of Python:

Python is a high-level, interpreted, and dynamically-typed programming


language known for its simplicity, readability, and versatility. Some key
features of Python include:

Simple and Readable Syntax: Python uses a minimalistic and easily


understandable syntax, making it beginner-friendly and easy to read and
write.

Interpreted Language: Python is an interpreted language, which means that


the code is executed line-by-line at runtime, without the need for
compilation.

Dynamically Typed: Python is dynamically typed, allowing variables to be


assigned different data types during runtime.

Object-Oriented: Python supports object-oriented programming (OOP)


principles, enabling the creation of classes and objects for better code
organization and reusability.

Large Standard Library: Python comes with a comprehensive standard


library, providing a wide range of built-in modules and functions for
various tasks, such as file I/O, networking, web development, and more.

Extensive Third-party Libraries: Python has a vibrant ecosystem of third-


party libraries (e.g., NumPy, Pandas, TensorFlow) that expand its
capabilities for various domains like data analysis, machine learning,
web development, etc.

Platform Independence: Python code can run on different platforms without


modification due to its platform independence.

c) Scope of Variables:

The scope of a variable in Python refers to the part of the program where
the variable is accessible or visible. In Python, variables can have
different scopes:
Global Scope: Variables declared outside any function or class have a
global scope, making them accessible throughout the entire program.

Local Scope: Variables declared inside a function have a local scope,


making them accessible only within that function.

Enclosing Scope: In nested functions, variables declared in the enclosing


function have an enclosing scope and can be accessed by the nested
functions.

Built-in Scope: Python has a built-in scope that includes all the names
of Python's built-in functions and modules.

The scope of a variable is crucial for understanding how it behaves in


different parts of a program and avoids naming conflicts between
variables in different scopes.

d) Tuples in Python:

In Python, a tuple is an ordered, immutable, and heterogeneous collection


of elements. Tuples are similar to lists but have a few key differences:

Immutable: Once a tuple is created, its elements cannot be changed or


modified. You cannot add, remove, or replace elements in a tuple.

Syntax: Tuples are defined using parentheses () or the tuple()


constructor, and elements are separated by commas.

Heterogeneous: Tuples can hold elements of different data types, making


them versatile for grouping related data together.

Accessing Elements: You can access elements in a tuple using indexing,


just like lists.

Example:
# Creating a tuple
my_tuple = (1, 'hello', 3.14)

# Accessing elements
print(my_tuple[0]) # Output: 1

# Attempting to modify a tuple will result in an error


# my_tuple[0] = 2 # Raises TypeError: 'tuple' object does not support
item assignment

_________________________________________________________________________
_________________________________________________________________________
____________

A lambda function in Python is a small, anonymous, and one-liner


function. It is also known as an inline function or a function without a
name. Lambda functions are typically used for short and simple operations
where you don't want to define a full-fledged function using the `def`
keyword.
The general syntax of a lambda function is:

lambda arguments: expression

The lambda function takes one or more arguments, separated by commas,


followed by a colon `:` and an expression that is evaluated and returned
as the result of the function. Lambda functions can only contain a single
expression, and they can't have complex statements like loops or
conditional statements.

Lambda functions are often used as arguments in functions like `map()`,


`filter()`, and `sorted()`, where a quick function is needed for a short
operation.

Example:

Let's create a lambda function to calculate the square of a number:

# Using a lambda function to calculate the square of a number


square = lambda x: x ** 2

# Example usage:
num = 5
print(f"The square of {num} is: {square(num)}") # Output: The square of
5 is: 25

In this example, we define a lambda function called `square` that takes


one argument `x` and returns its square using the expression `x ** 2`. We
then use the lambda function to calculate the square of the number 5 and
print the result.

Lambda functions are useful when you need a simple function for a
specific task, especially when using higher-order functions that require
a function as an argument. However, for more complex tasks or functions
that need multiple statements, it's better to use a regular named
function defined with `def`.

Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows one class (subclass or derived class) to inherit properties
and behaviors (attributes and methods) from another class (superclass or
base class). In Python, you can create inheritance relationships using
the class definition.

There are four types of inheritance in Python:

1. Single Inheritance: A class inherits from a single base class.

2. Multiple Inheritance: A class inherits from multiple base classes.


3. Multilevel Inheritance: A class inherits from a base class, which in
turn, inherits from another base class.

4. Hierarchical Inheritance: Multiple classes inherit from a single base


class.

Let's demonstrate each type of inheritance with examples:

1. Single Inheritance:

class Animal:
def sound(self):
print("Some generic sound")

class Dog(Animal):
def sound(self):
print("Woof! Woof!")

# Example usage:
dog = Dog()
dog.sound() # Output: Woof! Woof!

2. Multiple Inheritance:

class Flyable:
def fly(self):
print("Flying...")

class Bird(Animal, Flyable):


pass

# Example usage:
bird = Bird()
bird.sound() # Output: Some generic sound
bird.fly() # Output: Flying...

3. Multilevel Inheritance:

class Mammal(Animal):
def give_birth(self):
print("Giving birth to live young")

class Human(Mammal):
pass

# Example usage:
human = Human()
human.sound() # Output: Some generic sound
human.give_birth() # Output: Giving birth to live young
```

4. Hierarchical Inheritance:

class Cat(Animal):
def sound(self):
print("Meow! Meow!")

class Cow(Animal):
def sound(self):
print("Moo! Moo!")

# Example usage:
cat = Cat()
cow = Cow()
cat.sound() # Output: Meow! Meow!
cow.sound() # Output: Moo! Moo!

In these examples, we define different classes representing animals and


their specific behaviors. We use various inheritance types to create
relationships between classes. The subclasses inherit attributes and
methods from their respective base classes.

Inheritance promotes code reusability, extensibility, and helps in


organizing classes into a hierarchical structure based on common
features.

Polymorphism is another fundamental concept in object-oriented


programming (OOP). It allows objects of different classes to be treated
as objects of a common base class, enabling different classes to have a
single unified interface. In Python, polymorphism is achieved through
method overriding and method overloading.
Method Overloading:
Method overloading allows a class to define multiple methods with the
same name but different parameter lists. Python doesn't support
traditional method overloading like some other languages (e.g., Java).
However, you can simulate method overloading by using default arguments
or variable-length argument lists.
class Calculator:
def add(self, a, b):
return a + b

def add(self, a, b, c):


return a + b + c
# Example usage:
calc = Calculator()
print(calc.add(2, 3)) # Output: TypeError: add() missing 1 required
positional argument: 'c'
print(calc.add(2, 3, 4)) # Output: 9

Iterator and Generator are two essential concepts in Python for working
with iterable data. They allow you to work with large datasets
efficiently, avoid memory overhead, and enable lazy evaluation.

1. Iterator:
An iterator is an object that allows you to loop over a sequence (e.g.,
list, tuple, string) one item at a time without loading the entire
sequence into memory. It follows the Iterator Protocol, which requires
the implementation of two methods: `__iter__()` and `__next__()`. The
`__iter__()` method returns the iterator object itself, and the
`__next__()` method returns the next item in the sequence. When there are
no more items to return, it raises the `StopIteration` exception to
signal the end of the iteration.

Example of Iterator:

my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)

print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3

In this example, `my_iterator` is an iterator for the `my_list`. We use


the `next()` function to fetch the next element from the iterator. When
there are no more elements, it raises `StopIteration`.

2. Generator:
A generator is a special type of iterator that generates data on-the-fly
using the `yield` keyword instead of returning it using the `return`
keyword. When a generator function is called, it doesn't execute the
entire function at once but generates values lazily as requested.
Generators are memory-efficient since they don't store all values in
memory but only the current state.

Example of Generator:

def square_numbers(n):
for i in range(n):
yield i ** 2

# Example usage:
my_generator = square_numbers(5)
for num in my_generator:
print(num) # Output: 0, 1, 4, 9, 16

In this example, `square_numbers()` is a generator function that yields


the square of numbers from 0 to `n-1`. When we create the generator
`my_generator`, it doesn't compute all the squares upfront. Instead, it
computes them one by one as we iterate through the generator using a
`for` loop.

Generators are very useful when working with large datasets or infinite
sequences, as they allow you to iterate over elements without storing
them all in memory at once.

Both iterators and generators help improve performance and memory usage,
especially when working with large datasets or when generating values on-
the-fly.

Multithreading in Python is a programming concept that allows a program


to perform multiple tasks concurrently within the same process. Python
provides a built-in module called `threading` to work with
multithreading. Threads are the smallest units of execution within a
process, and multithreading enables a program to execute multiple threads
simultaneously, making efficient use of available system resources and
improving overall performance, especially for I/O-bound tasks.

The `threading` module provides the `Thread` class to create and manage
threads. To implement multithreading in Python, you need to define a
function or use a callable object that will be executed as a separate
thread.

Here's a simple example of multithreading in Python:

import threading
import time

def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
time.sleep(1) # Introducing a delay to simulate some work

def print_letters():
for letter in 'ABCDE':
print(f"Letter: {letter}")
time.sleep(1) # Introducing a delay to simulate some work

# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting threads
thread1.start()
thread2.start()

# Waiting for threads to finish


thread1.join()
thread2.join()

print("Multithreading example is done.")

Output:

Number: 1
Letter: A
Number: 2
Letter: B
Number: 3
Letter: C
Number: 4
Letter: D
Number: 5
Letter: E
Multithreading example is done.
```

In this example, we define two functions, `print_numbers()` and


`print_letters()`, which will be executed by separate threads. We create
two `Thread` objects, `thread1` and `thread2`, with each thread targeting
one of the functions. Then, we start the threads using the `start()`
method, which initiates their execution concurrently.

The `time.sleep(1)` is used to introduce a one-second delay in each


thread to simulate some work being done. In a real-world application,
these threads can perform more complex tasks, such as downloading files,
processing data, or handling user input, while other threads run
simultaneously.

Finally, we use the `join()` method to wait for both threads to finish
before printing the message indicating the completion of the
multithreading example.

Keep in mind that while multithreading can be useful for I/O-bound tasks,
it might not provide significant performance improvements for CPU-bound
tasks due to Python's Global Interpreter Lock (GIL), which restricts
multiple threads from executing Python bytecode simultaneously on multi-
core processors. For CPU-bound tasks, consider using the
`multiprocessing` module to leverage multiple CPU cores.

You might also like