Python Imp
Python Imp
i) len()
) cmp( )
iii) update( )
iv) get()
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}
python
# Dictionary 1
dict1 = {'a': 1, 'b': 2, 'c': 3}
# Dictionary 2
dict2 = {'a': 1, 'b': 2, 'c': 3}
Example:
python
# Original dictionary
my_dict = {'apple': 3, 'banana': 6}
Example:
python
Copy code
# Dictionary
my_dict = {'apple': 3, 'banana': 6, 'orange': 4, 'grape': 12}
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.
python
Copy code
# Base class
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
def make_sound(self):
return "Woof!"
def make_sound(self):
return "Meow!"
# 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!
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
# 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":
"[email protected]"}
inserted_id = create_document(data_to_insert)
print("Inserted document ID:", inserted_id)
# Update example
update_query = {"name": "John"}
new_data = {"age": 31}
updated_count = update_document(update_query, new_data)
print("Updated documents count:", updated_count)
# 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).
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"
kotlin
Copy code
File content:
Hello, this is a text file.
We are writing data to it.
You can read this data later.
_________________________________________________________________________
________________________________________________________
# 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 = []
# 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.
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)
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).
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"
kotlin
File content:
Hello, this is a text file.
We are writing data to it.
You can read this data later.
_________________________________________________________________________
_________________________________________________________________________
_
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.
# 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")
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.
python
Copy code
# Base class A
class A:
def method_A(self):
print("This is method A from class A")
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.
python
Copy code
import numpy as np
# Output: [1 2 3 4 5]
# Output:
# [[1 2 3]
# [4 5 6]]
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]
# [0. 0. 0.]]
# Output:
# [[1. 1. 1.]
# [1. 1. 1.]
# [1. 1. 1.]]
# 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)
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)
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
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
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
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
print(df)
Example using Excel:
python
Copy code
import pandas as pd
print(df)
_________________________________________________________________________
_____________________________________________________________
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.
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.
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.
python
Copy code
add = lambda x, y: x + y
result = add(5, 10)
print(result) # Output: 15
_________________________________________________________________________
_________________________________________________________________________
__
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")
syntax:
import pandas as pd
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)
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
Example:
# Example of using dir() function with a list object
my_list = [1, 2, 3]
print(dir(my_list))
b) Features of Python:
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.
Built-in Scope: Python has a built-in scope that includes all the names
of Python's built-in functions and modules.
d) Tuples in Python:
Example:
# Creating a tuple
my_tuple = (1, 'hello', 3.14)
# Accessing elements
print(my_tuple[0]) # Output: 1
_________________________________________________________________________
_________________________________________________________________________
____________
Example:
# Example usage:
num = 5
print(f"The square of {num} is: {square(num)}") # Output: The square of
5 is: 25
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.
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...")
# 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!
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
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
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.
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.
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()
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.
```
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.