[Go to site: main page, start]

0% found this document useful (0 votes)
57 views42 pages

Advanced Python Programming Notes

The document covers advanced Python programming concepts focusing on Object Oriented Programming (OOP) principles, including encapsulation, abstraction, inheritance, and polymorphism. It explains the structure and functionality of classes, instances, and attributes, along with methods for binding and invocation, composition, subclassing, and the use of built-in functions. Additionally, it discusses customizing classes with special methods, privacy through encapsulation, and delegation and wrapping techniques in programming.

Uploaded by

tajitha36
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)
57 views42 pages

Advanced Python Programming Notes

The document covers advanced Python programming concepts focusing on Object Oriented Programming (OOP) principles, including encapsulation, abstraction, inheritance, and polymorphism. It explains the structure and functionality of classes, instances, and attributes, along with methods for binding and invocation, composition, subclassing, and the use of built-in functions. Additionally, it discusses customizing classes with special methods, privacy through encapsulation, and delegation and wrapping techniques in programming.

Uploaded by

tajitha36
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

Advanced Python Programming

Module-I: Object Oriented Programming (OOP)


OOP PRINCIPLES
Object Oriented Programming is a fundamental concept in Python, empowering developers to
build modular, maintainable and scalable applications.
OOP is a way of organizing code that uses objects and classes to represent real-world
entities and their behavior. In OOP, object has attributes thing that has specific data and can
perform certain actions using methods.
Key Features of OOP in Python:
 Organizes code into classes and objects
 Supports encapsulation to group data and methods together
 Enables inheritance for reusability and hierarchy
 Allows polymorphism for flexible method implementation
 Improves modularity, scalability, and maintainability
Principles of OOP
Encapsulation
Encapsulation is the concept of binding data and methods together inside a single unit
called a class. It protects the data from being accessed or modified accidentally from outside the
class. Just like MRDU keeps student details safe inside the Student Information System and only
authorized functions can access them, a class protects its internal variables. Encapsulation helps
in writing secure, organized, and controlled code.
Abstraction
Abstraction means showing only the required features and hiding unnecessary internal
details. Students use an ATM or a biometric machine without knowing how the internal circuits
work. Similarly, in Python, we create simple methods that provide only the necessary
information while hiding the background complexity. Abstraction makes programs clean and
easy to understand by exposing only essential behavior.
Inheritance
Inheritance allows one class (child class) to acquire properties and methods of another
class (parent class). It supports code reusability. For example, a 3rd-year engineering student
still uses concepts learned in 1st and 2nd year; similarly, a child class extends the capabilities of
the parent class. Inheritance helps build a hierarchy of classes and reduces code duplication.
Polymorphism
Polymorphism means “many forms.” It allows the same function or method name to
perform different actions depending on the object calling it. For example, pressing the “submit”
button works differently on Google Classroom, a website, or an email app, though the na me is
the same. In Python, polymorphism is mainly achieved through method overriding and operator
overloading, making programs more flexible.
Simple Python Program Demonstrating All OOP Principles
class Student:
def __init__(self, name):
[Link] = name # Encapsulation

def details(self): # Abstraction


return f"Student: {[Link]}"

class CSEStudent(Student): # Inheritance


def details(self): # Polymorphism (method overriding)
return f"CSE Student: {[Link]}"

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

Example – Class Attribute


class College:
college_name = "MRDU" # Class Attribute
s1 = College()
s2 = College()
print(s1.college_name)
print(s2.college_name)

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

Example – Instance Attributes


class Student:
def __init__(self, name, roll):
[Link] = name # Instance Attribute
[Link] = roll # Instance Attribute
s1 = Student("Arun", 101)
s2 = Student("Meghana", 102)
print([Link], [Link])
print([Link], [Link])
In the example inside the Student class, the variables name and roll are created using self,
so they become instance attributes. This means s1 and s2 store different values:
s1 → (“Arun”, 101)
s2 → (“Meghana”, 102)
Instance attributes make each object have its own separate data, unlike class attributes which are
shared.

BINDING AND METHOD INVOCATION


Binding in Python is the process of connecting a method to an object. When we call a
method using an object, Python internally passes the object as the first argument, usually named
self. This allows the method to access the data stored in that specific object. Method invocation
refers to how we call or execute a method. There are three types: instance methods (normal
methods using self), class methods (using @classmethod and cls), and static methods (using
@staticmethod). Binding ensures that the correct object’s data is used when the method runs.
Syntax (Instance Method)
object_name.method_name()

Example – Method Binding


class Demo:
def greet(self):
return "Hello from MRDU"
d = Demo()
print([Link]())

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.

COMPOSITION AND COMPONENT


Composition represents a “has-a” relationship between classes. One class contains an
object of another class. For example, a Car has an Engine, or a Classroom has a Projector.
Composition allows modular and reusable design. Instead of making one massive class, smaller
components are combined, making programs more organized.
Example – Composition Example
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
[Link] = Engine() # Composition
def move(self):
return [Link]() + " and Car is moving"
c = Car()
print([Link]())

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.

SUB-CLASSING AND DERIVATION


Sub-classing (also called derivation) is when a new class (child) is created from an
existing class (parent). The child class automatically gets all attributes and methods of the parent.
This helps in code reuse. The child can also add new attributes or override existing methods for
specific behavior. For example, a CSEStudent is a type of Student, so it inherits all properties of
Student but can have additional methods.
Syntax
class Child(Parent):
pass
Example – Sub-classing
class Teacher:
def teach(self):
return "Teaching students"
class Professor(Teacher): # Sub-classing
pass
p = Professor()
print([Link]())

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.

BUILT-IN FUNCTIONS FOR CLASSES, INSTANCES, AND OTHER


OBJECTS
Python provides several built-in functions to inspect, manipulate, and interact with
classes, instances, and objects. Functions like type(), isinstance(), issubclass(), dir(), id(),
getattr(), setattr(), hasattr(), and delattr() allow programmers to check types, access attributes,
and perform dynamic operations on objects. These functions make Python flexible and allow
programmers to interact with objects without directly modifying the class structure.

Example – Built-in Functions


class Student:
def __init__(self, name):
[Link] = name
s = Student("Rahul")
print(type(s)) # Type of object
print(isinstance(s, Student)) # Check object-class relationship
print(hasattr(s, "name")) # Check if attribute exists
print(getattr(s, "name")) # Get attribute value
setattr(s, "roll", 101) # Add new attribute
print([Link])

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.

Example – Types vs Classes


x = 10
print(type(x)) # Built-in type
class Car:
pass
c = Car()
print(type(c)) # User-defined class instance
print(c.__class__) # Class of the object

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.

CUSTOMIZING CLASSES WITH SPECIAL METHODS


Python allows classes to define special methods (also called dunder methods) with double
underscores before and after the name, like __init__(), __str__(), __add__(), etc. These methods
let programmers customize how objects behave with built-in operations, such as printing, adding,
indexing, or comparing. For example, __str__() controls what is printed when an object is passed
to print().
Example – Special Methods
class Student:
def __init__(self, name, roll):
[Link] = name
[Link] = roll
def __str__(self):
return f"Student {[Link]}, Roll: {[Link]}"
s = Student("Meghana", 102)
print(s)

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.

DELEGATION AND WRAPPING


Delegation is when one object passes a task to another object to perform. Wrapping is
when a class contains another object and extends or modifies its behavior. These techniques are
commonly used in real-time applications, such as printing reports in college offices or wrapping
a library class to add new features.

Example – Delegation and Wrapping


class Printer:
def print_text(self, msg):
return msg
class Office:
def __init__(self):
[Link] = Printer() # Wrapping
def print_report(self):
return [Link].print_text("MRDU report printed")
o = Office()
print(o.print_report())

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.

IMPORT AND FROM IMPORT


Python provides two ways to bring module content into a program.
import module imports the whole module, and we access functions through the module name.
from module import function directly imports specific functions and allows calling them without
prefix.
Example
import math
from math import pi
print([Link](4.2))
print(pi)
The first import brings the entire math module, so we use [Link](). The second imports
only pi, so we can use pi directly. Both methods are valid depending on how much of the module
we need.

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]

CREATING AND IMPORTING USER-DEFINED MODULES


We can create our own module by writing Python code in a .py file and importing it into
another program. This helps reuse functions across multiple programs.

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.

CREATING AND IMPORTING USER-DEFINED PACKAGES


We can create a package by grouping modules inside a folder with an __init__.py file.
Then we import parts of the package using the dot notation.
Example
Folder: tools
tools/
__init__.py
[Link]
File: [Link]
def add(a, b):
return a + b

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]))

It checks whether x is a numeric type.

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))

[Link](0) returns 0, and [Link](5) returns 120.

cmath Module
cmath handles complex number calculations, unlike math which works only on real
numbers.
Example
import cmath
z = 2 + 3j
print([Link](z))

[Link]() returns the angle of the complex number.

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))

Fractions handle numerator and denominator cleanly.

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))

[Link]() calculates the average of the values.

TEXT PROCESSING MODULES


string Module
Provides constants and helper functions for string manipulation like ascii_letters, digits,
punctuation.
Example
import string
print(string.ascii_letters)
print([Link])

re Module (Regular Expressions)


Used for pattern matching—validating emails, phone numbers, passwords, etc.
Example
import re
print([Link](r"\d+", "MREC123"))

It extracts digits from the string.


DATE AND TIME MODULES
datetime Module
Used for working with dates and timestamps.

Example
from datetime import datetime
print([Link]())

[Link]() returns the current date and time.


calendar Module
Used for printing calendars and finding days of the week.
Example
import calendar
print([Link](2025, 12))

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]

It launches the college website on the system's web browser.


MODULE – III
GRAPHICS & GUI
INTRODUCTION TO GRAPHICS IN PYTHON
Graphics in Python helps students visually understand programming concepts like loops,
motion, and events. Python provides a simple graphics library called turtle, which acts like a
small robot holding a pen. It moves around the screen and draws shapes. This is very helpful to
beginners as they can see the output immediately. Turtle is used to draw geometric patterns,
animations, and simple games.
TURTLE MODULE
The turtle module comes built-in with Python. It uses movement commands to draw
shapes.
Motion Control
These commands move the turtle around the screen.

Syntax
[Link](distance)
[Link](distance)
[Link](angle)
[Link](angle)
[Link](x, y) – move to specific position

Example – Draw a Square


import turtle
t = [Link]()
for i in range(4):
[Link](100)
[Link](90)
[Link]()
The turtle moves forward 100 units, then turns 90 degrees to the right. Repeating these
four times draws a square.
Pen Control
Pen control manages how the turtle draws on the screen.
Syntax
[Link](width) – thickness of lines
[Link](color) – changes pen color
[Link]() – lifts pen (moves without drawing)
[Link]() – puts pen down
[Link](1–10) – speed of drawing

Example – Pen Control Demo


import turtle
t = [Link]()
[Link](4)
[Link]("blue")
[Link](120)
[Link]()
[Link](50)
[Link]()
[Link](120)
[Link]()

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]()

Each turtle acts independently, allowing multi-object animations.


Reset and Clear
Used for cleaning the drawing.
Syntax
[Link]() – clears drawing but turtle position stays
[Link]() – clears drawing and resets turtle to center
Example
import turtle
t = [Link]()
[Link](100)
[Link]()
[Link](50)
[Link]()

The screen is cleared after drawing the first line, then a circle is drawn.

Introduction to GUI with Tkinter


Tkinter is Python’s standard GUI (Graphical User Interface) library. It is used to create
windows, forms, labels, buttons, menus, and many components for building small applications
like calculators, login screens, and mini-projects.
A GUI window starts with:

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]()

When the button is clicked, the function greet() is executed.


Entry (Input Box)
Used for entering single-line text.
Example
import tkinter as tk
root = [Link]()
e = [Link](root)
[Link]()
[Link]()

This creates an input box, useful for username or search input.


Frame
A frame holds other widgets.
Example
import tkinter as tk
root = [Link]()
frame = [Link](root, bg="lightblue", bd=5)
[Link]()
[Link](frame, text="Inside Frame").pack()
[Link]()

A frame is like a container inside the main window.


Listbox
Used to display a list of items.
Example
import tkinter as tk
root = [Link]()
lb = [Link](root)
[Link](1, "CSE")
[Link](2, "ECE")
[Link](3, "EEE")
[Link]()
[Link]()

The listbox shows department names that students can select.


Checkbutton
Allows multiple selections.
Example
import tkinter as tk
root = [Link]()
c1 = [Link](root, text="Python")
c2 = [Link](root, text="Java")
[Link]()
[Link]()
[Link]()
Radiobutton
Allows only one selection.
Example
import tkinter as tk
root = [Link]()
v = [Link]()
[Link](root, text="Male", variable=v, value=1).pack()
[Link](root, text="Female", variable=v, value=2).pack()
[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.

WEB SURFING WITH PYTHON


Web surfing using Python means connecting to websites and reading their contents
automatically. Instead of opening Chrome or Firefox, Python can send a request to a webpage
and receive the HTML content. The [Link] module is commonly used for this purpose.

Example – Reading a Webpage


from urllib import request
page = [Link]("[Link]
content = [Link]()
print(content[:300])

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.

Example – Simple Web Client


import [Link]
url = "[Link]
response = [Link](url)
print("Status:", [Link])
print("Data:", [Link]().decode())

The web client connects to GitHub’s API server and prints the status code (200 = success)
and the response data.

ADVANCED WEB CLIENTS


Advanced clients may send additional headers, authentication data, or POST form data.
Python allows more control using the requests module (if available) or advanced urllib features.
Through this
 send POST requests,
 upload form data,
 add authentication,
 handle cookies,
 handle errors.

CGI – HELPING SERVERS PROCESS CLIENT DATA


CGI (Common Gateway Interface) is an older method that allows web servers to execute
Python scripts when users submit forms. A CGI script processes user input and sends a dynamic
webpage as output.
Example – Simple CGI Script (concept only)
#!/usr/bin/python3
print("Content-Type: text/html\n")
print("<h1>Hello from CGI in Python!</h1>")

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.

BUILDING CGI APPLICATIONS


A CGI application gets data from the user (via HTML form), processes it, and returns
output. Python uses the cgi module to read form data. This is mostly used for academic learning
because modern systems now use frameworks.

WEB (HTTP) SERVERS IN PYTHON


Python can act as a web server using the [Link] module. This server responds to
HTTP requests.

Example – Simple HTTP Server


import [Link]
import socketserver
PORT = 8000
handler = [Link]
with [Link](("", PORT), handler) as httpd:
print("Serving at port", PORT)
httpd.serve_forever()

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:

socket() → creates a socket


bind() → attaches socket to IP and port
listen() → server waits for clients
accept() → server accepts client connection
connect() → client connects to a server
send() / sendall() → send data
recv() → receive data
close() → close connection

TCP ECHO SERVER


A TCP server waits for a client, receives data, and sends it back.
Program – TCP Echo Server
import socket
server = [Link]()
[Link](("localhost", 9000))
[Link](1)
print("Server waiting...")
conn, addr = [Link]()
print("Connected:", addr)
data = [Link](1024).decode()
[Link]([Link]())
[Link]()
[Link]()
The server listens on port 9000, accepts a client, reads data, and sends the same data back.

TCP ECHO CLIENT


import socket
client = [Link]()
[Link](("localhost", 9000))

[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".

UDP ECHO SERVER


UDP is connectionless and faster than TCP.

Program – UDP Server


import socket
server = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link](("localhost", 9001))
print("UDP Server ready")
while True:
data, addr = [Link](1024)
[Link](data, addr)
No connection is needed; the server receives data from any client and sends the same
data back.

UDP ECHO CLIENT

import socket
client = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link](b"Hello UDP Server", ("localhost", 9001))
data, addr = [Link](1024)
print("Received:", [Link]())

UDP client sends a message and receives the echo response.

HANDLING MULTIPLE CLIENTS AT ONCE


A server can handle multiple clients simultaneously using the select module. select
monitors multiple sockets and tells which ones are ready to read or write.
[Link]() takes 3 lists:
 sockets to read
 sockets to write
 sockets to check for errors

It returns sockets that are ready. This allows one server to serve many clients without blocking.

Basic conceptual example (not full implementation):


import socket, select
server = [Link]()
[Link](("localhost", 9002))
[Link](5)
sockets = [server]
while True:
readable, _, _ =
[Link](sockets, [], [])

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.

USING ARRAYS AND SCALARS


NumPy allows operations directly between arrays and values (scalars). These operations
apply to each element automatically.
Example
import numpy as np
arr = [Link]([1, 2, 3])
result = arr * 10
print(result)

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.

ARRAY INPUT AND OUTPUT


NumPy allows saving arrays to files and reading them back.
Example
import numpy as np
arr = [Link]([10,20,30])
[Link]("[Link]", arr)
loaded = [Link]("[Link]")
print(loaded)

[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 – One-dimensional labeled array


 DataFrame – Two-dimensional table similar to Excel
Pandas is widely used in Data Science, Machine Learning, AI, and analytics because it handles
real-world datasets easily (CSV, Excel, SQL, etc.).

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])

The index shows the position labels of the Series.

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']))

New index 'a' has no data, so NaN is shown.

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'))

The row with index 'b' is removed.


SELECT ENTRIES
Selecting data is done by index or position.
Example
import pandas as pd
s = [Link]([10,20,30], index=['a','b','c'])
print(s['a'])

This returns the value at index 'a'.


DATA ALIGNMENT
When operations happen between two Series/DataFrames, Pandas automatically aligns
data based on index.
Example
import pandas as pd
a = [Link]([1,2,3], index=['x','y','z'])
b = [Link]([4,5], index=['y','z'])
print(a + b)

Only matching indexes ('y' and 'z') are added; others become NaN.

RANK AND SORT


Sorting arranges values in ascending or descending order. Ranking assigns ranks to
values.
Example
import pandas as pd
s = [Link]([30,10,20])
print(s.sort_values())
print([Link]())
sort_values() sorts the Series; rank() assigns rankings.

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))

Missing value is replaced with 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)

Two-level indexing helps organize data in grouped form.

You might also like