PYthon Last Moment

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

PYTHON PROGRAMMING

1.Write a program to check the number entered by user is even or odd. Program should accept
integer only.

# Function to check if a number is even or odd


def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"

# Main program
try:
# Get user input
user_input = int(input("Enter an integer: "))

# Check if the input is even or odd and print the result


result = check_even_odd(user_input)
print(f"The number {user_input} is {result}.")

except ValueError:
print("Invalid input! Please enter an integer.")

2.Illustrate types of arguments used in python function with example.

In Python, functions can accept different types of arguments. Here are the main types of
arguments, along with examples:

Positional Arguments:
These are the most common type of arguments, where the values are passed based on the order
of parameters in the function definition.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8

Keyword Arguments:
In this type, you can explicitly mention the parameter names and their corresponding values
while calling the function.
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Hello", name="Alice")

Default Arguments:
You can provide default values for parameters, which are used when the argument is not
explicitly passed during the function call.
def power(base, exponent=2):
return base ** exponent

result1 = power(3) # Uses default exponent value (2)


result2 = power(3, 4) # Uses provided exponent value (4)

print(result1) # Output: 9
print(result2) # Output: 81

Variable-Length Arguments:
Functions can accept a variable number of arguments using *args and **kwargs.
*args is used for variable positional arguments
def sum_values(*args):
return sum(args)

result = sum_values(1, 2, 3, 4, 5)
print(result) # Output: 15

Passing a List or Dictionary as Arguments:


You can also pass a list or dictionary to a function and unpack its values.
def print_values(*args):
for value in args:
print(value)

values = [1, 2, 3, 4]
print_values(*values) # Unpacking the list

def print_info(name, age):


print(f"Name: {name}, Age: {age}")
user_info = {"name": "Bob", "age": 25}
print_info(**user_info) # Unpacking the dictionary

3.Discuss polymorphism concept in python create suitable python classes.


Polymorphism in Python refers to the ability of a single function, method, or operator to work
with different types of data or objects. There are two main types of polymorphism in Python:
compile-time (or static) polymorphism and run-time (or dynamic) polymorphism.

Compile-Time Polymorphism (Method Overloading):


Method overloading allows a class to have multiple methods having the same name, if their
parameter lists are different. Python doesn't support method overloading by default, but you
can achieve a similar effect using default values and variable-length arguments.
class MathOperations:
def add(self, a, b=0, c=0):
return a + b + c

math_obj = MathOperations()
result1 = math_obj.add(1)
result2 = math_obj.add(1, 2)
result3 = math_obj.add(1, 2, 3)

print(result1) # Output: 1
print(result2) # Output: 3
print(result3) # Output: 6

Run-Time Polymorphism (Method Overriding):


Method overriding allows a subclass to provide a specific implementation of a method that is
already defined in its superclass. This is achieved by defining a method in the subclass with the
same name and signature as the method in the superclass.
class Animal:
def make_sound(self):
pass

class Dog(Animal):
def make_sound(self):
return "Woof!"

class Cat(Animal):
def make_sound(self):
return "Meow!"

def animal_sound(animal_obj):
return animal_obj.make_sound()

dog = Dog()
cat = Cat()

print(animal_sound(dog)) # Output: Woof!


print(animal_sound(cat)) # Output: Meow!

Polymorphism simplifies code and enhances flexibility by allowing the use of a common interface
for different types of objects. This concept is fundamental to object-oriented programming and
plays a crucial role in designing reusable and extensible code.

4.Write a python program for the following.


• Create list of fruits
• Add new fruits in list
• Sort the list
• Delete last fruit name from list.
# Create a list of fruits
fruits = ['Apple', 'Banana', 'Orange', 'Grapes']

# Print the original list


print("Original List of Fruits:", fruits)

# Add new fruits to the list


fruits.extend(['Mango', 'Pineapple'])

# Print the list after adding new fruits


print("List of Fruits after Adding New Fruits:", fruits)

# Sort the list


fruits.sort()

# Print the list after sorting


print("Sorted List of Fruits:", fruits)
# Delete the last fruit name from the list
if fruits:
last_fruit = fruits.pop()

# Print the list after deleting the last fruit


print(f"List of Fruits after Deleting {last_fruit}:", fruits)
else:
print("The list is empty.")

5.Write a python function to check the given number is even or odd. Handle suitable
exception.
def check_even_odd(number):
try:
# Attempt to convert the input to an integer
num = int(number)

# Check if the number is even or odd


if num % 2 == 0:
return f"{num} is even."
else:
return f"{num} is odd."

except ValueError:
# Handle the exception if the input is not a valid number
return "Invalid input! Please enter a valid number."

# Get user input


user_input = input("Enter a number: ")

# Call the function and print the result


result = check_even_odd(user_input)
print(result)

6.Explain constructor concept in python with example


In Python, a constructor is a special method within a class that is automatically called when an
object of that class is created. It is used to initialize the attributes of the object. The constructor
method in Python is named _init_()
Constructor Method (_init_):
The _init_ method is a special method in Python classes that is automatically called when an
object is created from the class.
Its purpose is to initialize the attributes (or properties) of the object with values provided as
arguments when the object is instantiated.

Self-Parameter:
The self-parameter is a reference to the instance of the class. It allows you to access and modify
the attributes of the instance within the class methods.

Object Initialization:
When an object is created, the _init_ method is automatically called with the provided
arguments. This sets the initial state of the object.

class Car:
# Constructor method
def _init_(self, make, model, year):
# Initialize attributes
self.make = make
self.model = model
self.year = year
self.is_running = False

# Method to start the car


def start_engine(self):
self.is_running = True
print(f"{self.year} {self.make} {self.model}'s engine is running.")

# Method to stop the car


def stop_engine(self):
self.is_running = False
print(f"{self.year} {self.make} {self.model}'s engine is stopped.")

# Creating an instance of the Car class


my_car = Car(make="Toyota", model="Camry", year=2022)

# Accessing attributes
print(f"My car is a {my_car.year} {my_car.make} {my_car.model}.")
# Using methods
my_car.start_engine()
my_car.stop_engine()

7.Write a python program to create an employee.txt file and store employee name and
address.
def write_to_file(file_path, data):
try:
with open(file_path, 'w') as file:
for employee in data:
file.write(f"{employee['name']}, {employee['address']}\n")
print(f"Data written to {file_path} successfully.")
except Exception as e:
print(f"Error: {e}")

# Sample employee data


employee_data = [
{'name': 'John Doe', 'address': '123 Main Street, Cityville'},
{'name': 'Jane Smith', 'address': '456 Oak Avenue, Townsville'},
{'name': 'Bob Johnson', 'address': '789 Pine Road, Villagetown'}
]

# File path
file_path = 'employee.txt'

# Write data to the file


write_to_file(file_path, employee_data)

8. Write a python program to create "employee" collection with fields" (ID name, address,
phone email and dept) in mongoDB. Prform the following operations.
• Display all employees in "Accounts" department
• Delete employee with ID – 210345
• Update phone with new phone for empioyee ID -123
import pymongo

# Connect to MongoDB (assuming it's running locally on the default port)


client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["mydatabase"] # Change "mydatabase" to your database name
collection = database["employee"]

# Insert sample data into the "employee" collection


sample_data = [
{"ID": 123, "name": "John Doe", "address": "123 Main St", "phone": "555-1234", "email":
"[email protected]", "dept": "Accounts"},
{"ID": 210345, "name": "Jane Smith", "address": "456 Oak Ave", "phone": "555-5678", "email":
"[email protected]", "dept": "HR"},
# Add more employee data as needed
]

# Insert data into the collection


collection.insert_many(sample_data)

# Display all employees in the "Accounts" department


print("Employees in the 'Accounts' department:")
accounts_employees = collection.find({"dept": "Accounts"})
for employee in accounts_employees:
print(employee)

# Delete employee with ID - 210345


collection.delete_one({"ID": 210345})
print("Employee with ID 210345 deleted.")

# Update phone for employee with ID - 123


new_phone_number = "555-9999"
collection.update_one({"ID": 123}, {"$set": {"phone": new_phone_number}})
print(f"Phone number for employee with ID 123 updated to {new_phone_number}.")

# Close the MongoDB connection


client.close()

9.What is tuple? What is the difference between list and tuple?


In Python, a tuple is an immutable, ordered collection of elements. This means that once a tuple
is created, you cannot change its elements, add new elements, or remove existing elements.
Tuples are defined using parentheses ().
Tuple in Python:
Definition:
Created using parentheses ()
Immutable:
Once a tuple is created, you cannot modify its elements. This immutability provides data
integrity and makes tuples suitable for situations where the data should remain constant.
Ordered:
Elements in a tuple maintain their order, and you can access them using indices.
Supports Heterogeneous Elements:
A tuple can contain elements of different data types.
Methods:
Tuples have fewer built-in methods compared to lists because of their immutability.

List in Python:
Definition:
Created using square brackets [].
Mutable:
Lists are mutable, meaning you can modify their elements by adding, removing, or changing
values.
Ordered:
Elements in a list also maintain their order, and you can access them using indices.
Supports Heterogeneous Elements:
Like tuples, lists can contain elements of different data types.
Methods:
Lists have more built-in methods compared to tuples because of their mutability.

10.What is set? Explain with example.


In Python, a set is an unordered collection of unique elements. It is defined by enclosing a
comma-separated list of elements within curly braces {} or by using the set() constructor. Sets
are particularly useful when you want to store multiple items in a single variable, and you want
to ensure that each item is unique.

Uniqueness:
Sets do not allow duplicate elements. If you try to add an element that already exists in the set,
it will not be added again.

Adding and Removing Elements:


You can add elements to a set using the add method, and you can remove elements using the
remove or discard method.
Set Operations:
Sets support various operations such as union, intersection, and difference.

Unordered:
The elements in a set do not have a specific order. Therefore, you cannot access elements by
index.

Mutable:
While the elements of a set are mutable (you can add or remove elements), the set itself is
mutable.Sets are commonly used when you need to perform operations that involve checking
for membership, finding intersections, or obtaining unique elements from a collection of data.

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union
union_set = set1.union(set2) # or set1 | set2

# Intersection
intersection_set = set1.intersection(set2) # or set1 & set2

# Difference
difference_set = set1.difference(set2) # or set1 - set2

11.Write a program to retrieve and display employee details from ”Employee” collection
stored in mangoDB database.
import pymongo

# Connect to MongoDB (assuming it's running locally on the default port)


client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["your_database_name"] # Replace with your actual database name
collection = database["Employee"] # Replace with your actual collection name

# Retrieve and display employee details


def display_employee_details():
employees = collection.find()
for employee in employees:
print(f"Employee ID: {employee['ID']}")
print(f"Name: {employee['name']}")
print(f"Address: {employee['address']}")
print(f"Phone: {employee['phone']}")
print(f"Email: {employee['email']}")
print(f"Department: {employee['dept']}")
print("--------------------")

# Call the function to display employee details


display_employee_details()

# Close the MongoDB connection


client.close()

12.Write a python program to update the employee details stored in “Employee” collection
stored in MangoDB Database.
import pymongo

# Connect to MongoDB (assuming it's running locally on the default port)


client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["your_database_name"] # Replace with your actual database name
collection = database["Employee"] # Replace with your actual collection name

# Function to update employee details


def update_employee_details(employee_id, new_phone):
try:
# Update the phone number for the employee with the given ID
collection.update_one({"ID": employee_id}, {"$set": {"phone": new_phone}})
print(f"Employee with ID {employee_id} details updated successfully.")
except Exception as e:
print(f"Error: {e}")

# Call the function to update employee details


employee_id_to_update = 123 # Replace with the actual employee ID to update
new_phone_number = "555-1234" # Replace with the new phone number
update_employee_details(employee_id_to_update, new_phone_number)

# Display updated employee details


updated_employee = collection.find_one({"ID": employee_id_to_update})
if updated_employee:
print("Updated Employee Details:")
print(f"Employee ID: {updated_employee['ID']}")
print(f"Name: {updated_employee['name']}")
print(f"Address: {updated_employee['address']}")
print(f"Phone: {updated_employee['phone']}")
print(f"Email: {updated_employee['email']}")
print(f"Department: {updated_employee['dept']}")
else:
print(f"No employee found with ID {employee_id_to_update}.")

# Close the MongoDB connection


client.close()

13.Write a python program to read “Employee.txt” file and display alternate employee record.
# Open the file for reading
file_path = "Employee.txt"

try:
with open(file_path, 'r') as file:
# Read all lines from the file
lines = file.readlines()

# Display alternate employee records


for i in range(0, len(lines), 2):
print(lines[i].strip()) # Use strip to remove leading/trailing whitespaces

except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"Error: {e}")

14.Write a program for extracting email address from a given webpage.


import requests
import re

def extract_emails_from_webpage(url):
try:
# Send a GET request to the webpage
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses

# Extract email addresses using a regular expression


email_pattern = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
emails = re.findall(email_pattern, response.text)

return emails

except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return []

# Example URL (replace with the actual URL you want to scrape)
webpage_url = "https://example.com"

# Call the function to extract email addresses


extracted_emails = extract_emails_from_webpage(webpage_url)

# Display the extracted email addresses


print("Extracted Email Addresses:")
for email in extracted_emails:
print(email)

15.What is synchronization in threading? Explain with example.


In Python, synchronization in threading involves coordinating the execution of multiple threads
to ensure that they work together harmoniously and avoid race conditions, deadlocks, and other
issues that can arise when multiple threads access shared resources concurrently. The threading
module in Python provides various synchronization primitives to assist in achieving this
coordination.
Here are some key concepts related to synchronization in threading in Python:

Locks (Mutex):
The Lock class in the threading module is a mutual exclusion lock, commonly known as a mutex.
A lock is used to protect critical sections of code, allowing only one thread at a time to acquire
the lock and enter the critical section.
Semaphores:
The Semaphore class provides a way to control access to a resource by multiple threads.
Unlike a lock, a semaphore can allow more than one thread to access the critical section
simultaneously, depending on its count.

Condition Variables:
The Condition class provides a way for one thread to notify other threads about changes in a
shared resource. It is often used with locks to implement producer-consumer scenarios.

Event Objects:
The Event class allows one thread to signal an event to other threads. It is often used to
coordinate the execution of threads based on specific conditions.

These synchronization primitives help in writing thread-safe code by managing access to shared
resources and ensuring that multiple threads can work together effectively. It's important to
choose the appropriate synchronization mechanism based on the specific requirements of the
multithreaded application.

import threading

# Shared counter
counter = 0

# Lock for synchronization


counter_lock = threading.Lock()

# Function to increment the counter


def increment_counter():
global counter
for _ in range(100000):
with counter_lock:
counter += 1

# Create two threads


thread1 = threading.Thread(target=increment_counter)
thread2 = threading.Thread(target=increment_counter)

# Start the threads


thread1.start()
thread2.start()

# Wait for both threads to finish


thread1.join()
thread2.join()

# Display the final value of the counter


print("Final Counter Value:", counter)

16.What is module? Explain with example.


In Python, a module is a file containing Python definitions and statements. Modules allow you
to organize your Python code logically, break it into reusable components, and avoid naming
conflicts. A module can define functions, classes, and variables, and it can also include runnable
code.
# math_operations.py

def add(x, y):


"""Function to add two numbers."""
return x + y

def subtract(x, y):


"""Function to subtract two numbers."""
return x - y

def multiply(x, y):


"""Function to multiply two numbers."""
return x * y

def divide(x, y):


"""Function to divide two numbers."""
if y != 0:
return x / y
else:
return "Cannot divide by zero"

# Variable in the module


module_variable = "I am a module variable"

# Code to run when the module is imported


print("Module math_operations has been imported.")

This demonstrates the concept of a module in Python. It encapsulates related functionality and
can be reused in other scripts by importing it using the import statement.

17.Write a program to validate URL using regular expression. Explain every special character
of the regular expression used in this program.
import re

def validate_url(url):
# Regular expression for validating a URL
url_pattern = re.compile(
r'^(https?|ftp):\/\/' # Protocol (http, https, or ftp)
r'([a-zA-Z0-9-]+\.?)+[a-zA-Z]{2,}' # Domain name
r'(:\d+)?' # Optional port number
r'(\/\S*)?$' # Optional path
)

# Check if the provided URL matches the pattern


if url_pattern.match(url):
print(f"{url} is a valid URL.")
else:
print(f"{url} is not a valid URL.")

# Example usage
validate_url("https://www.example.com/path/to/page")

18.Write a multithreading program, where one thread prints square of a number and another
thread prints factorial of a number. Also display the total time taken for the execution.
import threading
import time
import math

# Function to calculate square


def calculate_square(number):
result = number * number
print(f"Square of {number}: {result}")

# Function to calculate factorial


def calculate_factorial(number):
result = math.factorial(number)
print(f"Factorial of {number}: {result}")

if __name__ == "__main__":
# Get the input number
input_number = int(input("Enter a number: "))

# Record the start time


start_time = time.time()

# Create threads for square and factorial calculations


thread_square = threading.Thread(target=calculate_square, args=(input_number,))
thread_factorial = threading.Thread(target=calculate_factorial, args=(input_number,))

# Start the threads


thread_square.start()
thread_factorial.start()

# Wait for both threads to finish


thread_square.join()
thread_factorial.join()

# Calculate and display total time taken


end_time = time.time()
total_time = end_time - start_time
print(f"Total time taken for execution: {total_time} seconds")

19.What is anonymous function in python? Demonstrate with example.


In Python, an anonymous function is a function defined without a name. Anonymous functions
are created using the lambda keyword. They are also known as lambda functions. Lambda
functions are often used for short, simple operations where a full function definition using the
def keyword would be overly verbose.

Lambda functions are often used in conjunction with functions like map(), filter(), and sorted()
where a small, anonymous function is needed for a short-lived operation.
# Regular function definition
def add(x, y):
return x + y

# Equivalent lambda function


lambda_add = lambda x, y: x + y

# Using both functions


result1 = add(3, 5)
result2 = lambda_add(3, 5)

print("Result from regular function:", result1)


print("Result from lambda function:", result2)

20.Create 5*5 2D NumPy assay and retrieve top left corner 2*2 array from it.
import numpy as np

# Create a 5x5 2D NumPy array


array_2d = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])

# Retrieve the top left corner 2x2 array


top_left_corner = array_2d[:2, :2]

# Display the original array and the top left corner


print("Original 2D Array:")
print(array_2d)

print("\nTop Left Corner 2x2 Array:")


print(top_left_corner)

21.Write a program to illustrate slicing in numpy array.


import numpy as np

# Create a 2D NumPy array


array_2d = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])

# Display the original array


print("Original 2D Array:")
print(array_2d)

# Example of slicing
sliced_row = array_2d[1, 1:4] # Slice the second row from column index 1 to 3
sliced_column = array_2d[1:4, 2] # Slice the third column from row index 1 to 3
subarray = array_2d[:2, :3] # Slice the top-left 2x3 subarray

# Display the sliced results


print("\nSliced Row:")
print(sliced_row)

print("\nSliced Column:")
print(sliced_column)

print("\nSubarray:")
print(subarray)

22.Create pandas dataframe using two dimensional list. Perform following operations.
• Count number of rows
• Count missing values in first column
• Display number of columns in data frame
import pandas as pd

# Create a two-dimensional list


data = [
['John', 25, 'Male'],
['Alice', 30, 'Female'],
['Bob', None, 'Male'],
['Eve', 28, 'Female'],
[None, 35, 'Male']
]
# Create a DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age', 'Gender'])

# Display the DataFrame


print("DataFrame:")
print(df)

# Count number of rows


num_rows = len(df)
print(f"\nNumber of Rows: {num_rows}")

# Count missing values in the first column


missing_values_first_column = df['Name'].isnull().sum()
print(f"Missing Values in the First Column: {missing_values_first_column}")

# Display the number of columns in the DataFrame


num_columns = len(df.columns)
print(f"Number of Columns: {num_columns}")

23. Explain the terms w.r.t. oops in python


• Init
• Self
In Python, when working with object-oriented programming (OOP), the terms _init_ and self are
related to the concept of constructors and instance methods. Let's discuss each term:

_init_:
_init_ is a special method in Python classes and is used for initializing the attributes of an object.
It is often referred to as the constructor.
When a new object is created, the _init_ method is automatically called, allowing you to set up
the initial state of the object.
It is not mandatory to have an _init_ method in a class, but it is commonly used to define and
initialize the attributes of the object.
The _init_ method can take parameters, and these parameters are typically used to set the initial
values of the object's attributes.
The self-parameter, which represents the instance of the class, is always the first parameter in
the _init_ method.
self:
self is a convention in Python that represents the instance of the class. It is the first parameter
of any instance method.
When you call a method on an object, the instance is automatically passed as the first argument
to the method. By convention, this parameter is named self.
Using self allows you to access and modify the attributes of the instance within the class
methods.
self is not a keyword; you could technically use any name for this parameter, but it is a widely
adopted convention to use self for clarity.

24.Create 3*3 numpy array and display column wise mean and median.
import numpy as np

# Create a 3x3 NumPy array


array_2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Display the original array


print("Original 3x3 Array:")
print(array_2d)

# Calculate and display column-wise mean


column_means = np.mean(array_2d, axis=0)
print("\nColumn-wise Mean:")
print(column_means)

# Calculate and display column-wise median


column_medians = np.median(array_2d, axis=0)
print("\nColumn-wise Median:")
print(column_medians)

25.Create a series from numpy array and find max and mean of unique items of series.
import numpy as np
import pandas as pd

# Create a NumPy array


numpy_array = np.array([1, 2, 3, 4, 4, 5, 5, 6, 7, 7])
# Create a Pandas Series from the NumPy array
series = pd.Series(numpy_array)

# Display the original series


print("Original Series:")
print(series)

# Find unique items in the series


unique_items = series.unique()

# Display unique items


print("\nUnique Items in Series:")
print(unique_items)

# Calculate and display the maximum and mean of unique items


max_value = unique_items.max()
mean_value = unique_items.mean()

print(f"\nMaximum of Unique Items: {max_value}")


print(f"Mean of Unique Items: {mean_value}")

26.Given data frame as below:


ID Name HRA TA DA
1001 Mohan 12000 6000 10000
2002 Sachin 13000 5000 9000
1003 Virat 11000 4000 8000
• Compute sum of each column
• Compute mean of each integer column
• Compute median of each integer column
import pandas as pd

# Create the DataFrame


data = {
'ID': [1001, 2002, 1003],
'Name': ['Mohan', 'Sachin', 'Virat'],
'HRA': [12000, 13000, 11000],
'TA': [6000, 5000, 4000],
'DA': [10000, 9000, 8000]
}

df = pd.DataFrame(data)

# Display the original DataFrame


print("Original DataFrame:")
print(df)

# Compute sum of each column


column_sums = df.sum()
print("\nSum of Each Column:")
print(column_sums)

# Compute mean of each integer column


integer_columns_mean = df[['ID', 'HRA', 'TA', 'DA']].mean()
print("\nMean of Each Integer Column:")
print(integer_columns_mean)

# Compute median of each integer column


integer_columns_median = df[['ID', 'HRA', 'TA', 'DA']].median()
print("\nMedian of Each Integer Column:")
print(integer_columns_median)

27.Compute overloading in python with example.


In Python, function overloading is not supported in the same way it is in some other
programming languages like C++ or Java. In Python, when you define multiple functions with the
same name in the same scope, the last function definition will override the previous ones.
However, Python supports a form of overloading using default arguments and variable-length
arguments. You can define a function with default values for some or all of its parameters, and
you can also use variable-length argument lists (*args and **kwargs) to handle a variable
number of arguments.
def add(a, b=0, c=0):
return a + b + c

# Example usage
result1 = add(1)
result2 = add(1, 2)
result3 = add(1, 2, 3)
print("Result with one argument:", result1)
print("Result with two arguments:", result2)
print("Result with three arguments:", result3)

It's important to note that Python doesn't perform strict function overloading based on the
number or types of arguments like some statically-typed languages do. Instead, it relies on
default values and variable-length arguments to provide flexibility.

28.Explain positional and keyword argument in function. Use suitable example.


Positional Arguments:
Positional arguments are the most common type of arguments in Python.
They are passed to a function in the order in which the parameters are defined in the function
signature. The values of positional arguments are assigned based on their positions.

def greet(name, greeting):


print(f"{greeting}, {name}!")

# Example of positional arguments


greet("Alice", "Hello")

Keyword Arguments:
Keyword arguments are passed to a function using the parameter names, and their order doesn't
matter. They provide more clarity and flexibility when calling a function, especially if the function
has multiple parameters.

def greet(name, greeting):


print(f"{greeting}, {name}!")

# Example of keyword arguments


greet(greeting="Hola", name="Carlos")

29.Describe instance variable, static variable and local variable in python object-oriented
programming with example.
In Python object-oriented programming (OOP), instance variables, static variables (also known
as class variables), and local variables are different types of variables associated with classes and
objects.
Instance Variables:
• Instance variables are variables that belong to an instance of a class.
• They are created for each instance/object of the class and are specific to that instance.
• They are defined within methods using the self-keyword.

Static Variables (Class Variables):


• Static variables are shared among all instances of a class.
• They are defined outside any method and are associated with the class rather than with
instances.
• They are often used for constants or variables shared by all instances.

Local Variables:
• Local variables are variables defined within a method and are only accessible within that
method.
• They are temporary and exist only during the execution of the method.
• They are not related to the class or its instances.

30.What is lambda with example.


In Python, lambda is a keyword that is used to create anonymous functions, also known as
lambda functions. Lambda functions are small, unnamed functions defined using a compact
syntax. They are often used for short, one-time operations and are particularly handy when you
need a quick function for a short period.

Lambda functions are often used in conjunction with functions like map (), filter (), and sorted ()
where a short, anonymous function is needed.

While lambda functions are concise and can be powerful for certain use cases, they are generally
recommended for simple operations. For more complex functions, it's often better to use a
regular named function.

numbers = [1, 2, 3, 4, 5]

# Using lambda with map to square each element


squared_numbers = map(lambda x: x**2, numbers)

print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]


31.Illustrate CRUD operations in MongoDB with example
CRUD (Create, Read, Update, Delete) operations in MongoDB are fundamental operations for
managing data in a MongoDB database. MongoDB is a NoSQL database that stores data in
flexible, JSON-like documents.

import pymongo

# Connect to the MongoDB server running on localhost


client = pymongo.MongoClient("mongodb://localhost:27017/")

# Create or switch to a database named "mydatabase"


database = client["mydatabase"]

# Create a collection named "mycollection"


collection = database["mycollection"]

# --- Create (Insert) ---


# Insert a document into the collection
document_to_insert = {"name": "John", "age": 30, "city": "New York"}
inserted_result = collection.insert_one(document_to_insert)
print("Insert Result:", inserted_result.inserted_id)

# --- Read (Find) ---


# Find a document in the collection
query = {"name": "John"}
found_document = collection.find_one(query)
print("Found Document:", found_document)

# --- Update ---


# Update a document in the collection
update_query = {"name": "John"}
new_values = {"$set": {"age": 31, "city": "San Francisco"}}
update_result = collection.update_one(update_query, new_values)
print("Update Result:", update_result.modified_count)

# --- Read (Find) after Update ---


# Find the updated document
found_updated_document = collection.find_one(query)
print("Found Updated Document:", found_updated_document)
# --- Delete ---
# Delete a document from the collection
delete_query = {"name": "John"}
delete_result = collection.delete_one(delete_query)
print("Delete Result:", delete_result.deleted_count)

# --- Read (Find) after Delete ---


# Try to find the deleted document
found_deleted_document = collection.find_one(query)
print("Found Deleted Document:", found_deleted_document)

• Create (Insert): Inserting a document into the MongoDB collection.


• Read (Find): Finding a document in the MongoDB collection.
• Update: Updating a document in the MongoDB collection.
• Read (Find) after Update: Confirming the changes after the update.
• Delete: Deleting a document from the MongoDB collection.
• Read (Find) after Delete: Confirming the document is no longer present after deletion.

32.Compare SQL Database with NoSQL Database.


SQL databases and NoSQL databases are two broad categories of database management
systems, and they differ in their data models, structures, and use cases. Here's a comparison
between SQL and NoSQL databases:

SQL Database (Relational Database):

Data Model:
SQL databases use a structured and tabular data model.
Data is organized into tables with rows and columns.
Each table has a predefined schema, and data must conform to this schema.

Schema:
SQL databases are schema-based, meaning the structure of the database, including tables and
their relationships, is defined in advance.
Changes to the schema can be complex and may require migrations.
Scaling:
Vertical scaling (increasing the power of a single server) is a common approach to handle
increased loads.
Scaling can be more challenging and expensive compared to NoSQL databases.

Transactions:
ACID properties (Atomicity, Consistency, Isolation, Durability) are maintained to ensure data
integrity.
Suitable for applications where data consistency and integrity are critical, such as banking
systems.

Examples:
MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle.

NoSQL Database:

Data Model:
NoSQL databases support various data models, including document-based, key-value pairs,
column-family, and graph databases.
The data structure can be dynamic and unstructured.

Schema:
NoSQL databases are schema-less or have a dynamic schema, allowing flexibility in data storage.
Documents or objects can be added without requiring a predefined schema.

Scaling:
Horizontal scaling (adding more servers to a distributed system) is a common approach.
Scaling is typically easier and more cost-effective compared to SQL databases.

Transactions:
May not strictly adhere to ACID properties.
Emphasizes eventual consistency, providing higher performance for read and write operations
in distributed systems.

Examples:
MongoDB, Cassandra, CouchDB, Redis, Neo4j.
33.Wrte a program to check whether entered string and number is palindrome or not.
def is_palindrome(input_value):
# Convert the input to a string for consistency
input_str = str(input_value)

# Reverse the string


reversed_str = input_str[::-1]

# Check if the original and reversed strings are the same


return input_str == reversed_str

# Get input from the user


user_input = input("Enter a string or number: ")

# Check if the input is a palindrome


if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")

34.Explain generators in python with suitable example.


In Python, a generator is a special type of inerrable, defined using a function with the yield
statement. Generators allow you to iterate over a potentially large sequence of data without
generating the entire sequence in memory at once, making them memory-efficient.

The main difference between a regular function and a generator function is that a generator
function uses yield to produce a series of values over time, and it retains its state between
successive calls.

Generators are beneficial when working with large datasets or when you want to generate values
on-the-fly. They are memory-efficient because they only produce one value at a time and don't
store the entire sequence in memory.

Generators are an essential feature in Python for handling large datasets, streaming data, and
optimizing memory usage in various scenarios.
35.Explain decoders in python with suitable example.
In Python, decorators are a powerful and flexible way to modify or extend the behavior of
functions or methods. Decorators allow you to wrap another function, enabling you to execute
code before and after the wrapped function is called. They are denoted by the
@decorator_name syntax.

Decorators are a powerful tool in Python, and they are commonly used in web frameworks,
logging, memoization, and other scenarios where you want to modify the behavior of functions
or methods in a clean and reusable way.

36.Explain numpy integer indexing, array indexing. Boolean array indexing and slicing with
example.
1. Integer Array Indexing:
You can use an array of integers to index into another array. This is often used to select specific
elements from an array.
import numpy as np

# Create a sample array


arr = np.array([10, 20, 30, 40, 50])

# Integer array indexing


indices = np.array([1, 3, 4])
selected_elements = arr[indices]

print("Original Array:", arr)


print("Selected Elements:", selected_elements)

2. Array Indexing:
For multi-dimensional arrays, you can use tuples of integers to index into each dimension.
import numpy as np

# Create a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Array indexing
element = arr_2d[1, 2]

print("Original 2D Array:")
print(arr_2d)
print("Selected Element:", element)

3. Boolean Array Indexing:


You can use boolean arrays to index into an array, selecting elements where the corresponding
boolean value is True.
import numpy as np

# Create an array
arr = np.array([1, 2, 3, 4, 5])

# Boolean array indexing


bool_indices = arr > 2
selected_elements = arr[bool_indices]

print("Original Array:", arr)


print("Boolean Indices:", bool_indices)
print("Selected Elements:", selected_elements)

4. Slicing:
Slicing allows you to extract a portion of an array.
import numpy as np

# Create an array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

# Slicing
subset = arr[2:6]

print("Original Array:", arr)


print("Sliced Subset:", subset)

These are just a few examples of the various indexing techniques available in NumPy.
Understanding and leveraging these indexing methods can significantly enhance your ability to
work with multi-dimensional arrays efficiently.

37.Draw bar graph using matplotlib and decorate it by adding various elements.
import matplotlib.pyplot as plt

# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [25, 40, 30, 35]

# Create a bar graph


plt.bar(categories, values, color='skyblue')

# Add labels and title


plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Graph Example')

# Add grid lines


plt.grid(True, linestyle='--', alpha=0.6)

# Add annotations on top of the bars


for i, value in enumerate(values):
plt.text(i, value + 1, str(value), ha='center', va='bottom')

# Show the bar graph


plt.show()

38.Explain Multiple inheritance in python with suitable example.


Multiple inheritance is a feature in object-oriented programming where a class can inherit
attributes and methods from more than one parent class. In Python, a class can inherit from
multiple classes by listing them in its class definition.
# Parent class 1
class Animal:
def _init_(self, name):
self.name = name

def speak(self):
pass

# Parent class 2
class Mammal:
def give_birth(self):
print("Giving birth to live young.")

# Parent class 3
class Bird:
def lay_eggs(self):
print("Laying eggs.")

# Child class inheriting from Animal, Mammal, and Bird


class Platypus(Animal, Mammal, Bird):
def _init_(self, name):
# Call constructors of parent classes
Animal._init_(self, name)
Mammal._init_(self)
Bird._init_(self)

def speak(self):
print("Platypus says Quack!")

# Create an instance of the Platypus class


perry = Platypus("Perry")

# Access attributes and methods


print(f"Name: {perry.name}")
perry.speak()
perry.give_birth()
perry.lay_eggs()

Multiple inheritance can lead to complex class hierarchies, and care should be taken to avoid
ambiguity or the diamond problem (a situation where two parent classes have a common
ancestor). It's often recommended to use multiple inheritance judiciously and favor composition
or interfaces in some cases.

39.Write a program to read the contents of file and display occurrence of given character.
def count_occurrence(file_path, char_to_count):
try:
# Open the file in read mode
with open(file_path, 'r') as file:
# Read the entire content of the file
content = file.read()

# Count the occurrence of the given character


char_count = content.count(char_to_count)
# Display the result
print(f"The character '{char_to_count}' occurs {char_count} times in the file.")

except FileNotFoundError:
print(f"Error: File not found at path: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")

# Example: Count the occurrence of the character 'a' in a file


file_path = 'example.txt' # Provide the actual file path
character_to_count = 'a'
count_occurrence(file_path, character_to_count)

40.What is dictionary in python? Explain with example.


In Python, a dictionary is a built-in data type that stores key-value pairs. It is an unordered,
mutable collection, and each key in a dictionary must be unique. Dictionaries are widely used
for organizing and retrieving data based on keys rather than indices, making them highly efficient
for certain types of data access patterns.
# Creating a dictionary
student = {
'name': 'Alice',
'age': 25,
'grade': 'A',
'courses': ['Math', 'Physics', 'History']
}

# Accessing values using keys


print("Name:", student['name'])
print("Age:", student['age'])
print("Courses:", student['courses'])

# Modifying values
student['age'] = 26
student['grade'] = 'B'
student['courses'].append('Computer Science')

# Adding a new key-value pair


student['gender'] = 'Female'
# Displaying the updated dictionary
print("Updated Student Information:", student)
Dictionaries provide a convenient and efficient way to represent and manipulate structured data,
especially when the relationships between different pieces of information are important.

41.Write a short note on packages in python.


In Python, a package is a way of organizing related modules into a single directory hierarchy. It
allows you to structure your Python code in a hierarchical and modular manner, making it easier
to manage, maintain, and reuse code across different projects. A package is essentially a
directory containing a special file called _init_.py and possibly subdirectories with additional
modules or sub-packages.

Key points about packages in Python:

Directory Structure:
A package is a directory that contains a special file named _init_.py. This file can be empty or
may contain Python code. Its presence indicates that the directory should be treated as a
package.

Module Organization:
Modules within a package are organized hierarchically. You can have sub-packages within a
package, forming a tree-like structure

Importing:
Modules within a package can be imported using the dot notation. For example, to import
module1.py in the above structure: import mypackage.module1.

Namespace Isolation:
Packages provide a way to create a namespace, helping avoid naming conflicts between modules
in different packages.
For example, two packages can have modules with the same name (e.g., utils.py), but they won't
conflict because they are in different packages.

Initialization Code:
The _init_.py file can contain initialization code that is executed when the package is imported.
This can be useful for setting up package-level configurations or variables.
Subpackages:
Packages can have sub-packages, creating a hierarchical structure. This allows for logical
organization of code, making it easier to navigate and understand.

Distribution:
Packages are often used in conjunction with Python's packaging and distribution mechanisms,
such as setuptools and pip. This makes it easy to distribute and install Python projects.

In summary, packages provide a way to organize and structure Python code, facilitating
modularity, code reuse, and project organization. They are an integral part of Python's module
system and contribute to writing maintainable and scalable code.

42.Explain operator overloading in python.


Operator overloading in Python refers to the ability to define or redefine the behavior of
operators for user-defined objects. Python allows you to define special methods in your classes
that are called when instances of the class are used with standard operators. This provides a way
to customize the behavior of operators for objects of your class.

The key to operator overloading lies in defining special methods with double underscores (often
referred to as "dunder" methods). For example, to overload the + operator, you can define the
_add_ method in your class.

You can then create instances of ComplexNumber and use the + and * operators as if you were
working with built-in types. Operator overloading provides a way to make your classes more
intuitive and allows you to define custom behaviors for operators based on the context of your
objects.

You might also like