PYTHON NOTES
1)Explain with example class and object.
→In Python, a class is a blueprint or template used to create objects. It defines properties
(variables) and behaviors (methods) that the objects created from the class will have. A class
groups related data and functions together, making programs easier to understand and
maintain.
An object is an instance of a class. It is a real-world entity created using the class blueprint.
When an object is created, it gets its own copy of the class variables, and it can access the class
methods. An object allows us to use the features defined in the class. Classes and objects
support the principles of object-oriented programming such as encapsulation, abstraction,
inheritance, and polymorphism.
•Example: Class and Object in Python
2) Define exceptions. Explain Python exceptions handling in detail with suitable example.
→An exception in Python is an error that occurs during the execution of a program. When an
exception occurs, the normal flow of the program is disturbed, and the program stops unless
the error is handled. Exceptions usually occur due to situations like dividing by zero, accessing
invalid indexes, incorrect input, file not found, etc.
Examples of exceptions: ZeroDivisionError, ValueError, IndexError, FileNotFoundError,
• Exception Handling in Python: -
1. try Block: - The code that might cause an exception is written inside the try block.
If no error occurs, the except block is skipped.
example: - try:
risky_code
2. except Block: - The except block handles the exception.
When an error occurs in the try block, Python jumps to the appropriate except block.
example: - except ExceptionType:
handle_error
3. else Block: - The else block executes only when no exception occurs in the try block.
It is useful for code that should run only if everything is successful.
example: - else:
code_runs_if_no_error
4. finally Block: - The finally block runs whether an exception occurs or not.
It is used for cleanup work like closing files, releasing resources, disconnecting databases.
example: - finally:
code_that_always_runs
5. raise Keyword: - The raise keyword is used to manually throw an exception based on a
condition.
example: - raise ValueError("Invalid Input")
3)List Functions and Methods in Python (With Examples)
→In Python, a list is a versatile, ordered, and mutable collection used to store multiple items
in a single variable. Lists can hold mixed data types such as integers, strings, floats, and even
other lists. Because of their flexibility, lists are one of the most widely used data structures in
Python.
• List Functions
1. len(list): - Returns the number of elements in a list.
example: - numbers = [10, 20, 30]
print(len(numbers)) # Output: 3
2. max(list): - Returns the largest element.
example: - numbers = [10, 20, 30]
print(max(numbers)) # Output: 30
3. min(list): - Returns the smallest element.
example: - numbers = [10, 20, 30]
print(min(numbers)) # Output: 10
4. sum(list): - Returns the total of all numeric elements.
example: - numbers = [10, 20, 30]
print(sum(numbers)) # Output: 60
• List Methods
1. append(value): - Adds an element at the end of the list.
example: - [Link](40)
2. insert (index, value): - Inserts a value at a specific index.
example: - [Link](1, 15)
3. extend([list]): - Adds multiple elements to the list.
example: - [Link]([50, 60])
4. remove(value): - Removes the first occurrence of a value.
example: - [Link](20)
5. reverse (): - Reverses the list order.
example: - [Link]()
4) Explain tuples in Python. Write Python code to add two tuples.
→ A tuple in Python is an ordered and immutable collection of elements. Like lists, tuples can
store multiple items of different data types such as integers, strings, floats, or even nested
tuples. Tuples are written using parentheses ()` and elements are separated by commas. Since
tuples are immutable, their values cannot be changed, updated, or deleted after creation. This
immutability makes tuples faster, memory-efficient, and suitable for storing fixed data such as
days of the week, coordinates, and database records.
• Example of Tuple: - t1 = (10, 20, 30)
print(t1[1]) # Output: 20
Since tuples do not allow modification, we cannot add elements directly inside them. However,
tuple addition means concatenation, where two tuples are joined together using the +
operator.
• Example Code to Add Two Tuples: -
tuple1 = (10, 20, 30)
tuple2 = (40, 50, 60)
result = tuple1 + tuple2
print(result)
Output: - (10, 20, 30, 40, 50, 60)
5) Write the Applications of Python.
→Python is a powerful, high-level, and versatile programming language used in a wide range of
fields. Its simple syntax and large number of libraries make it suitable for beginners as well as
professionals. Python is platform-independent and supports object-oriented, procedural, and
functional programming.
1. Web Development: - Using frameworks like Django, Flask, and FastAPI, Python is used to
build dynamic websites and backend servers.
2. Artificial Intelligence: - Python powers AI applications such as speech recognition, face
detection, and natural language processing.
3. Automation & Scripting: - Python is widely used to automate tasks like file handling, testing,
server management, and data entry.
4. Game Development: - Games are built using libraries like Pygame, Panda3D, and other
engines.
5. Mobile & Desktop Applications: - GUI applications can be created using Tkinter, Kivy, and
PyQt.
6. Cybersecurity: - Python is used for penetration testing, malware analysis, and security
automation.
7. Data Science & Machine Learning: - Python is the #1 language for data science and ML.
Libraries
6) What is module in Python? How to create a module?
→ A module in Python is a file that contains Python code such as variables, functions, classes,
or executable statements. The main purpose of a module is to organize large programs into
smaller, manageable parts. Modules help improve readability, reusability, and maintainability of
code. Instead of writing long programs in a single file, related functions and logic can be
grouped into modules. Python also provides many built-in modules like math, random, os, and
datetime, which make programming easier by providing prewritten functionalities.
• How to Create a Module in Python
Step 1: Create a Python file
»Example: Create a file named [Link]
# [Link]
def add (a, b):
return a + b
def greet(name):
return "Hello, " + name
»Step 2: Import the module in another Python program
import mymodule
print ([Link] (10, 20))
print ([Link]("Rahul"))
»Output: - 30
Hello, Rahul
7)Write a program to print the following pattern using loop.
→This can be printed using nested loops in Python.
The outer loop prints each row, and the inner loop prints numbers in each row.
• Python Program: -
for i in range(1, 6): # Outer loop for rows
for j in range(1, i + 1): # Inner loop for printing numbers
print(j, end=" ")
print() # Move to next line after each row
»Output
1
12
123
1234
1234
8) Define Set. Explain any four set operations.
→ A set in Python is an unordered and mutable collection of unique elements. Sets are written
using curly braces {} and do not allow duplicate values. Because sets are unordered, the
elements do not maintain any specific position or index. Sets are mainly used to perform
mathematical set operations like union, intersection, difference, and symmetric difference.
They are also efficient for tasks like removing duplicates from a list or checking membership
due to their fast-processing speed.
•Four Important Set Operations
1. Union (set1 | set2 or [Link](set2)): - Combines all elements from both sets
without duplicates.
example: - A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # {1, 2, 3, 4, 5}
2. Intersection (set1 & set2 or [Link](set2)): - Returns only the common
elements from both sets.
example: - print(A & B) # {3}
3. Difference ( set1 - set2 or [Link](set2) ): - Returns elements that are in the first
set but NOT in the second set.
example: - print(A - B) # {1, 2}
4. Symmetric Difference ( set1 ^ set2): - Returns elements that are in either of the sets
but NOT in both.
example: - print(A ^ B) # {1, 2, 4, 5}
9)Program to Print Sum of All Elements of a List
→
Output: - Sum of all elements: 150
10) Program to Print Multiplication of All Elements of a List
→
Output: - Multiplication of all elements: 120
11) What is Deep Copy and Shallow Copy in Python?
→ Shallow Copy: -
A shallow copy creates a new object but does not create copies of nested objects inside it.
Instead, it only copies reference to those nested objects. So, changes made to nested elements
will reflect in both the original and copied object.
Shallow copy is created using:
• copy. Copy()
• Slicing (list[:])
• list() constructor
• Deep Copy: -
A deep copy creates a completely independent copy of the object along with all nested objects.
Changes in the deep copy do NOT affect the original object.
Deep copy is created using:
• [Link]()
Conclusion:
• Shallow copy → copies only outer object (shares nested objects)
• Deep copy → copies everything including nested objects (fully independent)
12) Explain Python loops with example.
→ In Python, loops are used to execute a block of code repeatedly until a certain condition is
met. Loops help reduce repetition, make programs shorter, and improve efficiency. Python
mainly provides two types of loops: for loop and while loop.
• for Loop: - The for loop is used when we know the number of iterations in advance. It is
commonly used to iterate over sequences such as lists, strings, tuples, and ranges. It
automatically picks each element and executes the code block for every element.
»Example of for Loop: - for i in range(1, 6):
print("Number:", i)
»Output: -
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
• while Loop: - The while loop is used when the number of iterations is not fixed. It continues
to run as long as the condition is True. The loop stops when the condition becomes False.
»Example of while Loop: - count = 1
while count <= 5:
print("Count:", count)
count += 1
»Output: -
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
13) Explain pass statement in Python.
→The pass statement is a placeholder used when a statement is required syntactically but no
action is needed. It allows the program to run without errors.
Example: - for i in range(5):
pass
) Write a Python program to print length of a string.
→ s = "Hello World"
print("Length of string =", len(s))
14) Define function, user define function and built in function with example.
→A function in Python is a block of reusable code that performs a specific task.
It helps in reducing repetition, improving code organization, and increasing readability.
Functions can take input (parameters), perform operations, and return output.
1. User-Defined Function: - A user-defined function is a function created by the programmer
based on the requirements of the program. It allows customization and reuse of logic.
• Features of User-Defined Functions: -
➢ Created using def keyword
➢ Designed by users
➢ Can accept parameters
➢ May or may not return a value
➢ Used for modular and reusable code
• Example: User-Defined Function
Explanation: -
• The function add() is defined by the user.
• It takes two inputs a and b.
• It returns their sum.
[Link]-in Function: - A built-in function is a function that is already available in Python without
needing to define it. Python provides many built-in functions to perform common tasks.
• Examples include: print(), len(), sum(), input(), type(), max(), min()
These functions are easy to use and improve development speed.
• Example: Built-in Function
Explanation:
• len() calculates the number of elements.
• sum() adds the list elements.
• Both are built-in and require no definition.
15) What is Inheritance and How is it Used?
→Inheritance is an important concept in Object-Oriented Programming where one class (child
class) can acquire the properties and methods of another class (parent class). It helps in code
reusability and reduces redundancy.
Definition: -
Inheritance allows creating a new class from an existing class.
The existing class is called parent (base) class, and the new class is called child (derived) class.
Why Inheritance is Used?
• To reuse existing code
• To extend or modify parent class functionality
• To create hierarchical relationships
• To reduce code duplication
Types of Inheritance in Python
[Link] Inheritance – One parent, one child
[Link] Inheritance – Parent → Child → Grandchild
3. Multiple Inheritance – Child inherits from multiple parents
4. Hierarchical Inheritance – One parent, many children
• Example of Inheritance
Explanation: -
• Dog inherits sound() from Animal.
• This shows reuse of existing methods.
16) Explain pop() and popitem() Methods in Python.
→
• pop() Method: -
The pop() method is used to remove and return an element from a collection.
It allows safe deletion because the removed value is returned, which can be used further in the
program.
(A)pop() in Lists
• Removes element at a specified index.
• If index is not given, removes the last element.
• Returns the removed element.
Example
• popitem() Method
The popitem() method removes the last inserted key–value pair and returns it as a tuple.
It follows a LIFO (Last In, First Out) order, making it useful for stack-like operations on key–value
pairs.
• Example
• pop() → removes a specific element (by index in list, by key in dictionary).
• popitem() → removes the last inserted pair (only in dictionary).
17) Explain inheritance in Python.
→Inheritance allows one class (child) to acquire properties and methods of another class
(parent). It promotes code reuse and supports OOP.
Example:-
18) Explain the steps for database connectivity in Python with suitable example.
→Database connectivity in Python allows a program to store, retrieve, update, and delete data
from a database such as MySQL, SQLite, PostgreSQL, etc. Python provides database drivers and
modules (like [Link] or sqlite3) to establish a connection and execute SQL queries.
1. Import the Database Module: - The first step is to import the required database connector
library.
E.g. import sqlite3 # or: import [Link]
2. Establish the Connection: - Create a connection between Python and the database.
E.g. con = [Link]("[Link]")
3. Create a Cursor Object: - The cursor is used to execute SQL commands.
E.g. cur = [Link]()
4. Execute SQL Queries: - SQL commands like CREATE, INSERT, UPDATE, DELETE, SELECT is
executed through the cursor.
E.g. [Link]("CREATE TABLE IF NOT EXISTS student(id INTEGER, name TEXT)")
[Link]("INSERT INTO student VALUES (1, 'Rahul')")
5. Commit the Changes: - Save the changes permanently in the database.
E.g. [Link]()
6. Fetch the Data (for SELECT queries): - Used to retrieve result records.
E.g. [Link]("SELECT * FROM student")
data = [Link]()
print(data)
7. Close the Connection: - Close the database connection after work is completed.
E.g. [Link]()
• Complete Example Program
19) Define dictionary with example differentiate between list and dictionary.
→ Definition of Dictionary: - A dictionary in Python is an unordered, mutable collection of data
stored in key–value pairs. Each key in a dictionary is unique, and it is used to access its
corresponding value. Dictionaries are useful for fast lookups and storing structured data.
• Example of Dictionary: - student = {
"name": "Rahul",
"age": 20,
"marks": 85 }
Difference Between List and Dictionary
List Dictionary
➢ List is an ordered collection of items. ➢ Dictionary is an unordered collection of
key–value pairs.
➢ Elements are accessed using index ➢ Elements are accessed using keys.
numbers.
➢ Stored within square brackets []. ➢ Stored within curly braces {}.
➢ Allows duplicate values. ➢ Keys must be unique (values may
repeat).
➢ Used when data is simple and sequential. ➢ Used when data needs a label (key) for
fast access.
20) Explain set intersection operation in Python.
→ Intersection returns only the common elements between two sets.
21)Explain is and is not operator in Python.
→These are identity operators.
• is → checks if two variables refer to the same object.
• is not → checks if they refer to different objects.
Example: a is b
22) Why Python is called a high-level programming language?
→Python is called high-level because it is easy to read, closer to human language, and hides
low-level machine details like memory handling. It allows programmers to write programs
quickly and easily.
23) How to give comments in Python?
→Comments explain code and are ignored by Python.
• Single-line comment: starts with #
• multi-line comment: uses triple quotes
Example: # This is a comment
24) Describe dictionary in Python.
→A dictionary is an unordered, mutable collection of key–value pairs. Each key is unique, and
values can be updated.
• Example: d = {"name": "Rahul", "age": 20}
25) Difference Between Mutable and Immutable Objects in Python
→
Mutable Objects Immutable Objects
1)Can be changed after creation 1)Cannot be changed after creation
2) Changes happen in the same 2) Any change creates a new object in
memory location memory
3) Elements can be added, 3) Values cannot be updated; new object
removed, or updated is created
4) E.g. list, dictionary, set 4) E.g. string, tuple, int, float