0% found this document useful (0 votes)
7 views8 pages

PYTHONANS

The document provides a comprehensive overview of Django and Python programming concepts, including the use of Django for web development, its components like settings.py and urls.py, and features such as models, views, and forms. It also covers various Python concepts such as encapsulation, inheritance, polymorphism, and the differences between SQL and NoSQL databases. Additionally, it discusses Python's features, applications, and object-oriented programming principles.

Uploaded by

Sarang Tilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

PYTHONANS

The document provides a comprehensive overview of Django and Python programming concepts, including the use of Django for web development, its components like settings.py and urls.py, and features such as models, views, and forms. It also covers various Python concepts such as encapsulation, inheritance, polymorphism, and the differences between SQL and NoSQL databases. Additionally, it discusses Python's features, applications, and object-oriented programming principles.

Uploaded by

Sarang Tilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Question1

Q1: What is Django primarily used for in web development? def set_age(self, age):
Django is primarily used for building web applications. It is a high-level Python web if age > 0:
framework that encourages rapid development and clean, pragmatic design. self._age = age
Q2: Name the language Django is written in. else:
Django is written in Python. print("Age must be positive")
Q3: Which file in Django stores settings for the project?
The settings.py file stores the configuration settings for a Django project. obj = MyClass("John", 30)
Q4: What is the purpose of the urls.py file in a Django project? print(obj.name) # Accessing public attribute
The urls.py file is used to define URL patterns for routing requests to the appropriate views print(obj.get_age()) # Accessing protected attribute via method
in a Django project. obj.set_age(35)
Q5: What does a Django model represent in a database? print(obj.get_age())
A Django model represents a table in a database. It is used to define the structure of the data, Q23. What is Polymorphism in Python?
including fields and behaviors. Polymorphism is a concept where a single function or method can work in different ways
Q6: Which method is commonly used to save data from a model to the database in depending on the context. In Python, polymorphism can be achieved using method
Django? overriding and method overloading.
The save() method is commonly used to save data from a model to the database in Django. Example:
Q7: What is the main function of a view in Django? class Shape:
The main function of a view in Django is to handle web requests and return web responses. def area(self):
It can include data retrieval, business logic, and rendering templates. pass
Q8: What type of view is used for handling HTTP requests in Django?
Class-based views (CBVs) or function-based views (FBVs) are used for handling HTTP class Rectangle(Shape):
requests in Django. CBVs use classes to handle requests, while FBVs use functions. def __init__(self, width, height):
Q9: How do you display a variable in a Django template? self.width = width
You can display a variable in a Django template using double curly braces: {{ self.height = height
variable_name }}.
Q10: What feature of Django templates allows code reuse through inheritance? def area(self):
Template inheritance allows code reuse in Django templates. This is achieved using the {% return self.width * self.height
block %} and {% extends %} tags.
Q11: What is the primary purpose of Django forms? class Circle(Shape):
The primary purpose of Django forms is to handle form rendering, validation, and def __init__(self, radius):
processing user input in a clean and secure way. self.radius = radius
Q12: Which method in a Django form is used to clean and validate data?
The clean() method and clean_<fieldname>() methods are used to clean and validate data in def area(self):
Django forms. return 3.14 * self.radius * self.radius
Q13: Which Django method is used to verify a user's credentials?
The authenticate() method is used to verify a user's credentials in Django. shapes = [Rectangle(3, 4), Circle(5)]
Q14: What decorator is used to restrict access to views to authenticated users in for shape in shapes:
Django? print(shape.area())
The @login_required decorator is used to restrict access to views to authenticated users in Q24. What is an Abstract Class in Python?
Django. An abstract class is a class that cannot be instantiated on its own and is meant to be
Q15: What is the purpose of a Serializer in Django Rest Framework? subclassed. It often contains one or more abstract methods, which are methods that have
A Serializer in Django Rest Framework is used to convert complex data types, such as declarations but no implementations. In Python, abstract classes are created using the abc
querysets and model instances, into native Python data types that can then be easily rendered module.
into JSON, XML, or other content types. Example:
Q16: Name one common tool used for deploying Django applications. from abc import ABC, abstractmethod
One common tool used for deploying Django applications is Heroku
Q17. Which are the types of NoSQL databases? class Animal(ABC):
Key-Value Stores @abstractmethod
Document Stores def sound(self):
Column-Based Stores pass
Graph Databases
Time Series Databases class Dog(Animal):
Wide Column Stores def sound(self):
Object-Oriented Databases return "Bark"
Q18. Write examples of key-value store Databases. class Cat(Animal):
Redis def sound(self):
Amazon DynamoDB return "Meow"
Riak # animal = Animal() # This will raise an error
Memcached dog = Dog()
Oracle NoSQL Database cat = Cat()
Q19. Name the fields where Column-based NoSQL databases are widely used. print(dog.sound())
Real-Time Analytics print(cat.sound())
Data Warehousing Q25. Explain the concept of __init__ method in Python.
Content Management Systems The __init__ method in Python is a special method called a constructor. It is automatically
Internet of Things (IoT) Applications invoked when a new instance of a class is created. The __init__ method is used to initialize
Time Series Data the instance attributes of the class.
Q20. Which are popular graph-based databases? Example:
Neo4j python
Amazon Neptune class Person:
OrientDB def __init__(self, name, age):
ArangoDB self.name = name
Microsoft Azure Cosmos DB (with Gremlin API) self.age = age
JanusGraph
Q21. What is a Sharding? def display(self):
Sharding is a database architecture pattern in which a large dataset is divided into smaller, print(f"Name: {self.name}, Age: {self.age}")
more manageable pieces called shards. Each shard is a separate database instance. The idea person = Person("Alice", 25)
is to spread the data across multiple machines to improve performance, scalability, and load person.display()
balancing. Sharding is often used in NoSQL databases to handle large volumes of data and Q26. Define the term super() in Python.
high transaction rates. The super() function in Python is used to call a method from the parent class. It is
Q22. Explain encapsulation with an example in Python. commonly used in the context of method overriding to call the parent class's version of a
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). method from within the child class's overridden method.
It refers to the bundling of data with the methods that operate on that data. Encapsulation Example:
restricts direct access to some of an object's components, which can prevent the accidental class Parent:
modification of data. In Python, encapsulation can be achieved using private and protected def greet(self):
access modifiers. print("Hello from Parent")
Example:
class MyClass: class Child(Parent):
def __init__(self, name, age): def greet(self):
self.name = name # Public attribute super().greet()
self._age = age # Protected attribute print("Hello from Child")

def get_age(self): child = Child()


return self._age child.greet()
● Dynamically Typed
Q27. What is the difference between @staticmethod and @classmethod in Python?
@staticmethod: Defines a method that does not operate on an instance or class level. It ● Extensive Standard Library
does not take the self or cls parameter. ● Support for Multiple Paradigms (object-oriented, procedural, functional)
python
class MyClass:
● Cross-Platform Compatibility
@staticmethod ● Open Source and Community-Driven
def static_method(): ● Readability and Maintainability
print("This is a static method") ● Support for GUI Programming
MyClass.static_method() ● Strong Integration Capabilities (with other languages and tools)
@classmethod: Defines a method that operates on the class level. It takes cls as a Q33. 'Python programming language is interpreted and interactive'. Comment this
parameter, representing the class itself. sentence.
python ● Interpreted: Python code is executed line by line by an interpreter, rather than being
class MyClass: compiled into machine code. This makes debugging easier and allows for quick
@classmethod testing and iteration.
def class_method(cls):
print("This is a class method")
● Interactive: Python provides an interactive mode (REPL - Read-Eval-Print Loop)
where you can enter and execute commands one at a time and see immediate results.
This is useful for testing code snippets, prototyping, and learning the language.
MyClass.class_method()
Q34. 'Python has developed as an open source project'. Justify this statement.
Q28. What is method resolution order (MRO) in Python?
Python is an open-source project, meaning its source code is freely available and can be
Method Resolution Order (MRO) is the order in which Python looks for a method in a
modified and distributed by anyone. It is developed and maintained by a community of
hierarchy of classes. This is especially important in the context of multiple inheritance.
contributors and governed by the Python Software Foundation. The open-source nature of
The MRO can be viewed using the __mro__ attribute or the mro() method.
Python has led to a vast ecosystem of libraries and frameworks, making it a versatile and
Example:
widely adopted language.
class A:
Q35. What is the difference between interactive mode and script mode of Python?
def method(self):
print("A") ● Interactive Mode: Allows you to execute Python commands one at a time and see
class B(A): results immediately. It is useful for testing, debugging, and experimentation.
def method(self): bash
print("B") $ python
class C(A): >>> print("Hello, World!")
def method(self): Hello, World!
print("C") ● Script Mode: Allows you to write Python code in a file (script) and execute the entire
class D(B, C): script at once. It is useful for larger programs and projects.
pass bash
d = D() $ python my_script.py
d.method() Q36. What is the use of comparison operator?
print(D.__mro__) # Method resolution order Comparison operators in Python are used to compare values. They return a Boolean value
Q29. Explain the concept of multiple inheritance with an example in Python. (True or False). The comparison operators are:
Multiple inheritance is a feature in which a class can inherit from more than one base
class. This allows a class to combine behaviors from multiple classes.
1. ==: Equal to
Example: 2. !=: Not equal to
class Base1: 3. >: Greater than
def method1(self):
print("Base1 method")
4. <: Less than
5. >=: Greater than or equal to
class Base2: 6. <=: Less than or equal to
def method2(self): Q37. Mention the features of identity operators?
print("Base2 method") Identity operators in Python are used to compare the memory locations of two objects. They
are:
class Derived(Base1, Base2): is: Returns True if both variables point to the same object
pass is not: Returns True if both variables point to different objects
Example:
d = Derived() python
d.method1() a = [1, 2, 3]
d.method2() b= a
Q30. What is the use of isinstance() and issubclass() functions in Python? c = [1, 2, 3]
isinstance(): Checks if an object is an instance of a class or a subclass thereof.
python print(a is b) # True
class MyClass: print(a is c) # False
pass print(a is not c) # True
Q38. Give the characteristics of membership operator?
obj = MyClass() Membership operators in Python are used to test whether a value or variable is found in a
print(isinstance(obj, MyClass)) # True sequence (such as a string, list, tuple, set, or dictionary). They are:
issubclass(): Checks if a class is a subclass of another class. in: Returns True if the value is found in the sequence
python not in: Returns True if the value is not found in the sequence
class Parent: Example:
pass python
lst = [1, 2, 3, 4, 5]
class Child(Parent):
pass print(3 in lst) # True
Q31. Enlist applications for Python programming. print(6 not in lst) # True
Python is used in a wide range of applications, including: Q39. What is the use of break statement in the loop?
● Web Development (e.g., Django, Flask) The break statement is used to terminate the execution of the nearest enclosing loop (for or
● Data Analysis and Visualization (e.g., Pandas, Matplotlib) while loop) prematurely. When a break statement is encountered, the loop is exited, and the
program control resumes at the next statement following the loop.
● Machine Learning and AI (e.g., TensorFlow, scikit-learn) Example:
● Scientific Computing (e.g., SciPy, NumPy) python
● Automation and Scripting
for i in range(10):
if i == 5:
● Game Development (e.g., Pygame) break
● Desktop GUI Development (e.g., Tkinter, PyQt) print(i)
● Network Programming
# Output: 0 1 2 3 4
● Software Development and Testing (e.g., Selenium)
● Education (due to its simplicity and readability)
Q32. What are the features of Python?
Python has several key features, including:
● Easy to Learn and Use
● High-Level Language
● Interpreted Language
Question2 Q1. List the features and explain different Object-Oriented features supported by
Q1. Explain NoSQL database. Python.
A NoSQL (Not Only SQL) database is a type of database designed to handle large amounts of Python supports several object-oriented programming (OOP) features:
data and diverse data structures that traditional relational databases (SQL databases) cannot ● Encapsulation: Bundling data with methods that operate on the data.
efficiently manage. NoSQL databases are schema-less, which means they do not require a fixed
table structure, and they can store and retrieve data in ways that are more flexible and scalable. ● Inheritance: Creating new classes based on existing classes.
Common types of NoSQL databases include key-value stores, document stores, column-family ● Polymorphism: Using a single interface to represent different data types.
stores, and graph databases. ● Abstraction: Hiding the complex implementation details and showing only the
Q2. List and explain the advantages of NoSQL database. necessary features.
● Scalability: NoSQL databases are designed to scale out by distributing data across Q2. Design a class that stores the information of a student and displays the same.
multiple servers. python
● Flexibility: Schema-less design allows storing unstructured and semi-structured class Student:
data. def __init__(self, name, age, student_id):
self.name = name
● Performance: Optimized for high performance with large volumes of data and high self.age = age
transaction rates. self.student_id = student_id
● Handling Big Data: Capable of managing large datasets efficiently.
● Distributed Architecture: Supports distributed data storage and processing. def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, ID: {self.student_id}")
● High Availability: Built-in support for replication and failover ensures data
availability. # Example usage
Q3. Differentiate between SQL and NoSQL. student = Student("John Doe", 20, "S12345")
Feature SQL Databases NoSQL Databases student.display_info()
Relational (tables with rows and Various models (key-value, document, Q3. What are basic overloading methods?
Data Model In Python, method overloading is achieved through default arguments and variable-length
columns) column, graph)
Schema Fixed schema Schema-less (flexible schema) arguments, as Python does not support method overloading directly. Common overloading
methods include:
Scalability Vertical scaling (scaling up) Horizontal scaling (scaling out)
ACID
● Default argument values.
Compliance
Strong ACID compliance Varies; some provide eventual consistency ● *args for variable-length positional arguments.

Query Language Structured Query Language (SQL)


Varies; some use proprietary query ● **kwargs for variable-length keyword arguments.
languages Q4. What is method overriding? Write an example.
MySQL, PostgreSQL, Oracle, Method overriding is when a subclass provides a specific implementation of a method
Examples MongoDB, Cassandra, Redis, Neo4j already defined in its superclass.
SQL Server
Example:
Q4. Explain the features of MongoDB.
python
● Document-Oriented: Stores data in BSON format, similar to JSON. class Parent:
● Schema-less: Flexible document structure. def show(self):
● Scalable: Horizontal scaling using sharding.
print("Parent class method")

● High Performance: Optimized for read and write operations. class Child(Parent):
● Replication: Supports replica sets for high availability. def show(self):
print("Child class method")
● Indexing: Supports various types of indexes for fast query performance.
● Aggregation: Provides powerful aggregation framework for data analysis. obj = Child()
● Ad Hoc Queries: Supports dynamic queries on documents. obj.show() # Output: Child class method
Q5. Explain installation steps of PyMongo. Q5. How can operator overloading be implemented in Python? Give an example.
1. Install Python: Ensure Python is installed on your system. Operator overloading allows custom implementation of operators for user-defined classes
bash using special methods (dunder methods).
python --version Example:
2. Install PyMongo: Use pip to install PyMongo, the Python driver for MongoDB. python
bash class Vector:
pip install pymongo def __init__(self, x, y):
3. Verify Installation: Verify the installation by importing PyMongo in a Python self.x = x
script. self.y = y
import pymongo
print(pymongo.__version__) def __add__(self, other):
Q6. Explain Collection, Database, and Documents in PyMongo. return Vector(self.x + other.x, self.y + other.y)
● Database: A MongoDB instance can host multiple databases. Each database def __repr__(self):
contains collections. return f"Vector({self.x}, {self.y})"
from pymongo import MongoClient
client = MongoClient('localhost', 27017) v1 = Vector(1, 2)
db = client['mydatabase'] v2 = Vector(3, 4)
● Collection: A collection is a group of MongoDB documents, similar to a table in a print(v1 + v2) # Output: Vector(4, 6)
relational database. Q6. Define the following terms: Object, Class, Inheritance, Data Abstraction.
collection = db['mycollection'] ● Object: An instance of a class containing data and methods.
● Document: A document is a record in a collection, represented as a JSON-like ● Class: A blueprint for creating objects, defining attributes and behaviors.
structure.
document = {'name': 'John', 'age': 30} ● Inheritance: A mechanism for creating a new class based on an existing class.
collection.insert_one(document) ● Data Abstraction: Hiding implementation details and exposing only essential
Q7. Explain the CRUD operations of MongoDB with Python. features.
● Create: Insert documents into a collection. Q7. Describe the term composition classes with example.
collection.insert_one({'name': 'Alice', 'age': 25}) Composition is a design principle where a class is composed of one or more objects of other
collection.insert_many([{'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]) classes. It represents a "has-a" relationship.
Example:
● Read: Query documents from a collection. python
result = collection.find_one({'name': 'Alice'}) class Engine:
results = collection.find({'age': {'$gt': 25}}) def start(self):
● Update: Modify existing documents. print("Engine started")
collection.update_one({'name': 'Alice'}, {'$set': {'age': 26}})
collection.update_many({'age': {'$gt': 30}}, {'$set': {'status': 'senior'}}) class Car:
● Delete: Remove documents from a collection. def __init__(self, engine):
python self.engine = engine
collection.delete_one({'name': 'Alice'})
collection.delete_many({'age': { '$lt': 30}}) def drive(self):
self.engine.start()
print("Car is driving")

engine = Engine()
car = Car(engine)
car.drive()
● Identity Operators
Q8. Explain customization via inheritance specializing inherited methods.
Customization via inheritance involves creating a subclass that extends or modifies the ● Membership Operators
behavior of a superclass by overriding or adding methods. Q8. What are the different loops available in Python?
Example: ● for loop
python
class Animal:
● while loop
Q9. Explain about different logical operators in Python with appropriate examples.
def sound(self):
pass ● and: Returns True if both statements are true
python
class Dog(Animal): x=5
def sound(self): print(x > 3 and x < 10) # Outputs: True
return "Bark" ● or: Returns True if one of the statements is true
python
class Cat(Animal): x=5
def sound(self): print(x > 3 or x < 4) # Outputs: True
return "Meow"
● not: Reverses the result, returns False if the result is true
python
dog = Dog()
x=5
cat = Cat() print(not(x > 3 and x < 10)) # Outputs: False
print(dog.sound()) # Output: Bark
Q10. Explain about different relational operators in Python with examples.
print(cat.sound()) # Output: Meow
Q9. Explain constructor function in Python class with example. ● ==: Equal to
A constructor is a special method called __init__ in Python. It is automatically invoked when python
an object is created and is used to initialize the object's attributes. x=5
Example: y=5
python print(x == y) # Outputs: True
class Person: ● !=: Not equal to
def __init__(self, name, age): python
self.name = name x=5
self.age = age y=3
print(x != y) # Outputs: True
def display(self):
print(f"Name: {self.name}, Age: {self.age}") Q1. Explain the following features of
● >: Greater than
python
Python programming:
x=5
y=3
● Simple: Python has a straightforward syntax which mimics natural language, making print(x > y) # Outputs: True
it easy to learn and use.
● <: Less than
● Platform Independent: Python is a cross-platform language; Python programs can python
run on various operating systems like Windows, macOS, and Linux without requiring x=5
any modifications. y=3
● Interactive: Python supports interactive mode which allows for testing and print(x < y) # Outputs: False
debugging of snippets of code. The command line can be used to write and test code. ● >=: Greater than or equal to
● Object Oriented: Python supports object-oriented programming which uses objects python
and classes for data manipulation, making it easy to reuse and modularize code. x=5
Q2. What is a variable? What are the rules and conventions for declaring variables? y=5
A variable is a reserved memory location to store values. In Python, you don't need to declare print(x >= y) # Outputs: True
the type of a variable. Rules and Conventions: ● <=: Less than or equal to
● Variable names must start with a letter or underscore (_) and cannot start with a python
number. x=5
y=7
● Variables can only contain alphanumeric characters and underscores (A-z, 0-9, and _
print(x <= y) # Outputs: True
).
Q11. Explain about identity operators in Python with appropriate examples.
● Variable names are case-sensitive (age, Age, and AGE are three different variables).
● is: Returns True if both variables are the same object
Q3. What are the various data types available in Python programming? python
● Numeric Types: int, float, complex x = ["apple", "banana"]
● Sequence Types: list, tuple, range y = ["apple", "banana"]
z=x
● Text Type: str print(x is z) # Outputs: True
● Binary Types: bytes, bytearray, memoryview ● is not: Returns True if both variables are not the same object
● Mapping Type: dict python
● Set Types: set, frozenset print(x is not y) # Outputs: True
Q12. Explain about arithmetic operators in Python.
● Boolean Type: bool
Q4. Explain Dictionary in Python with example. ● +: Addition
A dictionary in Python is a collection of key-value pairs. ● -: Subtraction
python
my_dict = {"name": "John", "age": 30, "city": "New York"}
● \*: Multiplication
print(my_dict["name"]) # Outputs: John ● /: Division
Q5. Define the following terms: ● %: Modulus
● Identifier: A name used to identify a variable, function, class, module, or object. ● \\**: Exponentiation
● Literal: A raw data given in a variable or constant. E.g., 5, 3.14, 'Hello'. ● //: Floor division
● Set: An unordered collection of unique items. Q13. List different conditional statements in Python.
● Tuple: An immutable sequence of items. ● if statement
● List: An ordered collection of items which can be of different types. ● if-else statement
Q6. What is meant by the control structure of a program? Explain with its types. ● if-elif-else ladder
Control structures are constructs that dictate the flow of control in a program. Types: Q14. Explain if-else statement with an example.
● Sequential: Executes statements one after the other. python
x = 10
● Selection: Makes decisions (if, if-else, if-elif-else). if x > 5:
● Iteration: Repeats statements (for, while). print("x is greater than 5")
Q7. What is an operator? Which operators are used in Python? else:
Operators are special symbols in Python that perform arithmetic or logical computations. print("x is not greater than 5")
Types of Operators:
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators Q15. Explain continue statement with an example.
The continue statement is used to skip the rest of the code inside the loop for the current
● Assignment Operators iteration only.
python Q15. Which are the different ways of creation of threads? Explain each with an
for i in range(10): example.
if i == 5: Python supports multithreading using the threading module. Threads can be created in two
continue ways:
print(i) ● Using the Thread class:
Q16. Explain use of break and pass statements in a loop with an example. python
● break: Terminates the loop import threading
python
for i in range(10): def print_numbers():
if i == 5: for i in range(5):
break print(i)
print(i)
● pass: Does nothing, can be used as a placeholder thread = threading.Thread(target=print_numbers)
python thread.start()
for i in range(10): thread.join()
if i == 5: ● Extending the Thread class:
pass python
print(i) import threading
Q17. Predict output and justify your answer:
i. -11%9: The result is 7. The modulus operator returns the remainder of the division. class MyThread(threading.Thread):
ii. 7.7//7: The result is 1.0. The floor division operator // returns the largest integer less than def run(self):
or equal to the result. for i in range(5):
iii. (200-70)*10/5: The result is 260.0. Operations inside parentheses are computed first. print(i)
iv. 5*2: The result is 10.
thread = MyThread()
thread.start()
person = Person("Alice", 25)
person.display()
Q10. What are different types of inheritance supported by Python?
Python supports several types of inheritance:
● Single Inheritance: A subclass inherits from one superclass.
● Multiple Inheritance: A subclass inherits from multiple superclasses.
● Multilevel Inheritance: A subclass inherits from a superclass, which in turn inherits
from another superclass.
● Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
● Hybrid Inheritance: A combination of multiple inheritance types.
Q11. Describe the methods of regular expression.
Regular expression methods in Python's re module include:
● match(): Checks for a match only at the beginning of the string.
● search(): Searches the string for a match.
● findall(): Finds all matches and returns them as a list.
● finditer(): Finds all matches and returns them as an iterator.
● sub(): Replaces matched patterns in a string.
● split(): Splits the string by the occurrences of the pattern.
Q12. Describe all the functions available in match objects.
Match objects in the re module have several methods:
● group(): Returns the entire match or specific groups.
● groups(): Returns a tuple containing all the subgroups.
● start(): Returns the starting position of the match.
● end(): Returns the ending position of the match.
● span(): Returns a tuple containing the start and end positions of the match.
Q13. What are regular expressions? How to find whether an email ID entered by the
user is valid or not using Python 're' module.
Regular expressions (regex) are sequences of characters that define search patterns. They
are used for matching, searching, and manipulating strings.
Example of validating an email ID:
python
import re

def validate_email(email):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(pattern, email) is not None

email = "[email protected]"
if validate_email(email):
print("Valid email")
else:
print("Invalid email")
Q14. Explain the function that is used to retrieve the parts of URL.
In Python, the urllib.parse module provides functions to parse URLs. The urlparse function
can be used to retrieve the parts of a URL.
Example:
python
from urllib.parse import urlparse

url = 'https://www.example.com/path?query=param#fragment'
parsed_url = urlparse(url)
print(parsed_url.scheme) # Output: https
print(parsed_url.netloc) # Output: www.example.com
print(parsed_url.path) # Output: /path
print(parsed_url.query) # Output: query=param
print(parsed_url.fragment) # Output: fragment
1. Graph-based Databases Data abstraction is the process of hiding the implementation details of an object and
Graph-based databases use graph structures with nodes, edges, and properties to represent exposing only the essential features. It simplifies complexity and enhances code
and store data. They are ideal for applications where relationships between data are as maintainability.
important as the data itself. Levels of Data Abstraction:
● Nodes: These represent entities such as people, places, or events. ● Physical Level: How data is physically stored in the database.
● Edges: These represent the relationships between nodes. For example, in a social ● Logical Level: What data is stored and the relationships between data.
network graph, nodes might represent users and edges might represent friendships ● View Level: How data is presented to the end-user.
between them. 7. Class Inheritance
● Properties: These store information about nodes and edges. For instance, a node Class inheritance is a core concept in object-oriented programming where a new class,
representing a person might have properties like name and age. known as the child class, derives properties and behaviors from an existing class, known as
Advantages: the parent class.
● Efficient Relationship Management: Graph databases are designed to handle and Advantages:
query relationships efficiently, making them ideal for applications with complex ● Code Reuse: Allows for reuse of existing code.
interconnections. ● Extensibility: Enables extending and enhancing existing functionality.
● Flexibility: They can easily evolve with changing data models since they do not rely ● Hierarchy: Establishes a logical hierarchy among classes.
on a rigid schema. Example:
● Performance: Designed for deep and complex queries on connected data. python
Use Cases: class Animal:
● Social Networks: Representing users and their connections. def __init__(self, name):
self.name = name
● Recommendation Engines: Suggesting items based on user preferences and
connections. def speak(self):
● Fraud Detection: Detecting patterns and connections in data to identify fraudulent pass
activities.
Examples: Neo4j, Amazon Neptune class Dog(Animal):
2. Column-based NoSQL Databases def speak(self):
Column-based NoSQL databases, also known as column-family stores, store data in return f"{self.name} says Woof!"
columns rather than rows. This design allows for efficient read and write operations for large
volumes of data. dog = Dog("Buddy")
● Column Family: A collection of rows where each row can have a different set of print(dog.speak()) # Outputs: Buddy says Woof!
columns. Column families are stored together, allowing for efficient retrieval of 8. Destructor
related data. A destructor is a special method in object-oriented programming that is called when an
object is about to be destroyed. It is used for clean-up activities like releasing resources.
● Super Column: A special column family that contains other columns or column Example:
families. python
Advantages: class MyClass:
● Scalability: They can handle large amounts of data distributed across many servers. def __init__(self, name):
● Performance: Optimized for read-heavy operations and queries involving large
self.name = name
print(f"{self.name} created")
datasets.
● Flexibility: Supports dynamic addition of new columns without affecting existing def __del__(self):
data. print(f"{self.name} destroyed")
Use Cases:
● Time-series Data: Storing and retrieving time-based events. obj = MyClass("MyObject")
● Real-time Analytics: Fast access to and analysis of large datasets.
del obj # Outputs: MyObject destroyed
9. Delegation and Container
● Content Management Systems: Managing large amounts of semi-structured data.
● Delegation: Involves an object relying on another helper object to perform a certain
Examples: Apache Cassandra, HBase
task.
3. Features of MongoDB
MongoDB is a leading NoSQL database known for its flexibility, scalability, and ease of ● Container: A class designed to hold and manage multiple objects.
use. Example of Delegation:
● Document-Oriented: Uses JSON-like documents to store data, allowing for nested
python
class Helper:
and complex data structures.
def assist(self):
● Schema-Less: Allows for dynamic changes in data structure without predefined print("Helper assisting...")
schemas.
● High Availability: Supports replication through replica sets to ensure data redundancy class Manager:
and high availability. def __init__(self):
● Scalability: Provides horizontal scalability with sharding, distributing data across
self.helper = Helper()
multiple machines.
def perform_task(self):
● Indexing: Supports various types of indexes to improve query performance. self.helper.assist()
● Aggregation Framework: Provides powerful tools for data processing and analysis
through aggregation pipelines. manager = Manager()
Use Cases: manager.perform_task() # Outputs: Helper assisting...
10. findall Function
● Content Management Systems: Managing varied content types.
The findall function in Python's re module finds all non-overlapping matches of a pattern in
● Real-time Analytics: Processing and analyzing data in real-time. a string and returns them as a list.
● Internet of Things (IoT): Storing and analyzing large volumes of sensor data. Example:
4. C-Create CRUD Operation python
CRUD operations are fundamental actions performed on databases. "C" stands for Create. import re
text = "The rain in Spain"
● Create Operation: Involves adding new records to the database. matches = re.findall("ai", text)
o SQL Example: print(matches) # Outputs: ['ai', 'ai']
INSERT INTO users (name, age, email) VALUES ('John Doe', 30, '[email protected]'); 11. compile Function
o MongoDB Example: The compile function in Python's re module compiles a regular expression pattern into a
db.users.insert({name: "John Doe", age: 30, email: "[email protected]"}); regex object, which can be used for matching.
5. Types of NoSQL Databases Example:
NoSQL databases are designed to handle large volumes of unstructured or semi-structured python
data. They fall into four main categories: import re
● Document Stores: Store data as JSON-like documents. Example: MongoDB, pattern = re.compile("ai")
matches = pattern.findall("The rain in Spain")
CouchDB.
print(matches) # Outputs: ['ai', 'ai']
● Key-Value Stores: Store data as key-value pairs. Example: Redis, DynamoDB.
● Column Stores: Store data in columns for efficient querying. Example: Apache
Cassandra, HBase.
● Graph Databases: Use graph structures to represent and store data. Example: Neo4j,
Amazon Neptune.

6. Data Abstraction
12. search Function
The search function in Python's re module searches for the first occurrence of a pattern in a Nested loops are loops within loops. Python supports nesting different types of loops,
string and returns a match object if found. providing flexibility to execute complex iterations. Here are the different nested loops
Example: available in Python:
python 1. Nested for Loop
import re A for loop inside another for loop is a common pattern used to iterate over multi-dimensional
text = "The rain in Spain" data structures like matrices or nested lists.
match = re.search("ai", text) Example:
if match: python
print(f"Match found: {match.group()}") # Outputs: Match found: ai matrix = [
13. Meta-characters [1, 2, 3],
Meta-characters are special characters in regular expressions that control how the matching [4, 5, 6],
process works. [7, 8, 9]
Examples: ]
● .: Matches any character except newline.
for row in matrix:
● *: Matches 0 or more repetitions of the preceding element. for col in row:
● +: Matches 1 or more repetitions of the preceding element. print(col, end=' ')
● ?: Matches 0 or 1 repetition of the preceding element. print() # Outputs: 1 2 3
# 456
● []: Matches any single character within the brackets. # 789
● ^: Matches the start of the string. 2. Nested while Loop
● $: Matches the end of the string. A while loop inside another while loop is useful for situations where the number of iterations
is not known beforehand and depends on some condition.
14. Multithreading
Example:
Multithreading is a programming technique where multiple threads are created within a
python
process to execute tasks concurrently. It allows for better utilization of CPU resources.
i=0
Example:
python while i < 3:
j=0
import threading
while j < 3:
print(i, j)
def print_numbers():
for i in range(5): j += 1
i += 1 # Outputs: (0, 0), (0, 1), (0, 2)
print(i)
# (1, 0), (1, 1), (1, 2)
# (2, 0), (2, 1), (2, 2)
thread = threading.Thread(target=print_numbers)
thread.start() 3. Nested for and while Loop
You can also nest a for loop inside a while loop or vice versa depending on the requirements.
thread.join()
Example:
15. Threads
python
Threads are the smallest units of a process that can be executed independently. They share
i=0
the same memory space but run concurrently.
Example: while i < 3:
for j in range(3):
python
import threading print(i, j)
i += 1 # Outputs: (0, 0), (0, 1), (0, 2)
def task(name): # (1, 0), (1, 1), (1, 2)
# (2, 0), (2, 1), (2, 2)
print(f"Task {name} is running")
4. Nested for Loop with if Statement
Combining nested loops with conditional statements allows for more complex logic.
thread1 = threading.Thread(target=task, args=("A",))
thread2 = threading.Thread(target=task, args=("B",)) Example:
python
for i in range(3):
thread1.start()
for j in range(3):
thread2.start()
if i == j:
thread1.join() print(f"i and j are equal: {i}, {j}") # Outputs: i and j are equal: (0, 0), (1, 1), (2, 2)
thread2.join() 5. Nested Loops with break and continue
Using break and continue within nested loops provides control over the flow of iterations.
16. Membership Operators in Python
Example (break):
Membership operators test whether a value is a member of a sequence, such as a string, list,
or tuple. for i in range(3):
for j in range(3):
● in: Returns True if a value is found in the sequence. if i == 1:
python break
print('a' in 'apple') # Outputs: True print(i, j) # Outputs: (0, 0), (0, 1), (0, 2)
● not in: Returns True if a value is not found in the sequence. # (1, 0)
python # (2, 0), (2, 1), (2, 2)
print('b' not in 'apple') # Outputs: True Example (continue):
17. Applications of Python for i in range(3):
Python is a versatile language used in various domains: for j in range(3):
● Web Development: Using frameworks like Django and Flask.
if j == 1:
continue
● Data Science: Libraries like Pandas and NumPy. print(i, j) # Outputs: (0, 0), (0, 2)
● Machine Learning: Libraries like TensorFlow and Scikit-learn. # (1, 0), (1, 2)
# (2, 0), (2, 2)
● Automation: Tools like Selenium and PyAutoGUI.
6. Nested Loops for Multi-dimensional Array
● Game Development: Libraries like Pygame. Nested loops are frequently used to access elements in multi-dimensional arrays or lists.
18. The Role of Indentation in Python Example:
The Role of Indentation in Python arr = [
● Defines Code Blocks: Indentation is used to indicate which statements belong to [1, 2, 3],
different control structures like loops, conditionals, functions, and classes. [4, 5, 6]
]
● Enhances Readability: Makes the code more readable and understandable by
visually representing the structure and flow. for i in range(len(arr)):
● Consistency: Enforces a consistent coding style, making it easier for multiple for j in range(len(arr[i])):
developers to read and maintain the code. print(arr[i][j], end=' ')
● Standard Practice: Python recommends using four spaces per indentation level. print() # Outputs: 1 2 3
# 456
● Error Prevention: Incorrect indentation raises IndentationError and can cause Nested loops in Python allow for the execution of complex iterative operations, making them
logical errors. indispensable for tasks such as data processing, manipulation of multi-dimensional arrays,
Example: and implementing algorithms that require nested iterations
if True:
print("This is indented properly")
print("This is not")
Indentation in Python is crucial for defining the structure and maintaining the readability of
your code. It’s not just a stylistic choice—it's a fundamental part of the language's syntax.
19. Different Nested Loops Available in Python
IV. Write Programs Q5. Write a Python program to find the occurrence and position of substrings within
Q1. Create a class Employee with data members: name, department, and salary. a string.
Create suitable methods for reading and printing employee information. python
class Employee: def find_substring_occurrences(main_str, sub_str):
def __init__(self, name, department, salary): positions = []
self.name = name start = 0
self.department = department while start < len(main_str):
self.salary = salary start = main_str.find(sub_str, start)
if start == -1:
def read_employee_info(self): break
self.name = input("Enter name: ") positions.append(start)
self.department = input("Enter department: ") start += 1
self.salary = input("Enter salary: ") return positions

def print_employee_info(self): # Usage


print(f"Name: {self.name}, Department: {self.department}, Salary: {self.salary}") main_string = "This is a test string. This test is just a test."
substring = "test"
# Usage print(find_substring_occurrences(main_string, substring))
emp = Employee("John Doe", "HR", 50000) Q6. Write a Python program to retrieve a string starting with 'm' and having 5
emp.print_employee_info() characters.
emp.read_employee_info() python
emp.print_employee_info() def find_string_with_m(strings):
Q2. Create a class Student with the following member attributes: roll no, name, age, result = [s for s in strings if s.startswith('m') and len(s) == 5]
and total marks. Create suitable methods for reading and printing member variables. return result
Write a Python program to overload the == operator to print the details of students
having the same marks. # Usage
class Student: strings_list = ["hello", "world", "mango", "match", "apple"]
def __init__(self, roll_no, name, age, total_marks): print(find_string_with_m(strings_list)) # Outputs: ['mango', 'match']
self.roll_no = roll_no Q7. Write a Python program to search a specific value from a given list of values using
self.name = name the Linear search method.
self.age = age python
self.total_marks = total_marks def linear_search(arr, target):
for i in range(len(arr)):
def read_student_info(self): if arr[i] == target:
self.roll_no = input("Enter roll no: ") return i
self.name = input("Enter name: ") return -1
self.age = input("Enter age: ")
self.total_marks = input("Enter total marks: ") # Usage
arr = [5, 3, 1, 2, 4]
def print_student_info(self): target = 3
print(f"Roll No: {self.roll_no}, Name: {self.name}, Age: {self.age}, Total Marks: print(f"Element found at index: {linear_search(arr, target)}")
{self.total_marks}") Q8. Write a Python program to search a specific value from a given list of values using
the binary search method.
def __eq__(self, other): python
if isinstance(other, Student): def binary_search(arr, target):
return self.total_marks == other.total_marks low, high = 0, len(arr) - 1
return False while low <= high:
mid = (low + high) // 2
# Usage if arr[mid] == target:
student1 = Student(1, "Alice", 20, 85) return mid
student2 = Student(2, "Bob", 21, 85) elif arr[mid] < target:
low = mid + 1
if student1 == student2: else:
student1.print_student_info() high = mid - 1
student2.print_student_info() return -1
Q3. Write a class with the following criteria:
● Class name: Flower # Usage
arr = [1, 2, 3, 4, 5]
● Objects: lily, rose, hibiscus target = 3
● Properties: price, color, smell print(f"Element found at index: {binary_search(arr, target)}")
● Methods: get(), display() Q9. Write a Python program to accept the base and height of a triangle and compute
the area.
class Flower:
def __init__(self, price, color, smell): python
self.price = price def compute_triangle_area(base, height):
self.color = color return 0.5 * base * height
self.smell = smell
# Usage
def get(self): base = float(input("Enter the base of the triangle: "))
self.price = input("Enter price: ") height = float(input("Enter the height of the triangle: "))
self.color = input("Enter color: ") print(f"Area of the triangle: {compute_triangle_area(base, height)}")
self.smell = input("Enter smell: ") Q10. Write a Python program to compute the future value of a specified principal
amount, rate of interest, and a number of years.
def display(self): python
print(f"Price: {self.price}, Color: {self.color}, Smell: {self.smell}") def compute_future_value(principal, rate, years):
return principal * (1 + rate/100) ** years
# Usage
lily = Flower(10, "White", "Pleasant") # Usage
rose = Flower(15, "Red", "Fragrant") principal = float(input("Enter the principal amount: "))
hibiscus = Flower(5, "Pink", "Mild") rate = float(input("Enter the rate of interest: "))
years = int(input("Enter the number of years: "))
lily.display() print(f"Future value: {compute_future_value(principal, rate, years)}")
rose.get() Q11. Write a Python program to create all possible permutations from a given
rose.display() collection of distinct numbers.
Q4. Write a Python program to read a file and convert a date of yyyy-mm-dd format from itertools import permutations
to dd-mm-yyyy format.
def convert_date_format(date_str): def generate_permutations(numbers):
yyyy, mm, dd = date_str.split('-') return list(permutations(numbers))
return f"{dd}-{mm}-{yyyy}"
# Usage
# Read from file numbers = [1, 2, 3]
with open("dates.txt", "r") as file: print(generate_permutations(numbers))
for line in file:
date_str = line.strip()
print(convert_date_format(date_str))

You might also like