PYthon Last Moment
PYthon Last Moment
PYthon Last Moment
1.Write a program to check the number entered by user is even or odd. Program should accept
integer only.
# Main program
try:
# Get user input
user_input = int(input("Enter an integer: "))
except ValueError:
print("Invalid input! Please enter an integer.")
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
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
values = [1, 2, 3, 4]
print_values(*values) # Unpacking the list
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
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()
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.
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)
except ValueError:
# Handle the exception if the input is not a valid number
return "Invalid input! Please enter a valid number."
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
# 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}")
# File path
file_path = 'employee.txt'
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
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.
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.
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
12.Write a python program to update the employee details stored in “Employee” collection
stored in MangoDB Database.
import pymongo
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()
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"Error: {e}")
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
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"
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
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
)
# 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
if __name__ == "__main__":
# Get the input number
input_number = int(input("Enter a number: "))
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
20.Create 5*5 2D NumPy assay and retrieve top left corner 2*2 array from it.
import numpy as np
# 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
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
_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
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
df = pd.DataFrame(data)
# 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.
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.
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.
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.
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]
import pymongo
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)
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
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)
# Create an array
arr = np.array([1, 2, 3, 4, 5])
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]
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]
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.")
def speak(self):
print("Platypus says Quack!")
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()
except FileNotFoundError:
print(f"Error: File not found at path: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
# Modifying values
student['age'] = 26
student['grade'] = 'B'
student['courses'].append('Computer Science')
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.
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.