Unit-4 Web and Internet Technology
Unit-4 Web and Internet Technology
Examples of ADTs:
● Stack
● Queue
● Linked List
● Tree
These structures focus on what operations are available (e.g., push, pop), not how they are
implemented internally.
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
Here:
4. What is a Class?
A class is a blueprint for creating objects. It defines the structure (attributes) and behavior
(methods) of its objects.
Syntax:
class ClassName:
def __init__(self, parameters):
self.attribute = value
def method(self):
# behavior
5. What is an Object?
An object is an instance of a class.
Example:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, I am {self.name}")
p1 = Person("Vishal")
p1.greet() # Output: Hello, I am Vishal
Summary
● ADTs define how data can be used, not how it is implemented.
● Objects are instances of classes used to interact with real-world entities in code.
1. What is Inheritance?
Inheritance is a feature of Object-Oriented Programming (OOP) that allows a class to inherit
properties and behaviors (methods and attributes) from another class.
● The class that is inherited from is called the Parent (or Base) class.
● The class that inherits is called the Child (or Derived) class.
3. Basic Syntax
class Parent:
def speak(self):
print("I am the parent")
class Child(Parent):
pass
obj = Child()
obj.speak() # Output: I am the parent
4. Method Overriding
The child class can override the parent’s method by defining it again.
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
obj = Child()
obj.greet() # Output: Hello from Child
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def show(self):
super().show()
print("Child class")
obj = Child()
obj.show()
Output:
Parent class
Child class
Type Description
Multiple Inheritance One child inherits from more than one parent
class A:
def methodA(self):
print("Method A")
class B:
def methodB(self):
print("Method B")
obj = C()
obj.methodA()
obj.methodB()
Summary
● Inheritance allows code reuse and logical structure.
● Python supports multiple types of inheritance, making it flexible for OOP design.
1. What is Encapsulation?
Encapsulation is an Object-Oriented Programming (OOP) concept that means bundling data
(variables) and methods (functions) into a single unit — the class.
It helps protect an object’s internal state and only allows controlled access through methods.
Benefits of Encapsulation:
2. Information Hiding
Information hiding means restricting access to certain parts of an object’s data, exposing only
what is necessary. This is done using access modifiers.
Example:
class Person:
def __init__(self, name, age):
self.name = name # Public
self._age = age # Protected
self.__salary = 50000 # Private
def show_info(self):
print(f"Name: {self.name}, Age: {self._age}")
p = Person("Ravi", 30)
print(p.name) # Allowed
print(p._age) # Allowed (but discouraged)
# print(p.__salary) # Error (private)
class Employee:
def __init__(self):
self.__salary = 0
def get_salary(self):
return self.__salary
emp = Employee()
emp.set_salary(60000)
print(emp.get_salary()) # Output: 60000
Summary
● Encapsulation groups data and methods into one unit (class).
Python provides built-in functions to work with files using the open() function.
Mode Description
3. Opening a File
file = open("example.txt", "r") # Open for reading
file.close()
5. Writing to a File
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
Summary
● Use the open() function with correct mode ('r', 'w', 'a', etc.).
● Always close files after use or use with open(...) for safer handling.
1. What is an Exception?
An exception is an error that occurs during the execution of a program, which interrupts the
normal flow of instructions.
Examples:
● Dividing by zero
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
try:
x=5
y=2
result = x / y
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Division successful:", result)
try:
f = open("test.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("Execution completed.")
age = 15
if age < 18:
raise ValueError("Age must be at least 18")
Summary
● Use try and except to handle exceptions.
1. Introduction
MySQLdb is a Python library used to interact with MySQL databases. It allows you to connect
to a MySQL server, create tables, insert, delete, and retrieve data using Python.
db = MySQLdb.connect(
host="localhost",
user="root",
passwd="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
if result:
print("Table exists.")
else:
print("Table does not exist.")
4. Creating a Table
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT
)
""")
5. Inserting Data
cursor.execute("INSERT INTO students (name, age) VALUES
(%s, %s)", ("Ravi", 20))
db.commit()
6. Deleting Data
cursor.execute("DELETE FROM students WHERE name = %s",
("Ravi",))
db.commit()
7. Fetching Data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
import re
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y)
plt.title("Sample Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Summary
● MySQLdb is used to connect Python with MySQL
databases.
import MySQLdb
2. Table Creation
If the table does not exist, you can create it using SQL:
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
)
""")
print("Table created successfully.")
db.close()
Summary
● Use SHOW TABLES to check for table existence.
Functi Description
on
3. Common Patterns
Patte Description
rn
\d Digit (0–9)
\w Word character (a-z,
A-Z, 0-9)
\s Whitespace
^ Start of string
$ End of string
1. Introduction to Plotting
Plotting helps you visualize data using graphs like line plots, bar
charts, histograms, etc.
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
3. Bar Chart Example
names = ['A', 'B', 'C']
scores = [80, 70, 90]
plt.bar(names, scores)
plt.title("Scores")
plt.ylabel("Marks")
plt.show()
4. Histogram Example
data = [20, 20, 30, 40, 50, 50, 50, 60, 70]
plt.hist(data, bins=5)
plt.title("Distribution")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.show()