Advanced Python Programming Notes
Advanced Python Programming Notes
s1 = Student("Rahul")
s2 = CSEStudent("Meghana")
print([Link]())
print([Link]())
In above program the Student class bundles data (name) and behavior (details()), which
shows encapsulation. The details() method provides a simple way for users to get information
without exposing internal implementation, demonstrating abstraction. The CSEStudent class
inherits from the Student class, meaning all the features of Student automatically come into
CSEStudent, which is inheritance. Inside CSEStudent, the details() method is redefined, so
calling it gives a different output compared to the parent class. This is polymorphism, where the
same method name behaves differently based on the object.
CLASSES
A class in Python is a blueprint or template used to create objects. Just like a civil
engineer uses a blueprint to build many identical classrooms in MRDU, a class defines how
objects will look and behave, but the actual objects are created only when we use the class.
A class contains two main things: attributes (data) and methods (functions inside the
class). Once a class is defined, we can create multiple objects using the class name. Each object
created from the class will have its own properties and behaviors. Classes help in organizing
programs and writing reusable, clear, and structured code.
Syntax: class ClassName:
Example:
class Laptop:
brand = "HP" # Attribute inside class
def show(self): # Method inside class
return "Laptop used in MRDU Labs"
lap = Laptop() # Creating an object
print([Link])
print([Link]())
In above example the class Laptop is created with one attribute brand and one method
show(). The attribute brand stores the name of the company, and the method show() returns a
simple message. When we create the object lap using Laptop(), it gets access to both the attribute
and method. The line print([Link]) prints the value “HP”, and print([Link]()) calls the
method, which prints the message returned by it. This example shows how a class acts as a
blueprint and how an object uses the data and functions defined inside the class.
CLASS ATTRIBUTES
A class attribute is a variable that belongs to the class itself, not to individual objects. It
is shared by all objects created from the class. This is similar to how all students of MRDU
share the same college name, even though each student has different personal details. A class
attribute is written inside the class but outside any method. Because it is shared, changing it from
the class will affect every object, but changing it from an object will only create a separate copy
for that object.
Syntax
class ClassName:
attribute_name = value
In the above example the attribute college_name is defined at the class level, so both s1
and s2 objects print the same value “MRDU”. This proves that class attributes are shared across
all instances of the class.
INSTANCES (OBJECTS)
An instance (or object) is a real, usable version of the class. A class is only a blueprint,
but when we create an object using ClassName(), we get an instance that can store data and
perform actions. Just like the timetable format is common for all students but each student has
their own actual timetable, objects are individual realizations of a class. Every object is stored
separately in memory, and we can create any number of objects from a single class.
Syntax
object_name = ClassName()
Example – Instance Creation
class Bike:
def ride(self):
return "Bike is moving"
b1 = Bike() # Instance 1
print([Link]())
In the above example the class Bike contains a method ride(). When we create the object
b1 using Bike(), it becomes an instance of that class. Calling [Link]() executes the method
defined inside the class. This shows how objects bring the class to life.
INSTANCE ATTRIBUTES
Instance attributes are variables that belong to each object individually. They are created
inside the init() constructor using self. This allows each object to store different values. For
example, every student in MREC/MRDU has a different name, roll number, and branch—these
vary from student to student. Instance attributes make every object unique and independent from
others.
Syntax
class ClassName:
def __init__(self, value):
[Link] = value
Here, the method greet() is bound to the object d. When we call [Link](), Python
internally converts it to [Link](d), passing the object automatically. This demonstrates how
binding ensures the method works with the correct instance.
The Car class contains an Engine object. Car itself does not start, it uses the engine’s
start() method. This shows the “has-a” relationship and demonstrates composition. Composition
allows us to delegate responsibilities to component classes.
In above example Professor is a child class of Teacher. Even though Professor does not
define the teach() method, it can still access it because of inheritance. This demonstrates sub-
classing and derivation.
INHERITANCE
Inheritance is a fundamental OOP concept where one class (child) acquires the attributes
and methods of another class (parent). Python supports single, multiple, multilevel, and
hierarchical inheritance. Inheritance allows reuse of code, hierarchical organization of classes,
and extensibility. For example, all engineering students in MREC/MRDU inherit basic student
attributes like name, roll number, and branch, but can have specific features depending on their
department.
Example – Single Inheritance
class Parent:
def show(self):
return "This is Parent class"
class Child(Parent):
def info(self):
return "This is Child class"
c = Child()
print([Link]())
print([Link]())
Child inherits the show() method from Parent. It also has its own method info(). When
we call [Link](), it executes the parent method. [Link]() executes the child method. This
demonstrates inheritance: child classes reuse parent features and can also extend or override
them.
Here, type(s) shows that s is a Student object. isinstance() confirms the relationship. hasattr()
checks whether the attribute exists. getattr() fetches the value of an attribute, and setattr()
dynamically adds a new attribute to the object. These built-in functions are useful for dynamic
programming and inspecting objects during runtime.
TYPES vs CLASSES / INSTANCE
In Python, everything has a type. Built-in types include int, str, list, etc., while user-
defined types are classes created by programmers. A class is a template to create objects, and an
instance is an object created from that class. The type() function tells us the category of the
object, while the __class__ attribute tells us which class created the instance. Understanding this
distinction is important for managing objects effectively in Python programs.
Here x is a built-in integer, so type(x) returns <class 'int'>. The object c is an instance of the
user-defined class Car. Using c.__class__ confirms that c was created from the Car class. This
illustrates the difference between types, classes, and instances.
The __str__() method defines the string representation of the object. Instead of printing
the memory address, Python prints “Student Meghana, Roll: 102”. Special methods let us
customize object behavior naturally and integrate objects with Python’s built-in operations.
PRIVACY (ENCAPSULATION)
Privacy in Python is implemented using public, protected, and private attributes. Public
attributes can be accessed anywhere. Protected attributes, indicated with a single underscore
_var, are meant to be used within the class and its subclasses by convention. Private attributes,
indicated with double underscore __var, use name mangling to prevent direct access from outside
the class. This mechanism ensures controlled access and protects sensitive data, such as student
grades or passwords.
Example– Privacy
class Student:
def __init__(self):
[Link] = "Rekha" # Public
self._age = 20 # Protected
self.__marks = 95 # Private
s = Student()
print([Link])
print(s._age)
print(s._Student__marks) # Accessing private
attribute
Here, name is public and directly accessible. _age is protected and can be accessed,
though conventionally it should not be modified from outside. __marks is private and Python
internally renames it to _Student__marks to prevent accidental access. Privacy helps in
encapsulating sensitive information.
The Office class wraps the Printer object and delegates the task of printing to it. Office
does not print directly; it relies on the Printer class. This demonstrates both delegation (passing
responsibility) and wrapping (containing another object to extend behavior).
MODULE – II
MODULES, PACKAGES & PYTHON STANDARD LIBRARY
INTRODUCTION TO MODULES
A module in Python is simply a file that contains Python code (variables, functions,
classes). The main purpose of modules is to organize large programs into smaller, manageable
files. This improves readability and reusability. Instead of writing all code in one huge file,
developers split code into multiple modules and import them wherever needed. For example,
Python's math module contains mathematical functions, and we can use them anytime by
importing the module.
Syntax
import module_name
Example
import math
print([Link](25))
The math module is imported, and then we call sqrt() from it. This shows how modules
help reuse pre-written code instead of writing everything from scratch.
PACKAGES IN PYTHON
A package is a collection of modules stored in folders with an __init__.py file. Packages
help organize modules hierarchically. For example, in real software, a project may have a student
package containing modules like [Link], [Link], [Link].
Example
college/
__init__.py
[Link]
[Link]
Example
File: [Link]
def greet(name):
return f"Hello {name} from MREC"
Main Program
import mymodule
print([Link]("Priyanka"))
We created [Link] containing greet(). Then we imported it in the main program
and used the function. This is how user-defined modules work.
Main Program
from tools import calc
print([Link](3, 4))
A package folder tools contains a module calc. We imported the calc module and used
the add function. This is how Python handles multi-file projects.
INSTALLING PACKAGES WITH PIP
pip is Python’s package installer. Using pip, we can install external libraries from the
internet, such as numpy, pandas, flask, etc. These are not built-in modules but are freely available
for developers.
Syntax
pip install package_name
Example
pip install requests
NUMERIC & MATHEMATICAL MODULES
Python provides several modules to handle numbers, equations, random values, statistics,
and mathematical calculations.
numbers Module
The numbers module defines numeric abstract base classes like Number, Complex, Real.
It is helpful for checking the type of numeric values.
Example
import numbers
x = 10
print(isinstance(x, [Link]))
math Module
This module provides mathematical functions like sqrt, sin, cos, log, pow, floor, ceil, etc.
Example
import math
print([Link](0))
print([Link](5))
cmath Module
cmath handles complex number calculations, unlike math which works only on real
numbers.
Example
import cmath
z = 2 + 3j
print([Link](z))
decimal Module
decimal provides high-precision arithmetic, useful for banking, financial calculations,
and engineering accuracy.
Example
from decimal import Decimal
a = Decimal("1.1")
b = Decimal("2.2")
print(a + b)
Decimal avoids floating-point errors and gives precise results.
fractions Module
Used for rational number calculations (fractions).
Example
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6))
random Module
Generates random numbers, used in simulations, games, testing, AI models, etc.
Example
import random
print([Link](1, 10))
randint generates a random integer between 1 and 10.
statistics Module
Provides functions like mean, median, mode, variance—useful in data science and
analytics.
Example
import statistics
marks = [50, 60, 70, 80]
print([Link](marks))
Example
from datetime import datetime
print([Link]())
OS MODULE
The os module interacts with the operating system. It handles files, directories,
environment variables, and system paths.
Example
import os
print([Link]())
[Link]() gives the current working directory.
WEBBROWSER MODULE
This module opens URLs in the default browser.
Example
import webbrowser
[Link]("[Link]
Syntax
[Link](distance)
[Link](distance)
[Link](angle)
[Link](angle)
[Link](x, y) – move to specific position
The turtle draws a line, lifts the pen to move without drawing, then draws again. This is
useful for separating shapes.
Colour and Fill
You can fill shapes with color using fill methods.
Syntax
t.begin_fill()
t.end_fill()
[Link](pen, fill)
Example – Filled Circle
import turtle
t = [Link]()
[Link]("black", "yellow")
t.begin_fill()
[Link](60)
t.end_fill()
[Link]()
The turtle draws a circle with a black outline and fills the inside with yellow.
Multiple Turtles
We can create more than one turtle to draw at the same time.
Example – Two Turtles
import turtle
t1 = [Link]()
t2 = [Link]()
[Link]("red")
[Link]("green")
[Link](100)
[Link](90)
[Link](100)
[Link]()
The screen is cleared after drawing the first line, then a circle is drawn.
import tkinter as tk
root = [Link]()
[Link]()
TKINTER WIDGETS
Label
Used to display text.
Example
import tkinter as tk
root = [Link]()
label = [Link](root, text="Welcome to MREC Students!")
[Link]()
[Link]()
A label displays text in the window. pack() arranges it automatically.
Button
Used to perform actions when clicked.
Example
import tkinter as tk
def greet():
print("Hello Students!")
root = [Link]()
btn = [Link](root, text="Click Me", command=greet)
[Link]()
[Link]()
Canvas
Used for drawing shapes inside a GUI.
Example
import tkinter as tk
root = [Link]()
c = [Link](root, width=200, height=200)
[Link]()
c.create_rectangle(50, 50, 150, 150, fill="blue")
[Link]()
Menu
Used to create dropdown menus like File, Edit, etc.
Example
import tkinter as tk
root = [Link]()
menu = [Link](root)
[Link](menu=menu)
file_menu = [Link](menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New")
file_menu.add_command(label="Exit", command=[Link])
[Link]()
Menubutton
A button that shows a menu when clicked.
Example
import tkinter as tk
root = [Link]()
menubtn = [Link](root, text="Options", relief="raised")
menu = [Link](menubtn, tearoff=0)
[Link](menu=menu)
menu.add_command(label="Save")
menu.add_command(label="Exit")
[Link]()
[Link]()
Message
Used for showing long, wrapped text.
Example
import tkinter as tk
root = [Link]()
msg = [Link](root, text="Welcome to Advanced Python
Programming.\nThis is a Message Widget.")
[Link]()
[Link]()
Scale
Used to choose a value by sliding.
Example
import tkinter as tk
root = [Link]()
[Link](root, text="Adjust the Value").pack()
scale = [Link](root, from_=0, to=100, orient="horizontal")
[Link]()
[Link]()
Scrollbar
Used with text or list to scroll through content.
Example
import tkinter as tk
root = [Link]()
text = [Link](root, height=5)
scroll = [Link](root, command=[Link])
[Link](yscrollcommand=[Link])
[Link](side="left")
[Link](side="right", fill="y")
[Link]()
Text Widget
Used for multi-line text input.
Example
import tkinter as tk
root = [Link]()
t = [Link](root)
[Link]()
[Link]()
MODULE – IV
WEB & NETWORK PROGRAMMING IN PYTHON
INTRODUCTION TO WEB PROGRAMMING IN PYTHON
Web programming allows Python to communicate with websites, send requests, receive
information, and build simple web clients or servers. Python supports many libraries that
simplify web tasks such as fetching web pages, submitting data, automating browsing, and
interacting with servers.
Web programming is important for Data Science students because almost all real-time
applications (like social media, online banking, shopping websites, machine-learning APIs)
communicate over the internet. In Python, modules like urllib, requests, and [Link] help in
implementing basic web clients or servers.
The program opens the URL and reads the webpage content as HTML. We print only the
first 300 characters for clarity. This technique is useful for web scraping, data collection, and
automation.
CREATING SIMPLE WEB CLIENTS
A web client sends a request to a server and waits for a response. A simple Python web
client uses the urllib module to send HTTP GET or POST requests. These clients are used to
download files, get data from APIs, or read website content.
The web client connects to GitHub’s API server and prints the status code (200 = success)
and the response data.
A CGI script prints a content-type header followed by HTML output. When placed in a
server’s CGI folder, the server executes it and returns the result to the web browser.
This server serves files in the current directory. When you open [Link]
you can view the server output.
NETWORK PROGRAMMING WITH SOCKETS
Sockets allow two computers to communicate over a network. Python's socket module
supports creating both server and client programs.
Socket Module Basics
A socket represents a communication endpoint.
Important functions:
[Link](b"Hello Server")
data = [Link](1024)
print("Received:", [Link]())
[Link]()
The client sends a message and receives the same message from the server. This is called
"echo".
import socket
client = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link](b"Hello UDP Server", ("localhost", 9001))
data, addr = [Link](1024)
print("Received:", [Link]())
It returns sockets that are ready. This allows one server to serve many clients without blocking.
for s in readable:
if s is server:
conn, addr = [Link]()
[Link](conn)
else:
data = [Link](1024)
if data:
[Link](data)
else:
[Link](s)
[Link]()
The server can now respond to multiple clients without using threads.
MODULE – V
DATA ANALYSIS
NUMPY – INTRODUCTION
NumPy (Numerical Python) is the foundation library for scientific and data analysis tasks
in Python. It provides a very fast and memory-efficient structure called the ndarray (N-
Dimensional Array). Unlike Python lists, NumPy arrays store elements of the same type and
support vectorized operations, meaning operations are applied on entire arrays without loops.
This makes NumPy extremely useful for engineering, data science, and machine learning tasks
where calculations must be fast and efficient.
Example – Creating a Simple Array
import numpy as np
arr = [Link]([10, 20, 30, 40])
print(arr)
print("Data type:", [Link])
We imported NumPy with the common alias np. We then created a 1-D array and printed
it. The dtype shows the type of elements stored inside the array.
CREATING ARRAYS
NumPy provides many ways to create arrays: using Python lists, using built-in functions
like zeros(), ones(), arange(), and linspace().
Example
import numpy as np
a = [Link](5)
b = [Link]((2,3))
c = [Link](1, 10, 2)
d = [Link](0, 1, 5)
print(a)
print(b)
print(c)
print(d)
zeros() creates an array containing all zeros, ones() creates a matrix filled with ones,
arange() generates numbers with a step value, while linspace() creates evenly spaced values
between a range.
Multiplying the array with 10 multiplies every element. This eliminates loops and makes
computation faster.
INDEXING ARRAYS
Array indexing works similar to Python lists but supports multidimensional access.
Example
import numpy as np
mat = [Link]([[10, 20, 30],
[40, 50, 60]])
print(mat[0][1])
print(mat[:, 2])
mat[0][1] selects the element in first row and second column. mat[:,2] selects the entire
third column.
ARRAY TRANSPOSITION
Transposition flips rows into columns. It is useful for matrix operations and linear
algebra.
Example
import numpy as np
mat = [Link]([[1,2,3],
[4,5,6]])
print(mat.T)
T transposes the matrix — rows become columns and columns become rows.
ARRAY PROCESSING
NumPy supports many operations like sum, mean, square root, multiplication, and matrix
multiplication.
Example
import numpy as np
arr = [Link]([1, 4, 9])
print([Link](arr))
print([Link](arr))
print(arr + 5)
sqrt() gives square root of each element, sum() adds all values, and arr + 5 adds 5 to every
element.
[Link]() stores the array, and [Link]() reads it back from the file.
PANDAS
INTRODUCTION TO PANDAS
Pandas is a powerful library built on NumPy, used for data analysis and manipulation. It
provides two main data structures:
SERIES IN PANDAS
A Series stores data with labels called index. It is like a column in Excel.
Example
import pandas as pd
s = [Link]([10, 20, 30], index=['a','b','c'])
print(s)
The Series stores values with custom labels 'a', 'b', 'c'. You can access data using
index.
INDEX OBJECTS
Index objects store row or column labels and help in selecting data.
Example
import pandas as pd
s = [Link]([1,2,3])
print([Link])
REINDEX
Reindexing changes the index order or adds new indexes.
Example
import pandas as pd
s = [Link]([10,20,30], index=['x','y','z'])
print([Link](['z','y','x','a']))
DROP ENTRY
Drop removes rows or columns from data.
Example
import pandas as pd
s = [Link]([10,20,30], index=['a','b','c'])
print([Link]('b'))
Only matching indexes ('y' and 'z') are added; others become NaN.
SUMMARY STATISTICS
Pandas provides quick statistical results like mean, max, min, sum, etc.
Example
import pandas as pd
s = [Link]([10,40,30,20])
print([Link]())
print([Link]())
describe() gives count, mean, min, max, standard deviation, etc.
MISSING DATA
Missing values are represented as NaN. Pandas provides methods to fill or drop missing
data.
Example
import pandas as pd
import numpy as np
s = [Link]([1, [Link], 3])
print([Link](0))
INDEX HIERARCHY
Hierarchical indexing allows multiple levels of indexing, useful for complex datasets
(like student–department–year data in MRDU).
Example
import pandas as pd
s = [Link]([10,20,30],
index=[['CSE','CSE','ECE'],
['Year1','Year2','Year1']])
print(s)