Advanced Python Cat 2
Advanced Python Cat 2
Introduction
Explanation
1. Functions
Example:
Benefits:
Code reusability
Reduces repetition
Easy debugging
2. Modules
Example: [Link]
import mymodule
print([Link](2,3))
Benefits:
Better organization
Reusability
3. Exception Handling
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
File: [Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
Main Program:
import calculator
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
except ZeroDivisionError:
print("Division by zero not allowed")
except ValueError:
print("Enter valid numbers")
Output
Advantages
1. Structured programming
2. Error-free execution
3. Reusable code
4. Easy maintenance
Conclusion
Answer 2. Compare built-in functions and user-defined functions with appropriate use cases.
Introduction
Functions are blocks of code used to perform specific tasks. In Python, functions are mainly
classified into:
---
1. Built-in Functions
Built-in functions are pre-defined functions available in Python without importing anything.
Examples:
print()
input()
len()
sum()
max()
min()
type()
range()
Example Program
Output
Length = 4
Maximum = 40
Sum = 100
1. Ready to use
3. Optimized performance
5. Easy to use
Use Cases
2. User-defined Functions
User-defined functions are functions written by the programmer using def keyword.
Syntax
def function_name(parameters):
statements
return value
Example Program
def greet(name):
print("Hello", name)
print(add(5, 3))
greet("Lithika")
Output
8
Hello Lithika
1. Customized logic
2. Reusability
3. Better readability
4. Easy debugging
5. Modular programming
Use Cases
Payroll system
Login authentication
Menu-driven applications
---
Comparison Table
---
Combined Example
def square(n):
return n*n
nums = [1,2,3,4]
Length = 4
Square = 25
---
Conclusion
Built-in functions are useful for common tasks and save time, while user-defined functions solve
specific problems based on user needs. Both are essential in Python programming and are
often used together in real-world applications.
---
Answer 3. Examine the working of socket communication between client and server.
Introduction
Socket communication is a method used for data exchange between two systems over a
network. It follows the client-server model, where one program acts as a server and another as
a client.
Sockets are widely used in chat applications, web browsers, online games, and file transfer
systems.
---
What is a Socket?
It uses:
IP Address – Identifies the device
Example:
IP Address : [Link]
Port : 5000
---
Connection-oriented
Connectionless
No guarantee of delivery
---
1. Create socket
2. Bind IP and port
4. Accept connection
5. Receive data
6. Send response
7. Close connection
1. Create socket
2. Connect to server
3. Send message
4. Receive reply
5. Close connection
---
Architecture Diagram
Client ---- Request ----> Server
Client <--- Response ---- Server
---
Python Program
Server Program
import socket
server = [Link]()
[Link](('localhost', 5000))
[Link](1)
print("Server waiting...")
msg = [Link](1024).decode()
print("Client says:", msg)
[Link]("Hello Client".encode())
[Link]()
---
Client Program
import socket
client = [Link]()
[Link](('localhost', 5000))
[Link]("Hello Server".encode())
reply = [Link](1024).decode()
print("Server says:", reply)
[Link]()
---
Output
Server Output
Server waiting...
Connected by ('[Link]', 56000)
Client says: Hello Server
Client Output
---
Function Purpose
---
1. Fast communication
---
Limitations
1. Network dependency
3. Programming complexity
---
Real-Time Applications
Chat applications
ATM networks
Web servers
---
Conclusion
Socket communication enables client and server systems to exchange data efficiently over a
network. Using Python’s socket module, developers can build real-time network applications
such as chat systems, web services, and online platforms.
---
Introduction
A file management application is used to create, read, write, append, rename, and delete files.
Python provides built-in support for file handling using functions like open(), read(), write(), and
modules such as os.
Such applications are useful for managing text files, records, logs, and documents.
---
1. Create a file
4. Append data
5. Rename file
6. Delete file
7. Exit program
---
Function Purpose
---
Python Program
import os
while True:
print("\n--- FILE MANAGEMENT SYSTEM ---")
print("1. Create File")
print("2. Write File")
print("3. Read File")
print("4. Append File")
print("5. Rename File")
print("6. Delete File")
print("7. Exit")
elif choice == 2:
fname = input("Enter file name: ")
data = input("Enter text: ")
f = open(fname, 'w')
[Link](data)
[Link]()
print("Data written successfully")
elif choice == 3:
fname = input("Enter file name: ")
f = open(fname, 'r')
print("File Content:")
print([Link]())
[Link]()
elif choice == 4:
fname = input("Enter file name: ")
data = input("Enter text to append: ")
f = open(fname, 'a')
[Link](data)
[Link]()
print("Data appended")
elif choice == 5:
old = input("Old file name: ")
new = input("New file name: ")
[Link](old, new)
print("File renamed")
elif choice == 6:
fname = input("Enter file name: ")
[Link](fname)
print("File deleted")
elif choice == 7:
print("Exiting...")
break
else:
print("Invalid choice")
---
Sample Output
Enter choice: 1
Enter file name: [Link]
File created successfully
Enter choice: 2
Enter file name: [Link]
Enter text: Hello Python
Data written successfully
Enter choice: 3
File Content:
Hello Python
---
Mode Meaning
r Read
w Write
a Append
x Create new file
rb Read binary
---
Advantages
---
Applications
Notes manager
---
Limitations
---
Conclusion
A file management application in Python simplifies file operations such as create, read, write,
rename, and delete. It is highly useful for storing and maintaining data efficiently in real-world
applications.
---
Introduction
In Python, threading and multiprocessing are techniques used to perform multiple tasks
simultaneously. They improve performance, responsiveness, and resource utilization.
---
1. Threading
A thread is the smallest unit of execution inside a process. Multiple threads share the same
memory space.
Example
import threading
def task():
for i in range(3):
print("Thread Running")
t1 = [Link](target=task)
[Link]()
[Link]()
Features of Threading
Shared memory
Lightweight
Fast communication
Use Cases
Downloading files
Chat applications
GUI applications
Network requests
---
2. Multiprocessing
Multiprocessing creates separate processes, each with its own memory space.
Example
import multiprocessing
def task():
print("Process Running")
p1 = [Link](target=task)
[Link]()
[Link]()
Features of Multiprocessing
Separate memory
True parallelism
Use Cases
Data analysis
Image processing
Scientific computation
---
Comparison Table
---
Threading
import threading
def show():
print("Thread executed")
for i in range(2):
t = [Link](target=show)
[Link]()
Multiprocessing
import multiprocessing
def show():
print("Process executed")
for i in range(2):
p = [Link](target=show)
[Link]()
---
Advantages of Threading
3. Better responsiveness
---
Advantages of Multiprocessing
2. High performance
4. Independent execution
---
Limitations
Threading
Affected by GIL
Shared memory issues
Race conditions
Multiprocessing
Slower startup
Complex communication
---
Real-Time Examples
---
Conclusion
Threading is best for I/O-bound tasks requiring quick response, while multiprocessing is best for
CPU-intensive tasks needing true parallel execution. The correct choice depends on application
requirements.
---
A real-time Python application can combine Regular Expressions (Regex), Threading, and
Subprocess to perform multiple tasks efficiently.
Such integration is useful in monitoring systems, automation tools, validation software, and log
analyzers.
---
Problem Statement
---
Concepts Used
1. Regular Expressions
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
---
2. Threading
---
3. Subprocess
Examples:
date
time
dir
ls
---
Python Program
import re
import threading
import subprocess
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")
# Create threads
t1 = [Link](target=validate_email)
t2 = [Link](target=system_info)
# Start threads
[Link]()
[Link]()
print("Application Finished")
---
Sample Output
Valid Email
Application Finished
---
Explanation
Email Validation
Threading
Subprocess
---
Advantages
5. Better performance
---
Real-Time Applications
---
Limitations
---
Improved Version
Mobile numbers
Password strength
URLs
IP addresses
---
Conclusion
By combining Regular Expressions, Threading, and Subprocess, Python can create powerful
real-time applications that validate input, execute tasks simultaneously, and interact with the
operating system efficiently.
---
Introduction
This architecture is widely used in web applications, banking systems, email services, and
database systems.
---
Basic Structure
Client 1 ----\
Client 2 ----- > Server ---- Database
Client 3 ----/
Examples:
Working Process
Example:
---
Easy control
Easy updates
Better consistency
2. Resource Sharing
Many clients can use same printer, files, database.
3. Security
User login
Access permissions
Data backup
4. Easy Maintenance
5. Scalability
6. Better Performance
---
1. Server Failure
2. High Cost
3. Network Dependency
Requires stable network connection.
4. Traffic Congestion
5. Security Risk
---
Comparison Table
---
Real-Time Examples
Banking System
College ERP
Web Application
Browser = Client
Email System
---
Applications
2. Banking networks
4. Office networks
---
Conclusion
Client-server architecture is a reliable and widely used model for sharing resources and
managing centralized data. It offers security, scalability, and maintenance benefits, but depends
heavily on server availability and network connectivity.
---
Introduction
A record management system is used to store and manage details of students or employees.
Using classes and objects in Python, we can design a structured system that stores data
members and performs operations through methods.
---
Objectives
2. Display records
3. Search records
4. Update records
Class
Object
Constructor
---
class Student:
def display(self):
print("Roll No :", [Link])
print("Name :", [Link])
print("Dept :", [Link])
print("Marks :", [Link])
# Object creation
s1 = Student(101, "Lithika", "CSE", 95)
# Display record
[Link]()
# Update marks
s1.update_marks(98)
---
Output
Roll No : 101
Name : Lithika
Dept : CSE
Marks : 95
Roll No : 101
Name : Lithika
Dept : CSE
Marks : 98
---
class Employee:
def show(self):
print([Link], [Link], [Link])
---
Explanation
Constructor __init__()
Methods Used
Method Purpose
---
3. Reusability
5. Easy maintenance
---
Real-Time Applications
1. Student management system
---
Limitations
---
Conclusion
Using classes and objects, Python can build efficient student or employee record systems. It
improves code organization, reusability, and simplifies data handling in real-world applications.
---
Introduction
Errors and exceptions are problems that occur during the execution of a program.
---
1. Syntax Errors
Example:
print("Hello"
Output:
---
Example:
a = 10
b=0
print(a/b)
Output:
---
3. Logical Errors
Example:
a=5
b = 10
print("Sum =", a - b) # Wrong logic
---
try
except
else
finally
---
Basic Syntax
try:
# risky code
except:
# handling code
---
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a/b)
except ZeroDivisionError:
print("Cannot divide by zero")
---
try:
x = int(input("Enter number: "))
print(10/x)
except ZeroDivisionError:
print("Division by zero")
except ValueError:
print("Invalid input")
---
try:
num = int(input("Enter number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Result =", result)
finally:
print("Execution completed")
---
Output
Enter number: 2
Result = 5.0
Execution completed
---
Exception Description
---
---
Limitations
1. Overuse makes code complex
---
Real-Time Applications
---
Conclusion
Errors are unavoidable in programming, but exception handling helps manage runtime issues
efficiently. By using try-except blocks, Python programs become stable, user-friendly, and
reliable.
---
Introduction
In Python, exception handling is used to manage runtime errors without stopping the program.
The complete structure uses:
---
Structure of try-except-else-finally
try:
# risky statements
except:
# error handling block
else:
# executes if no exception
finally:
# always executes
---
1. try Block
2. except Block
3. else Block
Used for:
Closing files
Releasing resources
Database disconnection
---
Flow Diagram
Start
↓
try block executed
↓
Error?
/ \
Yes No
| |
except else
\ /
finally
↓
End
---
Example Program
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Enter valid numbers")
else:
print("Result =", result)
finally:
print("Program ended")
---
Case 1: No Error
Input
10
2
Output
Result = 5.0
Program ended
Explanation
else runs
finally runs
---
Input
10
0
Output
Explanation
Error in try
else skipped
finally runs
---
Input
ten
2
Output
---
Important Points
Advantages
4. Better debugging
5. Improves reliability
---
Real-Time Uses
1. File opening/closing
2. Database connections
Conclusion
---
Introduction
Files are used to store data permanently. Python provides file handling features to create, read,
write, and modify files using different file modes.
Data processing means reading data from files, performing operations, and storing results.
---
---
Basic Syntax
f = open("[Link]", "r")
---
Mode Meaning
r Read file
w Write file (overwrite)
a Append data
x Create new file
rb Read binary file
wb Write binary file
r+ Read and write
a+ Append and read
---
Explanation of Modes
f = open("[Link]", "r")
print([Link]())
[Link]()
---
f = open("[Link]", "w")
[Link]("Hello Python")
[Link]()
---
f = open("[Link]", "a")
[Link]("\nNew Line")
[Link]()
---
f = open("[Link]", "r+")
print([Link]())
[Link]("Added")
[Link]()
---
---
text = [Link]()
[Link]()
---
f = open("[Link]", "r")
text = [Link]()
[Link]()
f = open("[Link]", "w")
[Link]([Link]())
[Link]()
---
f = open("[Link]", "r")
for line in f:
name, mark = [Link]()
if int(mark) >= 50:
print(name, "Pass")
else:
print(name, "Fail")
[Link]()
---
---
5. Automation friendly
---
Applications
3. Employee payroll
4. Report generation
5. Inventory management
---
Limitations
---
Conclusion
Python file modes help read, write, append, and manage files effectively. Combined with data
processing, Python becomes powerful for record management, report generation, and
real-world business applications.
---
Answer 12. Explain OOP concepts: inheritance, polymorphism, and encapsulation in Python.
Introduction
1. Inheritance
2. Polymorphism
3. Encapsulation
---
1. Inheritance
Definition
Inheritance is the process of creating a new class from an existing class. The new class
acquires the properties and methods of the existing class.
Syntax
class Parent:
pass
class Child(Parent):
pass
Example Program
class Person:
def show(self):
print("I am a Person")
class Student(Person):
def display(self):
print("I am a Student")
s = Student()
[Link]()
[Link]()
Output
I am a Person
I am a Student
Advantages of Inheritance
1. Code reusability
2. Reduces duplication
3. Easy maintenance
---
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
---
2. Polymorphism
Definition
Polymorphism means many forms. The same method name can perform different actions
depending on the object.
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
[Link]()
Output
Dog barks
print(len("Python"))
print(len([1,2,3,4]))
Output
6
4
Advantages of Polymorphism
2. Flexible coding
3. Easy expansion
4. Better readability
---
3. Encapsulation
Definition
Encapsulation means wrapping data and methods together inside a class and restricting direct
access to data.
Example Program
class Bank:
def __init__(self):
self.__balance = 5000
def show(self):
print("Balance =", self.__balance)
b = Bank()
[Link](2000)
[Link]()
Output
Balance = 7000
Explanation
Advantages of Encapsulation
1. Data hiding
2. Better security
3. Controlled access
4. Easy maintenance
---
Comparison Table
---
Real-Time Examples
Inheritance
Polymorphism
---
Conclusion
Inheritance, polymorphism, and encapsulation are core OOP principles in Python. They help
create reusable, secure, and flexible programs, making software development more efficient
and organized.
---
Introduction
Threading is a technique used to run multiple tasks concurrently within a single process. A
thread is the smallest unit of execution in a program.
Using threading, a program can perform several tasks at the same time, improving speed and
responsiveness.
Python provides the threading module for creating and managing threads.
---
What is Concurrency?
Example:
---
What is Threading?
Process
├── Thread 1
├── Thread 2
└── Thread 3
---
---
Syntax
import threading
t = [Link](target=function_name)
[Link]()
---
Example Program
import threading
import time
def task1():
for i in range(3):
print("Downloading File...")
[Link](1)
def task2():
for i in range(3):
print("Playing Music...")
[Link](1)
t1 = [Link](target=task1)
t2 = [Link](target=task2)
[Link]()
[Link]()
[Link]()
[Link]()
---
Output
Downloading File...
Playing Music...
Downloading File...
Playing Music...
Downloading File...
Playing Music...
Both tasks completed
---
Explanation
---
Function Purpose
---
Advantages of Threading
1. Improves responsiveness
---
1. Web Servers
2. Chat Applications
3. Download Managers
4. Games
5. GUI Applications
---
Limitations of Threading
---
Synchronization Example
lock = [Link]()
---
---
Conclusion
Threading is an important technique for concurrent applications. It allows multiple tasks to run
together, improving speed, efficiency, and responsiveness. It is highly useful in real-time and
network-based applications.
---
Introduction
A validation system checks whether user input follows the required format. In Python, Regular
Expressions (Regex) are widely used for validating data such as email IDs, phone numbers,
passwords, dates, and usernames.
---
3. Improve security
---
What is Regex?
Example:
[a-z]
Symbol Meaning
. Any character
^ Start of string
$ End of string
* Zero or more
+ One or more
? Optional
[0-9] Digits
[a-z] Lowercase letters
{n} Exactly n times
---
Function Purpose
---
Program
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")
Output
---
import re
if [Link](r'^[0-9]{10}$', num):
print("Valid Number")
else:
print("Invalid Number")
---
Conditions:
Minimum 8 characters
import re
pattern = r'^(?=.*[A-Z])(?=.*[0-9]).{8,}$'
if [Link](pattern, pwd):
print("Strong Password")
else:
print("Weak Password")
---
1. Login Forms
2. Registration Forms
3. Banking Apps
4. College Portals
5. E-commerce Websites
---
5. Saves time
---
Limitations
---
import re
if [Link](r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
print("Valid Email")
else:
print("Invalid Email")
if [Link](r'^[0-9]{10}$', phone):
print("Valid Phone")
else:
print("Invalid Phone")
---
Conclusion
Regex-based validation systems are powerful tools in Python for checking user input formats.
They are widely used in websites, apps, and software to ensure accurate and secure data entry.
---
Introduction
A Student Management System is used to store, update, search, and display student records.
Using Object-Oriented Programming (OOP) in Python, we can design the system efficiently
using classes and objects.
---
Objectives
4. Update marks
---
Python Program
class Student:
def display(self):
print([Link], [Link], [Link], [Link])
students = []
while True:
print("\n--- STUDENT MANAGEMENT SYSTEM ---")
print("1. Add Student")
print("2. Display Students")
print("3. Search Student")
print("4. Update Marks")
print("5. Delete Student")
print("6. Exit")
elif choice == 2:
for s in students:
[Link]()
elif choice == 3:
r = int(input("Enter Roll No: "))
for s in students:
if [Link] == r:
[Link]()
elif choice == 4:
r = int(input("Enter Roll No: "))
for s in students:
if [Link] == r:
[Link] = int(input("New Marks: "))
print("Updated")
elif choice == 5:
r = int(input("Enter Roll No: "))
for s in students:
if [Link] == r:
[Link](s)
print("Deleted")
elif choice == 6:
break
---
Sample Output
1. Add Student
Roll No: 101
Name: Lithika
Department: CSE
Marks: 95
Student Added
2. Display Students
101 Lithika CSE 95
4. Update Marks
Enter Roll No: 101
New Marks: 98
Updated
---
Explanation
Constructor
__init__()
Methods
Method Purpose
---
1. Organized structure
3. Reusable code
4. Scalable for large systems
5. Better maintenance
---
Real-Time Applications
---
Limitations
Improvements
Can add:
File/database storage
Attendance module
Grade calculation
Login authentication
---
Conclusion
A Student Management System using OOP in Python provides an efficient way to handle
student data. Classes and objects simplify record management and make the system scalable
and maintainable.
---
Introduction
A File Management System is used to create, read, write, update, rename, and delete files.
Python provides simple built-in functions and modules such as open() and os to perform file
operations.
This system is useful for managing documents, records, notes, logs, and reports.
---
Objectives
1. Create file
5. Rename file
6. Delete file
7. Exit
---
Python Functions
Function Purpose
os Module Functions
Function Purpose
[Link]() Rename file
[Link]() Delete file
---
Python Program
import os
while True:
print("\n--- FILE MANAGEMENT SYSTEM ---")
print("1. Create File")
print("2. Write File")
print("3. Read File")
print("4. Append File")
print("5. Rename File")
print("6. Delete File")
print("7. Exit")
if choice == 1:
fname = input("Enter File Name: ")
f = open(fname, "w")
[Link]()
print("File Created")
elif choice == 2:
fname = input("Enter File Name: ")
data = input("Enter Text: ")
f = open(fname, "w")
[Link](data)
[Link]()
print("Data Written")
elif choice == 3:
fname = input("Enter File Name: ")
f = open(fname, "r")
print([Link]())
[Link]()
elif choice == 4:
fname = input("Enter File Name: ")
data = input("Enter Text to Append: ")
f = open(fname, "a")
[Link](data)
[Link]()
print("Data Appended")
elif choice == 5:
old = input("Old File Name: ")
new = input("New File Name: ")
[Link](old, new)
print("File Renamed")
elif choice == 6:
fname = input("Enter File Name: ")
[Link](fname)
print("File Deleted")
elif choice == 7:
print("Thank You")
break
---
Sample Output
1. Create File
Enter File Name: [Link]
File Created
2. Write File
Enter File Name: [Link]
Enter Text: Python Programming
Data Written
3. Read File
Python Programming
---
r Read
w Write
a Append
x Create new file
---
Advantages
---
Real-Time Applications
1. Notes manager
3. Employee reports
4. Log file maintenance
---
Limitations
1. No password protection
---
Improvements
Can add:
Search file
Copy file
Move file
Encrypt files
GUI interface
---
Conclusion
A File Management System in Python helps users manage files efficiently using create, read,
write, append, rename, and delete operations. It is simple, practical, and widely useful in
real-world applications.
---
Introduction
Functions are reusable blocks of code used to perform specific tasks. They help reduce
repetition and improve program organization. In Python, functions are mainly of two types:
1. Built-in Functions
2. User-defined Functions
---
1. Built-in Functions
Definition
Built-in functions are functions already provided by Python. They can be used directly without
writing their definitions.
Examples
print()
input()
len()
sum()
max()
min()
type()
range()
Example Program
Output
Length = 4
Maximum = 40
Sum = 100
Advantages
1. Ready to use
4. Easy to understand
---
2. User-defined Functions
Definition
User-defined functions are functions created by the programmer using the def keyword to
perform custom tasks.
Syntax
def function_name(parameters):
statements
return value
Example Program
def greet(name):
print("Hello", name)
print(add(5, 3))
greet("Lithika")
Output
8
Hello Lithika
Advantages
2. Reusable code
3. Better readability
4. Easy debugging
5. Modular design
---
Comparison Table
---
Combined Example
def square(n):
return n*n
nums = [1,2,3]
print(len(nums)) # built-in
print(square(5)) # user-defined
Output
3
25
---
Real-Time Uses
Built-in Functions
Data counting
Input/output
Math operations
User-defined Functions
Payroll system
Banking operations
Login validation
---
Conclusion
Built-in functions are useful for common ready-made tasks, while user-defined functions solve
custom problems based on user requirements. Together, they make Python programs efficient,
readable, and reusable.
---
Introduction
Online transaction applications such as banking apps, UPI apps, and shopping payment
systems must handle errors properly to ensure safe and smooth transactions.
try
except
else
finally
---
3. Insufficient balance
4. Network failure
6. Server timeout
---
Exception Meaning
---
balance = 5000
try:
amount = int(input("Enter amount to transfer: "))
if amount <= 0:
raise ValueError("Invalid amount")
except ValueError:
print("Please enter valid amount")
except Exception as e:
print("Transaction Failed:", e)
else:
balance = balance - amount
print("Transaction Successful")
print("Remaining Balance =", balance)
finally:
print("Thank you for using our service")
---
---
---
Explanation of Flow
try Block
except Block
else Block
finally Block
Always executes.
---
Banking App
Wrong OTP
Session expired
Balance low
E-commerce
Card declined
Duplicate payment
UPI Apps
Server busy
---
1. Safe transactions
Security Enhancements
Can add:
OTP verification
Transaction logs
Fraud detection
Retry mechanism
---
Conclusion
Error handling is essential in online transaction applications. Using Python exception handling,
developers can manage failures safely, provide clear messages, and ensure secure and reliable
payment processing.
---
Introduction
Polymorphism is one of the major concepts in Object-Oriented Programming (OOP). The word
polymorphism means many forms.
In Python, polymorphism allows the same method name to perform different tasks depending on
the object that calls it.
Method overriding occurs when a child class defines a method with the same name as a
method in the parent class, but gives it a different implementation.
---
3. Improve flexibility
General Syntax
class Parent:
def method(self):
print("Parent Method")
class Child(Parent):
def method(self):
print("Child Method")
---
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
class Cat(Animal):
def sound(self):
print("Cat meows")
class Cow(Animal):
def sound(self):
print("Cow moos")
# Creating objects
a = Animal()
d = Dog()
c = Cat()
w = Cow()
---
Output
---
Explanation
Parent Class
class Animal
sound()
Child Classes
Dog
Cat
Cow
[Link]()
[Link]()
This is called runtime polymorphism, because the method to execute is decided at runtime.
---
Flow of Execution
---
class Payment:
def pay(self):
print("Payment Processing")
class UPI(Payment):
def pay(self):
print("Paid using UPI")
class Card(Payment):
def pay(self):
print("Paid using Card")
class Cash(Payment):
def pay(self):
print("Paid using Cash")
Output
Paid using UPI
Paid using Card
Paid using Cash
---
Real-Time Applications
1. Banking System
2. Vehicle System
3. Employee Management
4. Graphics Software
---
5. Better maintainability
6. Runtime flexibility
---
---
super().sound()
Example:
class Dog(Animal):
def sound(self):
super().sound()
print("Dog barks")
---
Conclusion
Applying polymorphism through method overriding allows child classes to provide their own
implementation of inherited methods. It makes programs dynamic, reusable, and flexible. It is
one of the most powerful OOP features used in real-world Python applications.
Answer 20. Apply file operations using different modes in Python (In Detail)
Introduction
Files are used to store data permanently. In Python, file operations are performed using the
open() function with different file modes.
File modes determine how the file is opened, such as reading, writing, appending, or updating.
Using different modes, we can create, modify, read, and manage files efficiently.
---
3. Update records
4. Generate reports
---
f = open("[Link]", "r")
---
Mode Meaning
r Read only
w Write only (overwrites old data)
a Append data
x Create new file
r+ Read and write
w+ Write and read
a+ Append and read
rb Read binary
wb Write binary
---
Program
f = open("[Link]", "r")
print([Link]())
[Link]()
Output
Hello Python
Welcome
---
2. Write Mode (w)
Program
f = open("[Link]", "w")
[Link]("Python File Handling")
[Link]()
---
Program
f = open("[Link]", "a")
[Link]("\nNew Line Added")
[Link]()
---
Program
f = open("[Link]", "x")
[Link]()
---
Program
f = open("[Link]", "r+")
print([Link]())
[Link]("\nExtra Data")
[Link]()
---
f = open("[Link]", "w+")
[Link]("Fresh Content")
[Link](0)
print([Link]())
[Link]()
---
f = open("[Link]", "a+")
[Link]("\nAppended")
[Link]()
---
# Write Mode
f = open("[Link]", "w")
[Link]("Lithika 95")
[Link]()
# Read Mode
f = open("[Link]", "r")
print([Link]())
[Link]()
# Append Mode
f = open("[Link]", "a")
[Link]("\nRavi 88")
[Link]()
# Read Again
f = open("[Link]", "r")
print([Link]())
[Link]()
---
Output
Lithika 95
Lithika 95
Ravi 88
---
Method Purpose
---
Real-Time Applications
1. Student Records
3. Office Reports
4. Attendance Systems
5. Notes Applications
---
---
Precautions
---
Conclusion
Python file operations using different modes help read, write, append, create, and update files
effectively. These operations are essential for data storage and real-world software applications.
---
Answer 21. Compare method overloading and method overriding in Python (In Detail)
Introduction
Method overloading and method overriding are two important concepts in Object-Oriented
Programming (OOP). Both involve methods with the same name, but they are used differently.
---
1. Method Overloading
Definition
Method overloading means defining multiple methods with the same name but with different
number or type of parameters.
Note in Python
Python does not support true method overloading like Java/C++. It is achieved using:
Default arguments
---
class Math:
m = Math()
[Link](5, 3)
[Link](5, 3, 2)
Output
Sum = 8
Sum = 10
---
class Demo:
d = Demo()
[Link](10,20)
[Link](10,20,30)
---
2. Method Overriding
Definition
Method overriding occurs when a child class provides its own implementation of a method
already defined in parent class.
---
Example Program
class Parent:
def show(self):
print("Parent Method")
class Child(Parent):
def show(self):
print("Child Method")
c = Child()
[Link]()
Output
Child Method
---
Comparison Table
Meaning Same method with different arguments Child redefines parent method
Inheritance Needed No Yes
Class InvolvedSame class Parent and child class
Parameters Different Usually same
Purpose Convenience Specialized behavior
Binding Compile-time style concept Runtime polymorphism
---
Detailed Explanation
Overloading Example
add(2,3)
add(2,3,4)
Overriding Example
[Link]()
[Link]()
---
Real-Time Applications
Method Overloading
Method Overriding
1. Payment methods (Cash/Card/UPI)
---
Advantages
Overloading
2. Cleaner code
3. Easy readability
Overriding
1. Dynamic behavior
3. Better extensibility
---
Important Note in Python
---
Conclusion
Method overloading provides multiple ways to use the same method name with different
parameters, while method overriding allows child classes to modify parent methods. Both
concepts improve flexibility, code reuse, and maintainability in Python OOP.
---
Answer 22. Compare single inheritance and multiple inheritance in Python (In Detail)
Introduction
1. Single Inheritance
2. Multiple Inheritance
---
What is Inheritance?
Inheritance allows a new class (child class) to use existing features of another class (parent
class).
Syntax
class Parent:
pass
class Child(Parent):
pass
---
1. Single Inheritance
Definition
Single inheritance means a child class inherits from one parent class.
Structure
Parent → Child
---
Example Program
class Person:
def show(self):
print("I am a Person")
class Student(Person):
def display(self):
print("I am a Student")
s = Student()
[Link]()
[Link]()
Output
I am a Person
I am a Student
---
Explanation
---
1. Simple structure
2. Easy to understand
3. Code reusability
4. Easy maintenance
---
2. Multiple Inheritance
Definition
Multiple inheritance means one child class inherits from more than one parent class.
Structure
Parent1 + Parent2 → Child
---
Example Program
class Father:
def money(self):
print("Father has money")
class Mother:
def care(self):
print("Mother gives care")
def skill(self):
print("Child has skills")
c = Child()
[Link]()
[Link]()
[Link]()
Output
---
Explanation
Comparison Table
---
Real-Time Applications
Single Inheritance
1. Person → Employee
2. Vehicle → Car
3. Animal → Dog
Multiple Inheritance
If two parent classes have same method name, Python uses MRO (Method Resolution Order).
Example
class A:
def show(self):
print("A")
class B:
def show(self):
print("B")
c = C()
[Link]()
Output
---
Limitations
Single Inheritance
Multiple Inheritance
Complex design
Ambiguity possible
Harder debugging
---
Conclusion
Single inheritance is simple and suitable when only one parent class is needed. Multiple
inheritance allows a child class to combine features from multiple parent classes but increases
complexity. Python supports both effectively.
---
Answer 23. Explain the effectiveness of regular expressions in real-world validation systems (In
Detail)
Introduction
Regular Expressions, commonly called Regex, are sequences of characters used to define
search patterns. They are highly effective in validating user inputs in real-world software
systems.
Regex is widely used in websites, mobile apps, databases, and enterprise systems to check
whether entered data follows the required format.
Python provides the re module to work with regular expressions.
---
What is Validation?
1. Correct format
2. Complete
3. Secure
Example:
Strong password
---
5. Increase security
---
Symbol Meaning
^ Start of string
$ End of string
. Any character
* Zero or more
+ One or more
? Optional
[0-9] Digits
[a-z] Lowercase letters
{n} Exactly n times
---
1. Email Validation
Pattern
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Example Program
import re
email = "user@[Link]"
if [Link](pattern, email):
print("Valid Email")
---
^[0-9]{10}$
Examples:
9876543210 → Valid
12345 → Invalid
---
Checks:
Minimum 8 characters
One digit
^(?=.*[A-Z])(?=.*[0-9]).{8,}$
---
---
5. Username Validation
^[a-zA-Z0-9_]{5,15}$
---
import re
if [Link](r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
print("Valid Email")
else:
print("Invalid Email")
---
Banking Systems
E-commerce
Phone number
Address ZIP code
Educational Institutions
Register number
Email IDs
Password creation
Healthcare Systems
Patient ID
Contact number
Date format
IT Companies
Employee ID
Login credentials
IP address validation
---
1. Fast execution
2. Accurate checking
5. Easy automation
6. Improves security
---
Limitations
---
---
Conclusion
Regular expressions are highly effective in real-world validation systems because they quickly
and accurately verify input formats. They improve data quality, security, and user experience,
making them essential in modern software development.
---
Answer 24. Develop a multithreaded application for concurrent tasks (In Detail)
Introduction
A multithreaded application uses multiple threads within a single process to perform several
tasks concurrently. A thread is the smallest unit of execution in a program.
---
Concurrent execution means multiple tasks are handled during overlapping time periods.
Examples:
---
---
Working of Multithreading
Main Program
├── Thread 1 → Task A
├── Thread 2 → Task B
└── Thread 3 → Task C
---
Python Syntax
import threading
t = [Link](target=function_name)
[Link]()
---
3. Notification display
import threading
import time
def download():
for i in range(3):
print("Downloading File...")
[Link](1)
def music():
for i in range(3):
print("Playing Music...")
[Link](1)
def notify():
for i in range(3):
print("Showing Notification...")
[Link](1)
# Creating threads
t1 = [Link](target=download)
t2 = [Link](target=music)
t3 = [Link](target=notify)
# Starting threads
[Link]()
[Link]()
[Link]()
Sample Output
Downloading File...
Playing Music...
Showing Notification...
Downloading File...
Playing Music...
Showing Notification...
Downloading File...
Playing Music...
Showing Notification...
All Tasks Completed
---
Explanation
Thread 1
Thread 2
Thread 3
---
Important Methods
Method Purpose
---
Real-Time Applications
1. Web Servers
2. Chat Applications
3. Download Managers
4. Games
5. Banking Apps
---
Advantages of Multithreading
2. Responsive applications
---
Limitations
---
Synchronization Example
lock = [Link]()
---
Conclusion
---
Answer 25. Compare map(), filter(), and reduce() in Python (In Detail)
Introduction
map(), filter(), and reduce() are higher-order functions in Python used for functional
programming. They process collections such as lists and tuples efficiently.
They are commonly used to transform data, select data, and combine data.
---
1. map()
Definition
map() applies a given function to every element in an iterable and returns a map object.
Syntax
map(function, iterable)
Example Program
nums = [1, 2, 3, 4]
print(result)
Output
[1, 4, 9, 16]
Use Cases
1. Square numbers
3. Type conversion
---
2. filter()
Definition
Syntax
filter(function, iterable)
Example Program
nums = [1,2,3,4,5,6]
Output
[2, 4, 6]
Use Cases
1. Even numbers
2. Valid records
---
3. reduce()
Definition
reduce() repeatedly applies a function to elements and reduces them to a single value.
Syntax
reduce(function, iterable)
Example Program
nums = [1,2,3,4]
print(result)
Output
10
Use Cases
1. Sum of numbers
2. Product of numbers
3. Maximum value
---
Comparison Table
---
Combined Example
nums = [1,2,3,4,5]
# map
a = list(map(lambda x: x*2, nums))
# filter
b = list(filter(lambda x: x%2==0, nums))
# reduce
c = reduce(lambda x,y: x+y, nums)
print(a)
print(b)
print(c)
Output
[2, 4, 6, 8, 10]
[2, 4]
15
---
Advantages
map()
1. Fast transformation
2. Cleaner code
filter()
2. Reduces loops
reduce()
2. Efficient aggregation
---
Real-Time Applications
map()
filter()
reduce()
Total marks
---
# Loop
sum = 0
for i in nums:
sum += i
---
Conclusion
map(), filter(), and reduce() are powerful Python functions for processing collections. map()
transforms data, filter() selects data, and reduce() combines data into one result. They make
programs shorter, cleaner, and efficient.
---
Answer 26. Compare modular programming and monolithic programming (In Detail)
Introduction
Programming approaches are used to organize software structure and development. Two
common approaches are:
1. Modular Programming
2. Monolithic Programming
These approaches differ in how the program is designed, developed, maintained, and executed.
---
1. Modular Programming
Definition
Modular programming is a method where a large program is divided into smaller independent
units called modules.
Examples of modules:
Login module
Payment module
Report module
Database module
---
Structure
Main Program
├── Module 1
├── Module 2
├── Module 3
---
Example in Python
# [Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
Main program:
import mathmodule
print([Link](5,3))
---
1. Easy to understand
2. Reusable code
3. Easy debugging
5. Better maintenance
6. Scalable
---
Real-Time Uses
Banking software
ERP systems
E-commerce websites
---
2. Monolithic Programming
Definition
Monolithic programming means the entire program is written as one large single block or file.
---
Structure
Single Large Program File
├── Login
├── Payment
├── Reports
└── Database Logic
---
Example
def login():
pass
def payment():
pass
def report():
pass
---
---
1. Difficult to maintain
2. Hard debugging in large systems
4. Teamwork difficult
---
Comparison Table
---
Detailed Example
Modular Approach
Admission module
Attendance module
Marks module
Report module
Monolithic Approach
---
Real-Time Comparison
Banking Application
Modular:
Login service
Transactions
Notifications
Reports
Monolithic:
---
1. Faster updates
2. Easy testing
---
---
Conclusion
Modular programming divides software into manageable independent modules, making it ideal
for large and modern applications. Monolithic programming keeps everything in one unit,
suitable only for small and simple programs. Therefore, modular programming is more effective
for scalable and maintainable systems.
---