[Go to site: main page, start]

0% found this document useful (0 votes)
3 views296 pages

Programming in Python

The document provides an introduction to Python programming, covering its features, applications, and basic elements such as tokens, keywords, identifiers, and data types. It explains fundamental programming concepts including variables, operators, expressions, and branching statements like if-else and nested if statements. Additionally, it discusses string manipulation and input/output functions, emphasizing the importance of indentation and comments in Python code.

Uploaded by

jatinchauhan6560
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)
3 views296 pages

Programming in Python

The document provides an introduction to Python programming, covering its features, applications, and basic elements such as tokens, keywords, identifiers, and data types. It explains fundamental programming concepts including variables, operators, expressions, and branching statements like if-else and nested if statements. Additionally, it discusses string manipulation and input/output functions, emphasizing the importance of indentation and comments in Python code.

Uploaded by

jatinchauhan6560
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

Sarvodaya College of Computer Science Programming in Python

MATERIAL

Unit 1: Introduction to Python


1. Introduction to Python

1.1 What is Python?


Python is a high-level, interpreted, and general-purpose programming language. It
is simple to learn and easy to use. Python is widely used in:
 Web Development
 Artificial Intelligence
 Machine Learning
 Data Science
 Software Development
 Automation
 Game Development
Python uses simple English-like syntax, which makes it beginner-friendly.

1.2 Features of Python


1. Easy to Learn
2. Simple Syntax
3. Open Source
4. Platform Independent
5. Object-Oriented
6. Large Library Support
7. Interpreted Language
8. Dynamically Typed

1.3 Applications of Python


 Website Development
 Data Analysis
 Artificial Intelligence
 Automation Scripts
 Desktop Applications
 Cyber Security
 Cloud Computing

Created by Rashesh Rehi 7


Sarvodaya College of Computer Science Programming in Python

2. Basic Elements of Python

The basic elements of Python are the fundamental building blocks used to create
Python programs. Before learning advanced programming concepts, students
must understand these basic elements clearly.
The basic elements include:

1. Python Tokens
2. Keywords
3. Identifiers
4. Variables
5. Data Types
6. Operators
7. Expressions
8. Statements
9. Comments
[Link]
[Link] and Output Functions
[Link] Conversion

2.1 Python Tokens


Tokens are the smallest individual units in a Python program.
Python tokens are divided into:
 Keywords
 Identifiers
 Literals
 Operators
 Delimiters

Example
a = 10
print(a)

In this example:
Token Type
a Identifier

Created by Rashesh Rehi 8


Sarvodaya College of Computer Science Programming in Python

Token Type
= Operator
10 Literal
print Function

2.2 Keywords
Keywords are reserved words in Python that have special meanings.
We cannot use keywords as variable names.

Common Python Keywords


Keyword Meaning
if Condition
else Alternative condition
while Loop
for Iteration
break Stop loop
continue Skip iteration
def Define function
return Return value
import Import module
True Boolean true
False Boolean false

Example
if 5 > 2:
print("Five is greater")
Here:
 if is a keyword
 print is a function

2.3 Identifiers
Identifiers are names given to:
 Variables

Created by Rashesh Rehi 9


Sarvodaya College of Computer Science Programming in Python

 Functions
 Classes
 Modules

Rules for Identifiers


1. Must start with letter or underscore (_)
2. Cannot start with number
3. Cannot contain spaces
4. Cannot use keywords
5. Case-sensitive

Valid Identifiers
name
student_name
_age
totalMarks

Invalid Identifiers
2name
my name
class

2.4 Variables
Variables are containers used to store data values.
Python creates variables automatically when value is assigned.

Syntax
variable_name = value

Example
name = "Python"
age = 20
marks = 85.5
print(name)
print(age)
print(marks)

Created by Rashesh Rehi 10


Sarvodaya College of Computer Science Programming in Python

Rules for Variable Names


1. Must start with letter or underscore
2. Cannot contain spaces
3. Cannot start with number
4. Case-sensitive

Multiple Variable Assignment


a, b, c = 10, 20, 30
print(a)
print(b)
print(c)

Dynamic Typing in Python


Python automatically detects data type.
x = 10
print(type(x))
x = "Hello"
print(type(x))

2.5 Data Types in Python


Data type defines the type of value stored in a variable.

Numeric Data Types


Integer (int)
Stores whole numbers.
a = 100
print(type(a))

Float
Stores decimal numbers.
price = 99.99
print(type(price))

String Data Type


String stores text data.

Created by Rashesh Rehi 11


Sarvodaya College of Computer Science Programming in Python

name = "Python"
print(type(name))

Boolean Data Type


Boolean contains:
 True
 False
is_pass = True
print(type(is_pass))

List Data Type


List stores multiple items.
numbers = [10, 20, 30]
print(type(numbers))

Tuple Data Type


Tuple is immutable collection.
data = (1, 2, 3)
print(type(data))

Dictionary Data Type


Stores key-value pairs.
student = {
"name": "Ravi",
"marks": 90
}
print(type(student))

Set Data Type


Stores unique values.
s = {1, 2, 3}
print(type(s))

2.6 Operators in Python


Operators perform operations on variables and values.

Created by Rashesh Rehi 12


Sarvodaya College of Computer Science Programming in Python

Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic Operators
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b
** Exponent a ** b
// Floor Division a // b

Example
a = 10
b=3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)
print(a // b)

Relational Operators
Used for comparison.
Operator Meaning
== Equal

Created by Rashesh Rehi 13


Sarvodaya College of Computer Science Programming in Python

Operator Meaning
!= Not equal
> Greater
< Less
>= Greater equal
<= Less equal

Example
a = 10
b = 20
print(a > b)
print(a < b)

Logical Operators
Operator Meaning
and Both conditions true
or Any one true
not Reverse condition

Example
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Assignment Operators
Operator Example
= x=5
+= x += 2
-= x -= 2
*= x *= 2

Created by Rashesh Rehi 14


Sarvodaya College of Computer Science Programming in Python

Example
x=5
x += 2
print(x)

Membership Operators
Operator Meaning
in Present
not in Not present

Example
name = "Python"
print("P" in name)

Identity Operators
Operator Meaning
is Same object
is not Different object

Example
a = [1, 2]
b=a
print(a is b)

2.7 Expressions
An expression is a combination of:
 Variables
 Values
 Operators
that produces a result.

Example
a = 10
b=5
c=a+b

Created by Rashesh Rehi 15


Sarvodaya College of Computer Science Programming in Python

Here:
 a + b is expression

2.8 Statements
Statements are instructions executed by Python interpreter.

Types of Statements
1. Assignment Statement
2. Conditional Statement
3. Loop Statement
4. Function Statement

Example
x = 10
print(x)

2.9 Comments
Comments are notes written inside program.
Python ignores comments during execution.

Single Line Comment


# This is comment
print("Hello")

Multi-line Comment
"""
This is
multi-line comment
"""

Advantages of Comments
1. Improves readability
2. Helps debugging
3. Makes code understandable

Created by Rashesh Rehi 16


Sarvodaya College of Computer Science Programming in Python

2.10 Indentation
Python uses indentation to define blocks of code.
Indentation means spaces before statement.

Example
if 5 > 2:
print("Correct Indentation")

Incorrect Indentation
if 5 > 2:
print("Error")
This generates:
 IndentationError

Importance of Indentation
1. Improves readability
2. Defines program structure
3. Mandatory in Python

2.11 Input and Output Functions

Output Function
Python uses print() function to display output.

Example
print("Welcome to Python")

Multiple Outputs
name = "Ravi"
age = 21
print(name, age)

Input Function
Python uses input() function to take user input.

Created by Rashesh Rehi 17


Sarvodaya College of Computer Science Programming in Python

Example
name = input("Enter your name: ")
print(name)

Input for Integer


age = int(input("Enter age: "))
print(age)

2.12 Type Conversion


Type conversion means changing one data type into another.

Implicit Type Conversion


Automatically done by Python.
a=5
b = 2.5
c=a+b
print(c)

Explicit Type Conversion


Done manually using functions.
Function Meaning
int() Convert to integer
float() Convert to float
str() Convert to string

Example
x = "10"
y = int(x)
print(y)
print(type(y))

Created by Rashesh Rehi 18


Sarvodaya College of Computer Science Programming in Python

3. Branching Programs

Branching means making decisions in a program.


In real life, we make decisions every day.

Example:
 If it is raining, take umbrella.
 If marks are greater than 40, student passes.
 If balance is low, recharge mobile.

Similarly, in programming, we use branching statements to make decisions based


on conditions.

Python provides decision-making statements such as:


1. if statement
2. if-else statement
3. nested if statement
4. if-elif-else ladder

These statements help the program choose different paths depending on


conditions.

Why Branching is Important?

Branching is used to:


 Control program flow
 Make decisions
 Execute different blocks of code
 Build logical programs
 Handle real-world situations

Created by Rashesh Rehi 19


Sarvodaya College of Computer Science Programming in Python

Flow of Branching Program

3.1 The if Statement


The if statement executes code only when the condition is True.

Syntax of if Statement
if condition:
statements

Working of if Statement
1. Python checks condition.
2. If condition is True:
o statements inside if block execute.
3. If condition is False:
o statements are skipped.

Example 1: Positive Number Check


num = 10
if num > 0:
print("Positive Number")

Created by Rashesh Rehi 20


Sarvodaya College of Computer Science Programming in Python

Output
Positive Number

Example 2: Voting Eligibility


age = 20
if age >= 18:
print("Eligible for Voting")

Important Points about if Statement


1. Colon (:) is compulsory.
2. Indentation is required.
3. Condition must return True or False.

3.2 if-else Statement


The if-else statement is used when there are two choices.
 If condition is True → if block executes.
 Otherwise → else block executes.

Syntax
if condition:
statements
else:
statements

Example 1: Even or Odd


num = 7

if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")

Output
Odd Number

Created by Rashesh Rehi 21


Sarvodaya College of Computer Science Programming in Python

Example 2: Pass or Fail


marks = 35

if marks >= 40:


print("Pass")
else:
print("Fail")

3.3 Nested if Statement


A nested if means:
 One if statement inside another if statement.
Used when multiple conditions must be checked.

Syntax
if condition1:
if condition2:
statements

Example: Largest of Three Numbers


a = 20
b = 15
c = 10

if a > b:
if a > c:
print("A is largest")

Example: Student Grade System


marks = 85

if marks >= 40:


if marks >= 75:
print("Distinction")

Advantages of Nested if
1. Useful for complex conditions

Created by Rashesh Rehi 22


Sarvodaya College of Computer Science Programming in Python

2. Improves logical checking


3. Helps in multi-level decision making

Disadvantages of Nested if
1. Program becomes lengthy
2. Difficult to understand
3. Hard to debug

3.4 if-elif-else Ladder


Used when there are multiple conditions.
Python checks conditions one by one.
 First True condition executes.
 Remaining conditions are skipped.

Syntax
if condition1:
statements

elif condition2:
statements

elif condition3:
statements

else:
statements

Example: Grade Calculation


marks = 72

if marks >= 90:


print("Grade A")

elif marks >= 70:


print("Grade B")

Created by Rashesh Rehi 23


Sarvodaya College of Computer Science Programming in Python

elif marks >= 50:


print("Grade C")
else:
print("Fail")

Output
Grade B

Example: Menu Program


choice = 2
if choice == 1:
print("Tea")
elif choice == 2:
print("Coffee")
elif choice == 3:
print("Cold Drink")
else:
print("Invalid Choice")

Flowchart of if-elif-else

Created by Rashesh Rehi 24


Sarvodaya College of Computer Science Programming in Python

3.5 Logical Operators in Branching


Logical operators are often used with conditions.

Types of Logical Operators


Operator Meaning
and Both conditions True
or Any one True
not Reverse result

Example Using and


age = 20
citizen = True

if age >= 18 and citizen:


print("Eligible")

Example Using or
a=5
b = 10

if a > 0 or b > 0:
print("Positive Number Exists")

Example Using not


is_raining = False

if not is_raining:
print("Go Outside")

3.6 Comparison Operators in Branching


Comparison operators compare values.
Operator Meaning
== Equal
!= Not Equal
> Greater

Created by Rashesh Rehi 25


Sarvodaya College of Computer Science Programming in Python

Operator Meaning
< Smaller
>= Greater or Equal
<= Smaller or Equal

Example
a = 10
b = 20
if a < b:
print("A is smaller")

3.7 Indentation in Branching


Python uses indentation to define code blocks.

Correct Example
if 5 > 2:
print("Correct")

Wrong Example
if 5 > 2:
print("Error")
This produces:
 IndentationError

3.8 Short-Hand if Statement


Python allows writing if statement in one line.

Syntax
if condition: statement

Example
a = 10
if a > 5: print("Greater")

3.9 Short-Hand if-else Statement


Also called Ternary Operator.
Created by Rashesh Rehi 26
Sarvodaya College of Computer Science Programming in Python

Syntax
statement1 if condition else statement2

Example
num = 8
print("Even") if num % 2 == 0 else print("Odd")

4. Strings and Input

A string is a sequence of characters enclosed inside:


 Single quotes ' '
 Double quotes " "
 Triple quotes ''' ''' or """ """

Strings are used to store:


 Names
 Addresses
 Messages
 Sentences
 Passwords
 Text data

Examples of Strings
name = "Python"
city = 'Rajkot'
message = """Welcome to Python"""

Characteristics of Strings
1. Strings are ordered.
2. Strings are immutable.
3. Strings support indexing.
4. Strings support slicing.
5. Strings can contain letters, numbers, and symbols.

Created by Rashesh Rehi 27


Sarvodaya College of Computer Science Programming in Python

String Representation

4.1 Creating Strings


Strings can be created using quotes.

Single Quote String


s1 = 'Hello'
print(s1)

Double Quote String


s2 = "Python"
print(s2)

Triple Quote String


Used for multi-line strings.
text = """Python is
easy to learn"""
print(text)

4.2 String Indexing


Indexing means accessing characters using position numbers.
Python indexing starts from 0.

Example
word = "PYTHON"

Created by Rashesh Rehi 28


Sarvodaya College of Computer Science Programming in Python

print(word[0])
print(word[1])
print(word[5])

Output
P
Y
N

Positive Indexing
Character P Y T H O N
Index 0123 4 5

Negative Indexing
Python also supports negative indexing.
Character P Y T H O N
Index -6 -5 -4 -3 -2 -1

Example
word = "PYTHON"
print(word[-1])
print(word[-2])

Advantages of Indexing
1. Access individual characters
2. Useful in loops
3. Helps string manipulation

4.3 String Slicing


Slicing means extracting part of string.

Syntax
string[start:end]

Created by Rashesh Rehi 29


Sarvodaya College of Computer Science Programming in Python

Example
text = "PYTHON"
print(text[0:3])
print(text[2:5])

Output
PYT
THO

Slicing Rules
1. Start index included
2. End index excluded
3. Default start = 0
4. Default end = length of string

Example with Default Values


text = "PYTHON"

print(text[:4])
print(text[2:])

Step Slicing
Syntax:
string[start:end:step]

Example
text = "PYTHON"
print(text[0:6:2])

Output
PTO

Reverse String Using Slicing


text = "PYTHON"
print(text[::-1])

Created by Rashesh Rehi 30


Sarvodaya College of Computer Science Programming in Python

Output
NOHTYP

4.4 String Immutability


Strings are immutable means:
 Original string cannot be changed.

Example
name = "Python"
# name[0] = "J" ❌ Error

Correct Method
name = "Python"
new_name = "J" + name[1:]
print(new_name)

4.5 String Operators

Concatenation Operator (+)


Used to join strings.

Example
a = "Hello"
b = "World"
print(a + " " + b)

Repetition Operator (*)


Repeats string multiple times.

Example
print("Python " * 3)

Membership Operators
Checks presence of character or substring.

Created by Rashesh Rehi 31


Sarvodaya College of Computer Science Programming in Python

Example
text = "Python"

print("P" in text)
print("z" not in text)

4.6 String Functions


Python provides many built-in string functions.

len() Function
Returns length of string.
text = "Python"
print(len(text))

upper() Function
Converts to uppercase.
text = "python"
print([Link]())

lower() Function
Converts to lowercase.
text = "PYTHON"
print([Link]())

title() Function
Converts first letter of each word into capital.
text = "python programming"
print([Link]())

strip() Function
Removes spaces.
text = " Python "
print([Link]())

replace() Function
Replaces substring.

Created by Rashesh Rehi 32


Sarvodaya College of Computer Science Programming in Python

text = "Hello Python"


print([Link]("Python", "World"))

find() Function
Finds index of substring.
text = "Python"
print([Link]("t"))

count() Function
Counts occurrences.
text = "banana"
print([Link]("a"))

split() Function
Splits string into list.
text = "Python Java C"
print([Link]())

join() Function
Joins list into string.
words = ["Python", "Java", "C"]
print("-".join(words))

4.7 Escape Characters


Escape characters start with backslash \.

Common Escape Characters


Escape Character Meaning
\n New line
\t Tab space
\ Backslash
' Single quote
" Double quote

Created by Rashesh Rehi 33


Sarvodaya College of Computer Science Programming in Python

Example
print("Hello\nPython")

Output
Hello
Python

4.8 Input in Python


Input means taking data from user.
Python uses:
 input() function

Syntax
input("message")

Example
name = input("Enter your name: ")
print(name)

How input() Works


1. Displays message
2. Waits for user input
3. Stores value as string

Important Note
input() always returns string data.

Example
age = input("Enter age: ")
print(type(age))

Output
<class 'str'>

4.9 Type Conversion with Input


To use numbers, convert input using:

Created by Rashesh Rehi 34


Sarvodaya College of Computer Science Programming in Python

 int()
 float()

Integer Input
age = int(input("Enter age: "))
print(age)

Float Input
price = float(input("Enter price: "))
print(price)

Multiple Inputs
a, b = input("Enter two numbers: ").split()
print(a)
print(b)

Multiple Integer Inputs


a, b = map(int, input("Enter two numbers: ").split())
print(a + b)

4.10 Formatting Output


Using Comma
name = "Ravi"
age = 21
print("Name:", name, "Age:", age)

Using format()
name = "Python"
print("Welcome {}".format(name))

Using f-string
Modern and easy method.
name = "Python"
print(f"Welcome {name}")

Created by Rashesh Rehi 35


Sarvodaya College of Computer Science Programming in Python

5. Iteration

Iteration means repeating a block of code multiple times until a condition


becomes false.
In programming, many tasks need repetition.

Examples:
 Printing numbers from 1 to 100
 Calculating sum of numbers
 Displaying multiplication tables
 Repeating menu options

Instead of writing same code again and again, loops are used.
Python provides iteration statements:
1. while loop
2. for loop

Flow of Iteration

Created by Rashesh Rehi 36


Sarvodaya College of Computer Science Programming in Python

Types of Iteration in Python


Loop Type Purpose
while loop Executes while condition is true
for loop Iterates over sequence

5.1 while Loop


The while loop repeats statements as long as condition remains True.

Syntax of while Loop


while condition:
statements

Working of while Loop


1. Condition is checked.
2. If condition is True:
o loop body executes.
3. Again condition checked.
4. Process repeats until condition becomes False.

Example 1: Print Numbers 1 to 5


i=1

while i <= 5:
print(i)
i += 1

Output
1
2
3
4
5

Created by Rashesh Rehi 37


Sarvodaya College of Computer Science Programming in Python

Explanation
Step Value of i Condition
1 1 True
2 2 True
3 3 True
4 4 True
5 5 True
6 6 False

Example 2: Sum of First 5 Numbers


i=1
total = 0
while i <= 5:
total = total + i
i += 1
print("Sum =", total)

Output
Sum = 15

Infinite while Loop


If condition never becomes False, loop runs forever.

Example
while True:
print("Hello")

Advantages of while Loop


1. Useful when number of iterations unknown
2. Easy for condition-based repetition
3. Suitable for menu-driven programs

Disadvantages of while Loop


1. Can create infinite loops

Created by Rashesh Rehi 38


Sarvodaya College of Computer Science Programming in Python

2. More chances of logical errors

5.2 for Loop


The for loop is used to iterate over:
 Strings
 Lists
 Tuples
 Range of numbers

Syntax of for Loop


for variable in sequence:
statements

Example 1: Print Numbers


for i in range(1, 6):
print(i)

Output
1
2
3
4
5

Example 2: Print Characters


word = "PYTHON"
for ch in word:
print(ch)

Output
P
Y
T
H
O
N

Created by Rashesh Rehi 39


Sarvodaya College of Computer Science Programming in Python

5.3 range() Function


range() generates sequence of numbers.

Syntax
range(start, stop, step)

Parameters
Parameter Meaning
start Starting value
stop Ending value
step Increment/decrement

Example 1
for i in range(5):
print(i)

Output
0
1
2
3
4

Example 2
for i in range(1, 10, 2):
print(i)

Output
1
3
5
7
9

Created by Rashesh Rehi 40


Sarvodaya College of Computer Science Programming in Python

Reverse Loop
for i in range(10, 0, -1):
print(i)

Output
10
9
8
7
6
5
4
3
2
1

5.4 Nested Loops


A loop inside another loop is called nested loop.

Example
for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Output
11
12
13
21
22
23
31
32
33

Created by Rashesh Rehi 41


Sarvodaya College of Computer Science Programming in Python

5.5 break Statement


break immediately terminates loop.

Example
for i in range(1, 10):
if i == 5:
break
print(i)

Output
1
2
3
4

Working of break
1. Loop runs normally.
2. When break executes:
o loop stops immediately.

5.6 continue Statement


continue skips current iteration.

Example
for i in range(1, 6):
if i == 3:
continue
print(i)

Output
1
2
4
5

Created by Rashesh Rehi 42


Sarvodaya College of Computer Science Programming in Python

5.7 pass Statement


pass does nothing.
Used as placeholder.

Example
for i in range(5):
pass

Why pass is Used?


1. Future code writing
2. Empty loops/functions/classes

5.8 Loop else Statement


Python supports else with loops.
else executes when loop finishes normally.

Example
for i in range(5):
print(i)
else:
print("Loop Completed")

Output
0
1
2
3
4
Loop Completed

5.9 Iterating Through Different Data Types

String Iteration
text = "Python"

Created by Rashesh Rehi 43


Sarvodaya College of Computer Science Programming in Python

for ch in text:
print(ch)

List Iteration
numbers = [10, 20, 30]

for n in numbers:
print(n)

Tuple Iteration
data = (1, 2, 3)

for item in data:


print(item)

Dictionary Iteration
student = {
"name": "Ravi",
"marks": 90
}

for key in student:


print(key, student[key])

6. Functions and Scoping

A function is a block of reusable code that performs a specific task.


Functions help:
 Reduce repetition
 Organize programs
 Improve readability
 Reuse code multiple times
Instead of writing same code again and again, we can create a function once and
use it whenever needed.

Created by Rashesh Rehi 44


Sarvodaya College of Computer Science Programming in Python

Real-Life Example of Function


Examples from daily life:
 Calculator performs addition function
 Washing machine performs washing function
 Mobile camera performs photo capturing function
Similarly, Python functions perform specific programming tasks.

Advantages of Functions
1. Code Reusability
2. Better Program Structure
3. Easy Debugging
4. Easy Maintenance
5. Reduces Code Length

Function Working Diagram

6.1 Types of Functions


Python provides two types of functions:
Type Description
Built-in Functions Already available in Python
User-defined Functions Created by programmer

Built-in Functions
Examples:
 print()
 len()
 input()
 type()
 max()

Created by Rashesh Rehi 45


Sarvodaya College of Computer Science Programming in Python

Example
text = "Python"
print(len(text))

User-defined Functions
Functions created using def keyword.

Syntax of Function
def function_name():
statements

Example
def greet():
print("Welcome to Python")
greet()

Output
Welcome to Python

Explanation
Part Meaning
def Keyword to define function
greet Function name
() Parameters
: Start of block
greet() Function call

6.2 Function Calling


After creating function, it must be called.

Example
def hello():
print("Hello Student")

Created by Rashesh Rehi 46


Sarvodaya College of Computer Science Programming in Python

hello()
hello()

Output
Hello Student
Hello Student

6.3 Parameters and Arguments


Parameters are variables inside function definition.
Arguments are values passed during function call.

Example
def add(a, b):
print(a + b)
add(10, 20)

Explanation
Item Value
Parameters a, b
Arguments 10, 20

Advantages of Parameters
1. Make function flexible
2. Avoid repeated code
3. Accept different inputs

6.4 Return Statement


Functions can return values using return.

Syntax
def function():
return value

Created by Rashesh Rehi 47


Sarvodaya College of Computer Science Programming in Python

Example
def square(n):
return n * n
result = square(5)
print(result)

Output
25

Difference Between print() and return


print() return
Displays value Sends value back
Cannot reuse output easily Output reusable

Example Using return


def add(a, b):
return a + b
x = add(5, 10)
print(x)

6.5 Types of User-Defined Functions

Function Without Parameters and Without Return


def show():
print("Python")
show()
Function With Parameters and Without Return
def add(a, b):
print(a + b)
add(2, 3)

Function Without Parameters but With Return


def message():
return "Welcome"
print(message())

Created by Rashesh Rehi 48


Sarvodaya College of Computer Science Programming in Python

Function With Parameters and Return


def multiply(a, b):
return a * b
print(multiply(4, 5))

6.6 Default Parameters


Functions can have default values.

Example
def greet(name="Student"):
print("Hello", name)
greet()
greet("Ravi")

Output
Hello Student
Hello Ravi

6.7 Keyword Arguments


Arguments can be passed using parameter names.

Example
def student(name, age):
print(name, age)
student(age=21, name="Ravi")

Advantages
1. Order not important
2. Improves readability

6.8 Variable Length Arguments


Python allows multiple arguments using *.

Created by Rashesh Rehi 49


Sarvodaya College of Computer Science Programming in Python

Example
def total(*numbers):
sum = 0

for n in numbers:
sum += n
print(sum)
total(1, 2, 3)

Output
6

6.9 Scope of Variables


Scope means visibility of variable.
Python mainly provides:
1. Local Scope
2. Global Scope

Local Variable
Declared inside function.
Accessible only inside function.

Example
def demo():
x = 10
print(x)
demo()

Output
10

Error Outside Function


def demo():
x = 10
print(x)

Created by Rashesh Rehi 50


Sarvodaya College of Computer Science Programming in Python

This produces:
 NameError

Global Variable
Declared outside function.
Accessible everywhere.

Example
x = 100
def show():
print(x)
show()

Output
100

Difference Between Local and Global Variable


Local Variable Global Variable
Inside function Outside function
Limited scope Accessible everywhere
Temporary Permanent during execution

6.10 global Keyword


Used to modify global variable inside function.

Example
x = 10
def change():
global x
x = 50
change()
print(x)

Output
50

Created by Rashesh Rehi 51


Sarvodaya College of Computer Science Programming in Python

6.11 Lambda Functions


Anonymous small functions.

Syntax
lambda arguments: expression

Example
square = lambda x: x * x
print(square(5))

Output
25

Advantages of Lambda
1. Short syntax
2. Useful in sorting/filtering
3. No need of def keyword

7. Specifications

A specification describes what a function or program does.


It explains:
 Purpose of function
 Input values
 Output values
 Working behavior
 Conditions and rules

Specifications help programmers understand how a function should be used


without reading the complete code.

Simple Meaning of Specification


A specification is like an instruction manual for a function.
Example:
 What function does

Created by Rashesh Rehi 52


Sarvodaya College of Computer Science Programming in Python

 What input it accepts


 What output it returns

Example
Suppose a medicine bottle contains:
 Medicine name
 Usage instructions
 Dosage
 Side effects
These details are specifications of medicine.
Similarly, Python function specifications explain function details.

Components of Specifications
A good specification contains:
1. Function Name
2. Purpose
3. Parameters
4. Return Value
5. Data Types
6. Conditions
7. Description

Example of Simple Specification


def add(a, b):
"""
This function adds two numbers
Input: two integers
Output: sum of numbers
"""
return a + b

7.1 Function Documentation


Documentation means writing information about function.
Python mainly uses:
 Comments
 Docstrings

Created by Rashesh Rehi 53


Sarvodaya College of Computer Science Programming in Python

Comments in Specification
# Function to calculate square
def square(n):
return n * n

Docstrings
Docstrings are multi-line strings written inside functions.
Used for professional documentation.

Syntax of Docstring
def function_name():
"""
Description
"""

Example
def greet(name):
"""
This function displays greeting message
"""
print("Hello", name)

7.2 Type Specifications


Specifications may describe data types.

Example
def multiply(a: int, b: int) -> int:
return a * b

Explanation
Part Meaning
a: int a should be integer
-> int returns integer

Created by Rashesh Rehi 54


Sarvodaya College of Computer Science Programming in Python

Advantages of Type Specification


1. Better readability
2. Easier debugging
3. Helps large projects

8. Recursion

Recursion is a programming technique in which a function calls itself repeatedly


to solve a problem.
A recursive function breaks a large problem into smaller subproblems of the same
type.

Simple Meaning of Recursion


A function calling itself is called recursion.

Real-Life Examples of Recursion


1. Mirrors facing each other
2. Family tree
3. Folder inside folder in computer
4. Countdown timer

Why Recursion is Important?


Recursion helps:
 Solve complex problems easily
 Reduce lengthy code
 Work with trees and graphs
 Solve mathematical problems

Created by Rashesh Rehi 55


Sarvodaya College of Computer Science Programming in Python

Recursion Working Diagram

8.1 Structure of Recursive Function


Every recursive function contains:
1. Base Case
2. Recursive Call

Base Case
Condition that stops recursion.
Without base case:
 Function runs forever
 Causes error

Recursive Call
Function calls itself with smaller problem.

General Syntax
def function_name(parameters):

if base_condition:
return value

return function_name(smaller_problem)

Created by Rashesh Rehi 56


Sarvodaya College of Computer Science Programming in Python

Example: Simple Recursion


def show(n):

if n == 0:
return
print(n)
show(n - 1)
show(5)

Output
5
4
3
2
1

Step-by-Step Working
Function Call Output
show(5) 5
show(4) 4
show(3) 3
show(2) 2
show(1) 1
show(0) Stop

8.2 Factorial Using Recursion


Factorial of number:
Example:
5! = 5 × 4 × 3 × 2 × 1

Recursive Program for Factorial


def factorial(n):
if n == 1:
return 1

Created by Rashesh Rehi 57


Sarvodaya College of Computer Science Programming in Python

return n * factorial(n - 1)
print(factorial(5))

Output
120

9. Modules

A module is a file containing Python code such as:


 Functions
 Variables
 Classes
 Statements

Modules help organize large programs into smaller and manageable parts.
Instead of writing all code in one file, Python allows dividing code into modules.

Simple Meaning of Module


A module is a Python file with .py extension that contains reusable code.
Example:
 [Link]
 [Link]

Why Modules are Important?


Modules help:
1. Reuse code
2. Reduce duplication
3. Organize programs
4. Improve readability
5. Simplify maintenance

Types of Modules
Python mainly provides:
1. Built-in Modules
2. User-defined Modules

Created by Rashesh Rehi 58


Sarvodaya College of Computer Science Programming in Python

9.1 Built-in Modules


Python already provides many ready-made modules.
Examples:
 math
 random
 os
 datetime
 statistics

Advantages of Built-in Modules


1. Save time
2. Reduce coding effort
3. Provide ready functions
4. Improve development speed

9.2 Importing Modules


To use module, we use:
 import keyword

Syntax
import module_name

Example
import math
print([Link](25))

Output
5.0

Explanation
Part Meaning
import Keyword
math Module name
sqrt() Function

Created by Rashesh Rehi 59


Sarvodaya College of Computer Science Programming in Python

9.3 Import Specific Functions


Instead of importing complete module, specific functions can be imported.

Syntax
from module_name import function_name

Example
from math import factorial
print(factorial(5))

Output
120

Advantages
1. Less typing
2. Faster access
3. Cleaner code

9.4 Import Multiple Functions

Example
from math import sqrt, factorial
print(sqrt(16))
print(factorial(4))

9.5 Using Alias Name


Alias means alternate short name.
Uses:
 Reduce long names
 Improve readability

Syntax
import module_name as alias

Example
import math as m

Created by Rashesh Rehi 60


Sarvodaya College of Computer Science Programming in Python

print([Link](49))

Output
7.0

9.6 dir() Function


dir() displays all functions and variables inside module.

Example
import math
print(dir(math))

Output
Displays all members of math module.

9.7 help() Function


Used to get documentation about module or function.

Example
import math
help([Link])

Advantages of help()
1. Understand functions
2. Learn parameters
3. View documentation

9.8 Common Built-in Modules

math Module
Provides mathematical functions.

Common Functions
Function Purpose
sqrt() Square root
factorial() Factorial

Created by Rashesh Rehi 61


Sarvodaya College of Computer Science Programming in Python

Function Purpose
pow() Power
ceil() Round up
floor() Round down

random Module
Used to generate random values.

Example
import random
print([Link](1, 10))

Common Functions
Function Purpose
randint() Random integer
random() Random float
choice() Random item

Example
import random
colors = ["Red", "Blue", "Green"]
print([Link](colors))

datetime Module
Used for date and time.

Example
import datetime
today = [Link]()
print(today)

9.9 User-Defined Modules


Users can create their own modules.

Created by Rashesh Rehi 62


Sarvodaya College of Computer Science Programming in Python

Steps to Create Module


1. Create Python file
2. Write functions
3. Save file
4. Import file

Example: Creating Module


File: [Link]

def add(a, b):


return a + b

def square(n):
return n * n

Using User-Defined Module


File: [Link]

import mymodule

print([Link](10, 20))
print([Link](5))

Output
30
25

Advantages of User-Defined Modules


1. Reusable code
2. Organized projects
3. Easy debugging
4. Team collaboration

9.10 name Variable


Python automatically creates:
 __name__

Created by Rashesh Rehi 63


Sarvodaya College of Computer Science Programming in Python

Used to check whether file runs directly or imported.

Example
if __name__ == "__main__":
print("Program running directly")

Importance
1. Avoid unwanted execution
2. Separate reusable code

9.11 Packages in Python


A package is collection of modules.
Folder containing modules is called package.

Package Structure
mypackage/
[Link]
[Link]

Advantages of Packages
1. Better organization
2. Large project management
3. Avoid naming conflicts

10. Files in Python

A file is used to store data permanently on a computer.


Normally, variables store data temporarily in memory.
When the program ends, data is lost.
Files allow data to be:
 Saved permanently
 Retrieved later
 Shared between programs

Created by Rashesh Rehi 64


Sarvodaya College of Computer Science Programming in Python

Real-Life Examples of Files


1. Text documents
2. Excel sheets
3. Images
4. Videos
5. Database files
6. Log files

Why File Handling is Important?


File handling helps:
1. Store large data
2. Save user information
3. Read previous records
4. Maintain databases
5. Process reports

File Handling Process

Steps of File Handling


Python file handling generally follows 3 steps:

Created by Rashesh Rehi 65


Sarvodaya College of Computer Science Programming in Python

1. Open File
2. Perform Operation
3. Close File

10.1 Opening a File


Python uses open() function to open files.

Syntax
file_object = open("filename", "mode")

Parameters
Parameter Meaning
filename Name of file
mode File operation mode

Example
file = open("[Link]", "r")

10.2 File Modes


File modes define operation type.

Common File Modes


Mode Meaning
r Read mode
w Write mode
a Append mode
x Create file
rb Read binary
wb Write binary
r+ Read and write

Read Mode (r)


Used to read file.

Created by Rashesh Rehi 66


Sarvodaya College of Computer Science Programming in Python

Example
file = open("[Link]", "r")

print([Link]())
[Link]()
Write Mode (w)
Creates new file or overwrites existing file.

Example
file = open("[Link]", "w")

[Link]("Welcome to Python")
[Link]()

Append Mode (a)


Adds data at end of file.

Example
file = open("[Link]", "a")

[Link]("\nPython Programming")
[Link]()

Exclusive Create Mode (x)


Creates new file.
If file exists:
 Error occurs

Example
file = open("[Link]", "x")
[Link]()

10.3 Closing a File


Files should be closed after use.

Created by Rashesh Rehi 67


Sarvodaya College of Computer Science Programming in Python

Syntax
[Link]()

Example
file = open("[Link]", "r")
print([Link]())
[Link]()

10.4 Reading File Data


Python provides multiple methods.

read() Method
Reads entire file.

Example
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

readline() Method
Reads one line at a time.

Example
file = open("[Link]", "r")
print([Link]())
[Link]()

readlines() Method
Reads all lines into list.

Example
file = open("[Link]", "r")
print([Link]())
[Link]()

Created by Rashesh Rehi 68


Sarvodaya College of Computer Science Programming in Python

Difference Between read(), readline(), readlines()


Method Description
read() Entire file
readline() Single line
readlines() All lines as list

10.5 Writing into File


write() method stores data into file.
Syntax
[Link](data)

Example
file = open("[Link]", "w")
[Link]("Ravi")
[Link]()

Writing Multiple Lines


file = open("[Link]", "w")
[Link]("Python\n")
[Link]("Java\n")
[Link]("C++")
[Link]()

10.6 with Statement


Python provides with statement for automatic closing.

Syntax
with open("[Link]", "mode") as file:
statements

Example
with open("[Link]", "r") as file:
print([Link]())

Advantages of with Statement


1. Automatic closing
Created by Rashesh Rehi 69
Sarvodaya College of Computer Science Programming in Python

2. Cleaner code
3. Better memory handling

10.7 File Pointer Functions


File pointer indicates current position.

tell() Function
Returns current position.

Example
file = open("[Link]", "r")
print([Link]())
[Link]()

seek() Function
Changes file pointer position.

Syntax
[Link](position)

Example
file = open("[Link]", "r")
[Link](2)
print([Link]())
[Link]()

10.8 Binary Files


Binary files store:
 Images
 Audio
 Videos
Use:
 rb
 wb modes

Created by Rashesh Rehi 70


Sarvodaya College of Computer Science Programming in Python

Example
file = open("[Link]", "rb")
data = [Link]()
[Link]()

10.9 Text Files vs Binary Files


Text File Binary File
Human readable Not readable
Stores text Stores bytes
.txt .jpg, .mp3

11. Tuples

A tuple is an ordered collection of elements in Python.

Tuples are similar to lists, but the main difference is:


 Tuples are immutable
 Lists are mutable

Immutable means:
 Values cannot be changed after creation

Simple Meaning of Tuple


A tuple is a collection of multiple items stored in a single variable using
parentheses ().

Example
numbers = (10, 20, 30)
print(numbers)

Output
(10, 20, 30)

Created by Rashesh Rehi 71


Sarvodaya College of Computer Science Programming in Python

Characteristics of Tuples
1. Ordered collection
2. Immutable
3. Allows duplicate values
4. Supports indexing
5. Supports slicing
6. Faster than lists

Tuple Structure Diagram

Why Tuples are Important?


Tuples are useful when:
 Data should not change
 Security is important
 Faster performance is needed

Real-Life Example
Examples of fixed data:
 Days of week
 Months of year
 GPS coordinates

Created by Rashesh Rehi 72


Sarvodaya College of Computer Science Programming in Python

 RGB color values


These values usually do not change, so tuples are suitable.

11.1 Creating Tuples


Tuples are created using parentheses ().

Example
data = (1, 2, 3)
print(data)

Tuple with Different Data Types


student = ("Ravi", 21, 85.5)
print(student)

Empty Tuple
t = ()
print(t)

Single Element Tuple


A comma is compulsory.

Correct Example
t = (5,)
print(type(t))

Wrong Example
t = (5)
print(type(t))

Output
<class 'int'>

Tuple Without Parentheses


Python also allows tuple packing.

Created by Rashesh Rehi 73


Sarvodaya College of Computer Science Programming in Python

Example
t = 1, 2, 3
print(t)

11.2 Tuple Packing and Unpacking

Tuple Packing
Storing multiple values into tuple.
data = 10, 20, 30

Tuple Unpacking
Extracting values from tuple.
a, b, c = (10, 20, 30)
print(a)
print(b)
print(c)

Output
10
20
30

11.3 Accessing Tuple Elements


Tuple elements are accessed using indexing.

Positive Indexing
Index starts from 0.

Example
t = ("Python", "Java", "C++")
print(t[0])
print(t[1])

Output
Python
Java

Created by Rashesh Rehi 74


Sarvodaya College of Computer Science Programming in Python

Negative Indexing
Value Python Java C++
Index -3 -2 -1

Example
t = ("Python", "Java", "C++")
print(t[-1])

Output
C++

11.4 Tuple Immutability


Tuples cannot be modified after creation.

Example
t = (10, 20, 30)
# t[0] = 100 ❌ Error

Error
TypeError

Why Tuples are Immutable?


1. Security
2. Faster processing
3. Prevent accidental changes

11.5 Tuple Operations

Concatenation
Joining tuples using +.

Example
a = (1, 2)
b = (3, 4)
print(a + b)

Created by Rashesh Rehi 75


Sarvodaya College of Computer Science Programming in Python

Output
(1, 2, 3, 4)

Membership Operators

Example
t = (10, 20, 30)
print(20 in t)

Output
True

11.6 Tuple Functions


Python provides built-in functions.

len()
Returns total elements.
t = (1, 2, 3)
print(len(t))

max()
Returns largest value.
t = (10, 50, 20)
print(max(t))

min()
Returns smallest value.
t = (10, 50, 20)
print(min(t))

sum()
Returns total sum.
t = (1, 2, 3)
print(sum(t))

Created by Rashesh Rehi 76


Sarvodaya College of Computer Science Programming in Python

sorted()
Returns sorted list.
t = (30, 10, 20)
print(sorted(t))

count()
Counts occurrences.
t = (1, 2, 2, 3)
print([Link](2))

index()
Returns index position.
t = (10, 20, 30)
print([Link](20))

11.7 Nested Tuples


Tuple inside another tuple.

Example
t = ((1, 2), (3, 4))
print(t[0])
print(t[1][1])

Output
(1, 2)
4

Advantages of Tuples
1. Faster execution
2. Data protection
3. Less memory usage
4. Useful for fixed data

Disadvantages of Tuples
1. Cannot modify elements
2. Fewer methods available

Created by Rashesh Rehi 77


Sarvodaya College of Computer Science Programming in Python

12. Lists and Mutability

A list is one of the most important data structures in Python.


A list is:
 Ordered collection
 Mutable
 Allows duplicate values
 Can store different data types
Lists are used to store multiple values in a single variable.

Simple Meaning of List


A list is a collection of items enclosed inside square brackets [].

Example
numbers = [10, 20, 30]
print(numbers)

Output
[10, 20, 30]

Characteristics of Lists
1. Ordered collection
2. Mutable
3. Allows duplicates
4. Dynamic size
5. Supports indexing and slicing

List Structure Diagram

Created by Rashesh Rehi 78


Sarvodaya College of Computer Science Programming in Python

Why Lists are Important?


Lists help:
1. Store multiple values
2. Process collections of data
3. Perform data manipulation
4. Create dynamic programs

12.1 Creating Lists


Lists are created using square brackets [].

Example
fruits = ["Apple", "Banana", "Mango"]
print(fruits)

List with Different Data Types


data = ["Python", 21, 85.5, True]
print(data)

Empty List
empty = []
print(empty)

Nested List
List inside another list.

Example
matrix = [[1, 2], [3, 4]]
print(matrix)

12.2 Accessing List Elements


Lists use indexing.

Positive Indexing
Index starts from 0.

Created by Rashesh Rehi 79


Sarvodaya College of Computer Science Programming in Python

Example
colors = ["Red", "Blue", "Green"]
print(colors[0])
print(colors[1])

Output
Red
Blue

Negative Indexing
Value Red Blue Green
Index -3 -2 -1

Example
colors = ["Red", "Blue", "Green"]
print(colors[-1])

Output
Green

12.3 List Slicing


Slicing extracts part of list.

Syntax
list[start:end]

Example
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])

Output
[20, 30, 40]

Reverse List
numbers = [1, 2, 3, 4]
print(numbers[::-1])

Created by Rashesh Rehi 80


Sarvodaya College of Computer Science Programming in Python

Output
[4, 3, 2, 1]

12.4 Mutability in Lists


Mutability means list elements can be changed after creation.

Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)

Output
[10, 50, 30]

Why Lists are Mutable?


1. Dynamic data handling
2. Easy updates
3. Flexible programming

12.5 List Operations

Concatenation
Joining lists using +.

Example
a = [1, 2]
b = [3, 4]
print(a + b)

Output
[1, 2, 3, 4]

Repetition
Using *.

Created by Rashesh Rehi 81


Sarvodaya College of Computer Science Programming in Python

Example
numbers = [1, 2]
print(numbers * 3)

Output
[1, 2, 1, 2, 1, 2]

Membership Operators

Example
numbers = [10, 20, 30]
print(20 in numbers)

Output
True

12.6 List Functions


Python provides built-in functions.

len()
Returns total elements.
numbers = [1, 2, 3]
print(len(numbers))

max()
Returns largest value.
numbers = [10, 50, 20]
print(max(numbers))

min()
Returns smallest value.
numbers = [10, 50, 20]
print(min(numbers))

sum()
Returns total sum.

Created by Rashesh Rehi 82


Sarvodaya College of Computer Science Programming in Python

numbers = [1, 2, 3]
print(sum(numbers))

sorted()
Returns sorted list.
numbers = [30, 10, 20]
print(sorted(numbers))

12.7 List Methods


Lists provide many useful methods.

append()
Adds item at end.
fruits = ["Apple"]
[Link]("Mango")
print(fruits)

extend()
Adds multiple items.
a = [1, 2]
[Link]([3, 4])
print(a)

insert()
Inserts item at specific position.
numbers = [1, 3]
[Link](1, 2)
print(numbers)

remove()
Removes specific item.
numbers = [10, 20, 30]
[Link](20)
print(numbers)

Created by Rashesh Rehi 83


Sarvodaya College of Computer Science Programming in Python

pop()
Removes item using index.
numbers = [10, 20, 30]
[Link](1)
print(numbers)

clear()
Removes all items.
numbers = [1, 2, 3]
[Link]()
print(numbers)

sort()
Sorts list.
numbers = [30, 10, 20]
[Link]()
print(numbers)

reverse()
Reverses list.
numbers = [1, 2, 3]
[Link]()
print(numbers)

count()
Counts occurrences.
numbers = [1, 2, 2, 3]
print([Link](2))

index()
Returns index position.
numbers = [10, 20, 30]
print([Link](20))

12.8 Nested Lists


List inside another list.

Created by Rashesh Rehi 84


Sarvodaya College of Computer Science Programming in Python

Example
matrix = [[1, 2], [3, 4]]
print(matrix[0])
print(matrix[1][1])

Output
[1, 2]
4

12.9 List Traversal


Traversal means accessing all elements one by one.

Using for Loop


numbers = [10, 20, 30]
for n in numbers:
print(n)

Using while Loop


numbers = [10, 20, 30]
i=0
while i < len(numbers):
print(numbers[i])
i += 1

12.10 List Comprehension


Short method to create lists.

Syntax
[expression for variable in sequence]

Example
squares = [x * x for x in range(5)]
print(squares)

Output
[0, 1, 4, 9, 16]

Created by Rashesh Rehi 85


Sarvodaya College of Computer Science Programming in Python

Advantages of List Comprehension


1. Short code
2. Faster execution
3. Better readability

12.11 Copying Lists

Direct Assignment
a = [1, 2, 3]
b=a
Both refer same list.

copy() Method
a = [1, 2, 3]
b = [Link]()
print(b)

13. Functions as Objects

In Python, functions are treated as objects.


This means:
 Functions can be stored in variables
 Functions can be passed as arguments
 Functions can be returned from other functions
 Functions can be stored inside data structures
Python is called a first-class function language because functions behave like
normal objects.

Simple Meaning
A function in Python is not just code.
It is also an object that can be used like variables and data.

Characteristics of Functions as Objects


Functions in Python can:
1. Be assigned to variables

Created by Rashesh Rehi 86


Sarvodaya College of Computer Science Programming in Python

2. Be passed to another function


3. Be returned from function
4. Be stored in lists/dictionaries

13.1 Function Assigned to Variable


Functions can be assigned to variables like numbers or strings.

Example
def greet():
print("Welcome")
x = greet
x()

Output
Welcome

Explanation
Part Meaning
greet Function object
x = greet Assign function
x() Call function

Important Note
Do not use parentheses while assigning function.

Correct:
x = greet

Wrong:
x = greet()

13.2 Functions as Arguments


Functions can be passed as arguments to other functions.

Created by Rashesh Rehi 87


Sarvodaya College of Computer Science Programming in Python

Example
def add(a, b):
return a + b
def calculate(func, x, y):
return func(x, y)
print(calculate(add, 5, 3))

Output
8

Explanation
Function Purpose
add Performs addition
calculate Receives function

Advantages
1. Flexible coding
2. Dynamic behavior
3. Code reuse

13.3 Functions Returning Functions


A function can return another function.

Example
def outer():
def inner():
print("Inner Function")
return inner
x = outer()
x()

Output
Inner Function

Explanation
1. outer() returns inner function

Created by Rashesh Rehi 88


Sarvodaya College of Computer Science Programming in Python

2. x stores returned function


3. x() calls inner()

14. Differences Between List and Tuple

Feature List Tuple


Symbol [] ()
Mutability Mutable Immutable
Speed Slower Faster
Memory Usage More memory Less memory
Methods More methods Fewer methods
Modification Allowed Not allowed
Security Less secure More secure

15. Dictionaries

A dictionary is a built-in data structure in Python used to store data in the form of:
 Key : Value pairs
Each value in dictionary is associated with a unique key.

Simple Meaning of Dictionary


A dictionary stores data like a real-world dictionary:
 Word → Meaning
Similarly in Python:
 Key → Value

Example
student = {
"name": "Ravi",
"age": 21,
"marks": 90
}
print(student)
Created by Rashesh Rehi 89
Sarvodaya College of Computer Science Programming in Python

Output
{'name': 'Ravi', 'age': 21, 'marks': 90}

Dictionary Structure Diagram

Why Dictionaries are Important?


Dictionaries help:
1. Store related data together
2. Access data quickly
3. Organize large information
4. Create efficient programs

Characteristics of Dictionaries
1. Store key-value pairs
2. Mutable
3. Unordered (older Python versions)
4. Keys must be unique
5. Values can be duplicated
6. Fast data access

15.1 Creating Dictionaries


Dictionaries use curly braces {}.

Created by Rashesh Rehi 90


Sarvodaya College of Computer Science Programming in Python

Syntax
dictionary = {
key1: value1,
key2: value2
}

Example
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2025
}
print(car)

Empty Dictionary
data = {}
print(data)

Dictionary with Different Data Types


info = {
"name": "Python",
"version": 3.12,
"popular": True
}
print(info)

15.2 Accessing Dictionary Elements


Dictionary values are accessed using keys.

Example
student = {
"name": "Ravi",
"marks": 90
}
print(student["name"])

Created by Rashesh Rehi 91


Sarvodaya College of Computer Science Programming in Python

Output
Ravi

Using get() Method


Safer method for access.

Example
student = {
"name": "Ravi"
}
print([Link]("name"))

Difference Between [] and get()


[] get()
Gives error if key missing Returns None
Faster Safer

Example of Missing Key


student = {
"name": "Ravi"
}
print([Link]("age"))

Output
None

15.3 Modifying Dictionaries


Dictionaries are mutable.
Values can be changed.

Example
student = {
"name": "Ravi",
"marks": 80
}

Created by Rashesh Rehi 92


Sarvodaya College of Computer Science Programming in Python

student["marks"] = 95
print(student)

Output
{'name': 'Ravi', 'marks': 95}

Adding New Elements


student = {
"name": "Ravi"
}
student["age"] = 21
print(student)

Output
{'name': 'Ravi', 'age': 21}

15.4 Removing Dictionary Elements

pop()
Removes specified key.

Example
student = {
"name": "Ravi",
"age": 21
}
[Link]("age")
print(student)

popitem()
Removes last inserted item.

Example
data = {
"a": 1,
"b": 2

Created by Rashesh Rehi 93


Sarvodaya College of Computer Science Programming in Python

}
[Link]()
print(data)

del Keyword
Deletes key or entire dictionary.

Example
student = {
"name": "Ravi",
"age": 21
}
del student["age"]
print(student)

clear()
Removes all items.

Example
student = {
"name": "Ravi"
}
[Link]()
print(student)

15.5 Dictionary Functions

len()
Returns total key-value pairs.
data = {
"a": 1,
"b": 2
}
print(len(data))

Created by Rashesh Rehi 94


Sarvodaya College of Computer Science Programming in Python

max()
Returns maximum key.
data = {
"a": 1,
"b": 2
}
print(max(data))

min()
Returns minimum key.
data = {
"a": 1,
"b": 2
}
print(min(data))

sorted()
Returns sorted keys.
data = {
"b": 2,
"a": 1
}
print(sorted(data))

15.6 Dictionary Methods

keys()
Returns all keys.
student = {
"name": "Ravi",
"age": 21
}
print([Link]())

values()
Returns all values.

Created by Rashesh Rehi 95


Sarvodaya College of Computer Science Programming in Python

student = {
"name": "Ravi",
"age": 21
}
print([Link]())

items()
Returns all key-value pairs.
student = {
"name": "Ravi",
"age": 21
}
print([Link]())

update()
Updates dictionary.
student = {
"name": "Ravi"
}
[Link]({"age": 21})
print(student)

copy()
Copies dictionary.
student = {
"name": "Ravi"
}
new_data = [Link]()
print(new_data)

15.7 Looping Through Dictionaries

Loop Through Items


student = {
"name": "Rashesh",
"marks": 90

Created by Rashesh Rehi 96


Sarvodaya College of Computer Science Programming in Python

}
for key, value in [Link]():
print(key, value)

15.8 Nested Dictionaries


Dictionary inside another dictionary.

Example
students = {
"student1": {
"name": "Ravi",
"marks": 90
},
"student2": {
"name": "Raj",
"marks": 85
}
}
print(students)

Access Nested Dictionary


print(students["student1"]["name"])

-----------**********----------

1 Mark Questions
1. What is Python?
2. What is indentation in Python?
3. What is a string?
4. What is recursion?
5. What is a module?
6. What is a tuple?
7. What is mutability?

Created by Rashesh Rehi 97


Sarvodaya College of Computer Science Programming in Python

8. What is a dictionary?
9. What is a function?
[Link] is a global variable?

2 Marks Questions
1. Explain features of Python.
2. Explain if-else statement with example.
3. Difference between for loop and while loop.
4. Explain local and global variables.
5. Explain recursion with example.
6. Explain file handling in Python.

5 Marks Questions
1. Explain basic elements of Python with examples.
2. Explain branching programs with suitable examples.
3. Explain strings and string operations in Python.
4. Explain iteration using for loop and while loop.
5. Explain functions and scoping in Python.
6. Explain recursion with suitable example.
7. Explain modules and file handling in Python.
8. Explain tuples, lists, and dictionaries with examples.

Practical Tasks
1. Program to check even or odd number.
2. Program using functions and recursion.
3. Program to read and write files.
4. Program demonstrating list operations.
5. Program demonstrating tuple operations.
6. Program using dictionary operations.

END OF UNIT 1

Created by Rashesh Rehi 98


Sarvodaya College of Computer Science Programming in Python

Unit 2: OOP using Python


1. Handling Exceptions

Introduction to Exception Handling


An exception is an error that occurs during the execution of a program.
When an error occurs:
 Program execution stops suddenly
 Normal flow of program is interrupted
Exception handling allows programmers to:
 Detect errors
 Handle errors properly
 Prevent program crash

Simple Meaning of Exception


An exception is an unexpected event or runtime error that occurs during program
execution.

Real-Life Example
Suppose:
 ATM machine has no cash
 Internet connection fails
 Wrong password entered
These are exceptional situations.
Similarly, programs may face exceptional situations during execution.

Why Exception Handling is Important?


Exception handling helps:
1. Prevent program crash
2. Improve reliability
3. Handle errors safely
4. Improve user experience
5. Continue program execution

Created by Rashesh Rehi 99


Sarvodaya College of Computer Science Programming in Python

Exception Handling Flow

Types of Errors in Python


Python mainly has two types of errors:
1. Syntax Errors
2. Exceptions (Runtime Errors)

Syntax Error
Occurs due to wrong Python syntax.

Example
print("Hello"

Output
SyntaxError

Runtime Error (Exception)


Occurs during execution.

Created by Rashesh Rehi 100


Sarvodaya College of Computer Science Programming in Python

Example
a = 10
b=0
print(a / b)

Output
ZeroDivisionError

Common Exceptions in Python


Exception Cause
ZeroDivisionError Division by zero
NameError Variable not defined
TypeError Wrong data type
ValueError Invalid value
IndexError Invalid index
KeyError Missing dictionary key
FileNotFoundError File missing

Example of Common Exceptions


numbers = [1, 2, 3]
print(numbers[5])

Output
IndexError

1.1 Exception Handling Using try and except


Python uses:
 try
 except
to handle exceptions.

Syntax
try:
statements

Created by Rashesh Rehi 101


Sarvodaya College of Computer Science Programming in Python

except:
statements

Working of try-except
1. Code inside try block executes.
2. If error occurs:
o Python jumps to except block.
3. Error handled safely.

Example
try:
a = 10
b=0
print(a / b)
except:
print("Cannot divide by zero")

Output
Cannot divide by zero

Advantages of try-except
1. Prevents crash
2. Improves reliability
3. Better user experience

try-except Flow Diagram

Created by Rashesh Rehi 102


Sarvodaya College of Computer Science Programming in Python

1.2 Handling Specific Exceptions


Specific exceptions can be handled separately.

Example
try:
number = int(input("Enter number: "))
print(number)
except ValueError:
print("Invalid Input")

Output Example
Invalid Input

Example with Multiple Exceptions


try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
except ZeroDivisionError:
print("Division by zero not allowed")
except ValueError:
print("Please enter valid number")

1.3 else Block


else executes when no exception occurs.

Syntax
try:
statements

except:
statements

else:
statements

Created by Rashesh Rehi 103


Sarvodaya College of Computer Science Programming in Python

Example
try:
a = 10
b=2

print(a / b)

except ZeroDivisionError:
print("Error")

else:
print("Division Successful")

Output
5.0
Division Successful

Working of else Block


Situation Result
Exception occurs else skipped
No exception else executes

1.4 finally Block


finally always executes whether exception occurs or not.

Syntax
try:
statements

except:
statements

finally:
statements

Created by Rashesh Rehi 104


Sarvodaya College of Computer Science Programming in Python

Example
try:

print(10 / 2)

except:
print("Error")

finally:
print("Program Finished")

Output
5.0
Program Finished

1.5 Raising Exceptions


Python allows creating exceptions manually using:
 raise

Syntax
raise ExceptionName

Example
age = -5

if age < 0:
raise ValueError("Age cannot be negative")

Output
ValueError: Age cannot be negative

Advantages of raise
1. Custom validation
2. Better security
3. Error control

Created by Rashesh Rehi 105


Sarvodaya College of Computer Science Programming in Python

1.6 User-Defined Exceptions


Programmers can create custom exceptions.

Syntax
class MyError(Exception):
pass

Example
class InvalidAgeError(Exception):
pass

age = -1

if age < 0:
raise InvalidAgeError("Invalid Age")

Output
InvalidAgeError: Invalid Age

1.7 Assertions
Assertions check conditions during execution.

Syntax
assert condition

Example
x = 10
assert x > 0
print("Valid")

Example with Error


x = -5
assert x > 0

Output
AssertionError

Created by Rashesh Rehi 106


Sarvodaya College of Computer Science Programming in Python

2. Exceptions as a Control Flow Mechanism

Normally, programs execute statements one after another in sequence.


However, sometimes the normal flow of a program changes due to:
 Errors
 Special conditions
 Unexpected situations

Exceptions can be used not only for handling errors, but also for controlling the
flow of a program.
This concept is called:

Exceptions as a Control Flow Mechanism


Simple Meaning
Using exceptions to change or control program execution flow is called exception-
based control flow.

Real-Life Example
Suppose:
 A road is blocked
 Traffic police redirects vehicles to another road
Here:
 Normal flow changes due to special condition
Similarly, exceptions redirect program execution to another block.

Control Flow Diagram

Created by Rashesh Rehi 107


Sarvodaya College of Computer Science Programming in Python

Normal Program Flow


Without exceptions:
print("Step 1")
print("Step 2")
print("Step 3")

Output
Step 1
Step 2
Step 3

Flow with Exception


print("Step 1")

print(10 / 0)

print("Step 3")

Output
ZeroDivisionError
Program stops immediately.

Using Exception Handling


try:

print("Step 1")
print(10 / 0)
print("Step 2")

except ZeroDivisionError:

print("Error Handled")

print("Program Continues")

Created by Rashesh Rehi 108


Sarvodaya College of Computer Science Programming in Python

Output
Step 1
Error Handled
Program Continues

Explanation
When exception occurs:
1. Normal flow stops
2. Control jumps to except block
3. Program continues after handling

3. Assertions

Introduction
Assertions are used in Python to:
Check whether a condition is true or false during program execution.
Assertions help programmers:
 Detect errors early
 Debug programs
 Validate conditions
If the condition is:
 True → Program con nues
 False → Program stops and raises an error

Why Assertions are Important?


Assertions help:
1. Detect bugs
2. Validate data
3. Improve debugging
4. Improve program reliability
5. Check logical conditions

Syntax of Assertion
assert condition

Created by Rashesh Rehi 109


Sarvodaya College of Computer Science Programming in Python

Example
x = 10
assert x > 0
print("Valid Number")

Output
Valid Number

Explanation
Condition:
x>0
is:
True
So:
 Program runs normally

What Happens if Condition is False?

Example
x = -5

assert x > 0
print("Valid Number")

Output
AssertionError

Explanation
Condition:
x>0
is:
False
So:
 AssertionError occurs

Created by Rashesh Rehi 110


Sarvodaya College of Computer Science Programming in Python

3.1 Assertion with Message


Custom message can be displayed.

Syntax
assert condition, "message"

Example
age = -1

assert age >= 0, "Age cannot be negative"

Output
AssertionError: Age cannot be negative

Example: Checking Marks


marks = 85
assert marks <= 100
print("Valid Marks")

Output
Valid Marks

Example: Invalid Marks


marks = 120
assert marks <= 100, "Marks cannot exceed 100"

Output
AssertionError: Marks cannot exceed 100

3.2 Assertions in Function


Assertions are often used inside functions.

Example
def divide(a, b):
assert b != 0, "Division by zero not allowed"

Created by Rashesh Rehi 111


Sarvodaya College of Computer Science Programming in Python

return a / b
print(divide(10, 2))

Output
5.0

Example with Error


print(divide(10, 0))

Output
AssertionError:
Division by zero not allowed

3.3 Assertions vs Exceptions


Assertions Exceptions
Used for debugging Used for error handling
Checks conditions Handles runtime errors
Raises AssertionError Raises different errors

3.4 Assertions in Loops

Example
numbers = [2, 4, 6]
for n in numbers:
assert n % 2 == 0
print("All numbers are even")

Output
All numbers are even

Example with Odd Number


numbers = [2, 5, 6]
for n in numbers:
assert n % 2 == 0, "Odd number found"

Created by Rashesh Rehi 112


Sarvodaya College of Computer Science Programming in Python

Output
AssertionError:
Odd number found

3.5 Advantages of Assertions


1. Easy debugging
2. Detect logical errors
3. Validate input
4. Improve code quality
5. Reduce hidden bugs

3.6 Limitations of Assertions


1. Not for handling all runtime errors
2. Stops program execution
3. Should not replace exception handling

4. Abstract Data Types and Classes

In Object-Oriented Programming (OOP), programs are designed using:


 Objects
 Classes
 Data structures
One important concept is:

Abstract Data Types (ADT)


ADT helps programmers represent real-world objects logically and safely.
Classes are used in Python to implement ADTs.

Simple Meaning of ADT


An Abstract Data Type defines:
 What operations can be performed
 Without showing internal implementation details

Created by Rashesh Rehi 113


Sarvodaya College of Computer Science Programming in Python

Real-Life Example
Suppose you use:
 ATM machine
 Mobile phone
 TV remote
You know:
 What operations to perform
But you do not know:
 Internal circuitry or implementation
Similarly:
 ADT hides internal details and shows only necessary operations.

Why ADTs are Important?


ADTs help:
1. Hide complexity
2. Improve security
3. Increase code reusability
4. Simplify programming
5. Improve maintenance

What is a Class?
A class is a blueprint or template used to create objects.
A class contains:
 Variables (data)
 Functions (methods)

Real-Life Example of Class


Class Objects
Car BMW, Audi
Student Ravi, Raj
Mobile Samsung, iPhone

Created by Rashesh Rehi 114


Sarvodaya College of Computer Science Programming in Python

Class Diagram

4.1 Creating a Class in Python

Syntax
class ClassName:
statements
Example
class Student:
name = "Ravi"
print([Link])

Output
Ravi

Explanation
Part Meaning
class Keyword
Student Class name
name Variable

Created by Rashesh Rehi 115


Sarvodaya College of Computer Science Programming in Python

4.2 Objects in Python


An object is an instance of a class.

Syntax
object_name = ClassName()

Example
class Car:
brand = "Toyota"
c1 = Car()
print([Link])

Output
Toyota

Class and Object Working


Class Object
Blueprint Real instance
Defines properties Uses properties

4.3 Constructor in Python


Constructor initializes object data automatically.
Python constructor:
init()

Syntax
class ClassName:
def __init__(self):
statements

Example
class Student:
def __init__(self):
print("Constructor Called")
s1 = Student()

Created by Rashesh Rehi 116


Sarvodaya College of Computer Science Programming in Python

Output
Constructor Called

Why Constructors are Important?


1. Initialize variables
2. Automatic setup
3. Simplify object creation

4.4 Instance Variables


Variables belonging to object.

Example
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
s1 = Student("Ravi", 21)
print([Link])
print([Link])

Output
Ravi
21

self Keyword
self refers to current object.

Explanation of self
Usage Meaning
[Link] Object variable
[Link] Current object's age

4.5 Methods in Classes


Functions inside class are called methods.

Created by Rashesh Rehi 117


Sarvodaya College of Computer Science Programming in Python

Example
class Calculator:
def add(self, a, b):
return a + b
c1 = Calculator()
print([Link](5, 3))

Output
8

4.6 Class Variables


Shared among all objects.

Example
class Student:

school = "ABC School"

s1 = Student()
s2 = Student()

print([Link])
print([Link])

Output
ABC School
ABC School

Difference Between Instance and Class Variables


Instance Variable Class Variable
Unique per object Shared by all objects
Uses self Defined directly

4.7 Abstract Class Concept


Python supports abstraction using:
 abc module

Created by Rashesh Rehi 118


Sarvodaya College of Computer Science Programming in Python

Example
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass

Advantages of Abstraction
1. Simplifies programs
2. Hides complexity
3. Improves security

Abstraction Diagram

4.8 ADT Example: Stack


Stack follows:
 LIFO (Last In First Out)
Operations:
 push()
 pop()

Created by Rashesh Rehi 119


Sarvodaya College of Computer Science Programming in Python

Stack Diagram

Stack Class Example


class Stack:

def __init__(self):

[Link] = []

def push(self, item):


[Link](item)

def pop(self):
return [Link]()

s = Stack()
[Link](10)
[Link](20)

print([Link]())

Output
20

Created by Rashesh Rehi 120


Sarvodaya College of Computer Science Programming in Python

5. Inheritance

Introduction to Inheritance
Inheritance is one of the most important concepts of Object-Oriented
Programming (OOP).
Inheritance allows:
 One class to acquire properties and methods of another class.
This helps:
 Reuse code
 Reduce duplication
 Build hierarchical relationships

Simple Meaning of Inheritance


Inheritance means:
 Child class uses features of parent class.

Real-Life Example
Suppose:
 Child inherits properties from parents.

Examples:
 Eye color
 Height
 Family name

Similarly in Python:
 Child class inherits variables and methods from parent class.

Why Inheritance is Important?


Inheritance helps:
1. Reuse existing code
2. Reduce repetition
3. Improve maintainability
4. Support hierarchical design
5. Simplify development

Created by Rashesh Rehi 121


Sarvodaya College of Computer Science Programming in Python

Parent and Child Classes


Term Meaning
Parent Class Base/Super class
Child Class Derived/Sub class

Example
class Parent:
pass

class Child(Parent):
pass

Explanation
 Child class inherits Parent class.

5.1 Syntax of Inheritance

Syntax
class Parent:
statements

class Child(Parent):
statements

Example
class Animal:

def sound(self):
print("Animal makes sound")

class Dog(Animal):
pass

d = Dog()
[Link]()

Created by Rashesh Rehi 122


Sarvodaya College of Computer Science Programming in Python

Output
Animal makes sound

Explanation
Dog inherits method from Animal class.

5.2 Advantages of Inheritance


1. Code Reusability
2. Faster Development
3. Better Organization
4. Easy Maintenance
5. Extensibility

5.3 Types of Inheritance


Python supports:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

5.4 Single Inheritance


One child inherits one parent.

Diagram

Created by Rashesh Rehi 123


Sarvodaya College of Computer Science Programming in Python

Example
class Father:

def show(self):

print("Father Class")

class Son(Father):

pass

s = Son()

[Link]()

Output
Father Class

5.5 Multiple Inheritance


One child inherits multiple parents.
Diagram

Created by Rashesh Rehi 124


Sarvodaya College of Computer Science Programming in Python

Example
class Father:
def skills1(self):
print("Driving")
class Mother:
def skills2(self):
print("Cooking")
class Child(Father, Mother):
pass
c = Child()
c.skills1()
c.skills2()

Output
Driving
Cooking

Advantages
1. Combine features from multiple classes
2. Better flexibility

5.6 Multilevel Inheritance


Inheritance chain of multiple levels.

Diagram

Created by Rashesh Rehi 125


Sarvodaya College of Computer Science Programming in Python

Example
class Grandfather:

def property1(self):
print("Land")
class Father(Grandfather):
def property2(self):
print("House")

class Son(Father):
pass
s = Son()
s.property1()
s.property2()

Output
Land
House

5.7 Hierarchical Inheritance


Multiple child classes inherit same parent.

Diagram

Created by Rashesh Rehi 126


Sarvodaya College of Computer Science Programming in Python

Example
class Parent:
def show(self):
print("Parent Class")

class Child1(Parent):
pass

class Child2(Parent):
pass

c1 = Child1()
c2 = Child2()

[Link]()
[Link]()

Output
Parent Class
Parent Class

5.8 Hybrid Inheritance


Combination of different inheritance types.

Example Structure
class A:
pass

class B(A):
pass

class C(A):
pass

class D(B, C):


pass

Created by Rashesh Rehi 127


Sarvodaya College of Computer Science Programming in Python

Hybrid Inheritance Diagram

5.9 Method Overriding


Child class redefines parent method.
Example
class Animal:

def sound(self):
print("Animal Sound")

class Dog(Animal):

def sound(self):
print("Bark")
d = Dog()
[Link]()

Output
Bark

Created by Rashesh Rehi 128


Sarvodaya College of Computer Science Programming in Python

5.10 super() Function


Used to access parent class methods.

Syntax
super().method_name()

Example
class Parent:

def show(self):
print("Parent Method")

class Child(Parent):

def show(self):
super().show()
print("Child Method")

c = Child()
[Link]()

Output
Parent Method
Child Method

6. Encapsulation and Information Hiding

Introduction
Encapsulation and Information Hiding are important concepts of Object-Oriented
Programming (OOP).

These concepts help:


 Protect data
 Improve security
 Organize programs properly

Created by Rashesh Rehi 129


Sarvodaya College of Computer Science Programming in Python

Encapsulation combines:
 Data
 Methods

into a single unit called:


Class
Information hiding restricts direct access to sensitive data.

Simple Meaning of Encapsulation

Encapsulation means:
Wrapping data and functions together into one unit.

That unit is called:


 Class

Simple Meaning of Information Hiding

Information hiding means:


Restricting direct access to internal data.

Real-Life Example
Suppose:
 ATM machine hides internal banking process
 Mobile phone hides hardware circuitry

Users can:
 Use functions
But cannot:
 Access internal implementation
This is encapsulation and information hiding.

Created by Rashesh Rehi 130


Sarvodaya College of Computer Science Programming in Python

Encapsulation Diagram

Why Encapsulation is Important?


Encapsulation helps:
1. Protect data
2. Prevent accidental modification
3. Improve security
4. Increase maintainability
5. Improve modularity

6.1 Encapsulation in Python


Python achieves encapsulation using:
 Classes
 Objects

Example
class Student:
def __init__(self):
[Link] = "Ravi"
def display(self):
print([Link])

Created by Rashesh Rehi 131


Sarvodaya College of Computer Science Programming in Python

s1 = Student()
[Link]()

Output
Ravi

Explanation
Part Meaning
name Data
display() Method
Student Encapsulated unit

Encapsulation Working
 Data and methods are combined together.

6.2 Data Members and Methods


Encapsulation combines:
1. Data Members (Variables)
2. Member Functions (Methods)

Example
class Car:

def __init__(self):
[Link] = "Toyota"

def show(self):
print([Link])

6.3 Information Hiding


Information hiding protects internal data from direct access.
Python uses:
 Access modifiers

Created by Rashesh Rehi 132


Sarvodaya College of Computer Science Programming in Python

Types of Access Modifiers


Modifier Symbol Access
Public No underscore Accessible everywhere
Protected _single underscore Internal use
Private __double underscore Restricted access

6.4 Public Members


Accessible from anywhere.

Example
class Student:

def __init__(self):
[Link] = "Ravi"

s1 = Student()
print([Link])

Output
Ravi

6.5 Protected Members


Protected members use:
 Single underscore _
Used for:
 Internal class/subclass access

Example
class Student:
def __init__(self):
self._marks = 90
s1 = Student()
print(s1._marks)

Output
90
Created by Rashesh Rehi 133
Sarvodaya College of Computer Science Programming in Python

Important Note
Protected members:
 Can still be accessed
 But should not be accessed directly

6.6 Private Members


Private members use:
 Double underscore __
Used for strong information hiding.

Example
class Bank:

def __init__(self):
self.__balance = 1000

b1 = Bank()
# print(b1.__balance) ❌Error

Output
AttributeError

6.7 Accessing Private Members


Private members can be accessed using methods.

Example
class Bank:

def __init__(self):
self.__balance = 5000

def show_balance(self):

print(self.__balance)
b1 = Bank()
b1.show_balance()

Created by Rashesh Rehi 134


Sarvodaya College of Computer Science Programming in Python

Output
5000

Getter and Setter Methods


Used to:
 Access private data safely
 Modify private data safely

6.8 Getter Method


Returns private value.

Example
class Student:

def __init__(self):
self.__marks = 80

def get_marks(self):
return self.__marks

s1 = Student()
print(s1.get_marks())

Output
80

6.9 Setter Method


Changes private value safely.

Example
class Student:

def __init__(self):
self.__marks = 0
def set_marks(self, m):
if m >= 0:

Created by Rashesh Rehi 135


Sarvodaya College of Computer Science Programming in Python

self.__marks = m
def get_marks(self):
return self.__marks

s1 = Student()
s1.set_marks(95)
print(s1.get_marks())

Output
95

Advantages of Getter and Setter


1. Validation possible
2. Better security
3. Controlled access

6.10 Name Mangling in Python


Python internally changes private variable name.

Example
class Demo:

def __init__(self):
self.__value = 10

d = Demo()
print(d._Demo__value)

Output
10

Explanation
Python converts:
 __value
to:
 _Demo__value

Created by Rashesh Rehi 136


Sarvodaya College of Computer Science Programming in Python

This process is called:


Name Mangling

6.11 Advantages of Encapsulation


1. Data protection
2. Better security
3. Easy maintenance
4. Improved modularity
5. Controlled access

6.12 Disadvantages of Encapsulation


1. More code writing
2. Slight complexity increase

6.13 Encapsulation vs Information Hiding


Encapsulation Information Hiding
Combines data and methods Restricts access
Uses classes Uses access modifiers
Focuses organization Focuses protection

7. Search Algorithms and Sorting Algorithms

Introduction
In computer programming, data must often be:
 Searched
 Arranged
Searching helps:
 Find required data
Sorting helps:
 Arrange data in proper order
These operations are very important in:
 Databases
 Software applications
 Data analysis

Created by Rashesh Rehi 137


Sarvodaya College of Computer Science Programming in Python

 Artificial Intelligence

Simple Meaning
Concept Purpose
Searching Finding data
Sorting Arranging data

Real-Life Examples
Searching
 Finding contact number in mobile
 Searching student roll number
 Searching product online

Sorting
 Arranging books alphabetically
 Ranking students by marks
 Sorting prices low to high

PART 1: SEARCH ALGORITHMS

Introduction to Searching
Searching means:
Finding a specific element from collection of data.

Types of Searching Algorithms


1. Linear Search
2. Binary Search

7.1 Linear Search


Linear search checks elements one by one.

Working
1. Start from first element
2. Compare target value
3. Continue until element found

Created by Rashesh Rehi 138


Sarvodaya College of Computer Science Programming in Python

Linear Search Diagram

Algorithm of Linear Search


1. Start from first element
2. Compare with target
3. If found → stop
4. Otherwise move next
5. Repeat until end

Example
List:
[10, 20, 30, 40, 50]
Search:
 30

Program
numbers = [10, 20, 30, 40, 50]
search = 30
found = False

Created by Rashesh Rehi 139


Sarvodaya College of Computer Science Programming in Python

for i in numbers:
if i == search:
found = True
break
if found:
print("Element Found")
else:
print("Element Not Found")

Output
Element Found

Advantages of Linear Search


1. Simple
2. Easy implementation
3. Works on unsorted data

Disadvantages
1. Slow for large data
2. More comparisons

7.2 Binary Search


Binary search works only on:

Sorted data
It repeatedly divides data into halves.

Working
1. Find middle element
2. Compare target
3. Search left or right half
4. Repeat until found

Created by Rashesh Rehi 140


Sarvodaya College of Computer Science Programming in Python

Binary Search Diagram

Binary Search Formula


Middle Index Formula:
mid=low+high2mid = \frac{low + high}{2}mid=2low+high

Example
Sorted List:
[10, 20, 30, 40, 50]
Search:
 40

Created by Rashesh Rehi 141


Sarvodaya College of Computer Science Programming in Python

Program
numbers = [10, 20, 30, 40, 50]
search = 40
low = 0
high = len(numbers) - 1
found = False

while low <= high:


mid = (low + high) // 2
if numbers[mid] == search:
found = True
break
elif numbers[mid] < search:
low = mid + 1
else:
high = mid - 1
if found:
print("Element Found")
else:
print("Element Not Found")

Output
Element Found

Advantages of Binary Search


1. Faster than linear search
2. Efficient for large data

Disadvantages
1. Requires sorted data
2. Slightly complex

Created by Rashesh Rehi 142


Sarvodaya College of Computer Science Programming in Python

PART 2: SORTING ALGORITHMS

Introduction to Sorting
Sorting means:
Arranging data in ascending or descending order.
Types of Sorting
1. Bubble Sort
2. Selection Sort
3. Insertion Sort

7.3 Bubble Sort


Bubble sort repeatedly swaps adjacent elements.
Largest element moves to end like bubble.

Bubble Sort Diagram

Created by Rashesh Rehi 143


Sarvodaya College of Computer Science Programming in Python

Bubble Sort Algorithm


1. Compare adjacent elements
2. Swap if wrong order
3. Repeat passes
4. Continue until sorted

Example
numbers = [5, 2, 8, 1]
n = len(numbers)
for i in range(n):
for j in range(0, n-i-1):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
print(numbers)

Output
[1, 2, 5, 8]

Advantages
1. Simple
2. Easy understanding

Disadvantages
1. Slow for large data
2. Many swaps

7.4 Selection Sort


Selection sort repeatedly selects smallest element.

Working
1. Find minimum value
2. Swap with first position
3. Repeat remaining list

Created by Rashesh Rehi 144


Sarvodaya College of Computer Science Programming in Python

Selection Sort Diagram

Program
numbers = [64, 25, 12, 22, 11]
n = len(numbers)
for i in range(n):
min_index = i
for j in range(i+1, n):
if numbers[j] < numbers[min_index]:
min_index = j
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
print(numbers)

Output
[11, 12, 22, 25, 64]

Advantages
1. Simple implementation
2. Less swapping

Created by Rashesh Rehi 145


Sarvodaya College of Computer Science Programming in Python

Disadvantages
1. Slow for large data

7.5 Insertion Sort


Insertion sort inserts element into correct position.

Real-Life Example
Playing cards arrangement.

Insertion Sort Diagram

Program
numbers = [12, 11, 13, 5, 6]

for i in range(1, len(numbers)):


key = numbers[i]
j=i-1

Created by Rashesh Rehi 146


Sarvodaya College of Computer Science Programming in Python

while j >= 0 and key < numbers[j]:


numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
print(numbers)

Output
[5, 6, 11, 12, 13]

Advantages
1. Efficient for small data
2. Stable sorting

Disadvantages
1. Slow for large data

Built-in Sorting in Python


Python provides:
 sort()
 sorted()

sort()
Sorts original list.
numbers = [5, 2, 8]
[Link]()
print(numbers)

sorted()
Returns new sorted list.
numbers = [5, 2, 8]
print(sorted(numbers))

Reverse Sorting
numbers = [1, 2, 3]
[Link](reverse=True)
print(numbers)

Created by Rashesh Rehi 147


Sarvodaya College of Computer Science Programming in Python

Output
[3, 2, 1]

8. Hashtables

Introduction to Hashtables
A Hashtable is a data structure used to store:
 Key-value pairs

It allows:
 Fast searching
 Fast insertion
 Fast deletion

Hashtables are one of the most efficient data structures in computer science.
In Python, dictionaries are implemented using hashtable concepts.

Simple Meaning of Hashtable


A hashtable stores data using:
Key → Value mapping

Each key is converted into an index using:


Hash Function

Real-Life Example
Suppose a library stores books using:
 Book ID → Book details

Instead of searching every book one by one:


 System directly jumps to required location.
This is similar to hashtable working.

Created by Rashesh Rehi 148


Sarvodaya College of Computer Science Programming in Python

Hashtable Diagram

Why Hashtables are Important?


Hashtables help:
1. Fast data access
2. Efficient searching
3. Quick insertion
4. Better performance
5. Database indexing

8.1 Components of Hashtable


A hashtable mainly contains:
1. Keys
2. Values
3. Hash Function
4. Hash Table Array

Created by Rashesh Rehi 149


Sarvodaya College of Computer Science Programming in Python

Keys
Unique identifiers.

Examples:
 Student ID
 Username
 Product code

Values
Actual stored data.

Examples:
 Student details
 Product information

Hash Function
Converts key into index position.

Hashing Process Diagram

Created by Rashesh Rehi 150


Sarvodaya College of Computer Science Programming in Python

8.2 Working of Hashtable


Steps:
1. Key provided
2. Hash function calculates index
3. Value stored at index
4. Retrieval uses same hash function

Example
student = {
"101": "Ravi",
"102": "Raj"
}
print(student["101"])

Output
Ravi

Explanation
Python internally uses hashing to access value quickly.

8.3 Hash Function


Hash function converts key into integer index.

Example Using hash()


Python provides built-in:
 hash()

Example
print(hash("Python"))

Output Example
-145632478

Important Note
Hash values may vary on different systems.

Created by Rashesh Rehi 151


Sarvodaya College of Computer Science Programming in Python

8.4 Collision in Hashtable


Collision occurs when:
Two keys generate same index.

Example
Suppose:
Key Hash Index
15 5
25 5

Both stored at same location.


This creates:
Collision

8.5 Collision Resolution Techniques


Main methods:
1. Chaining
2. Open Addressing

8.6 Python Dictionaries and Hashtable


Python dictionaries internally use:
Hash Tables

Example
student = {
"name": "Ravi",
"age": 21
}
print(student["name"])

Advantages of Python Dictionary


1. Fast searching
2. Fast insertion
3. Efficient storage

Created by Rashesh Rehi 152


Sarvodaya College of Computer Science Programming in Python

8.7 Hashtable Operations


Main operations:
1. Insertion
2. Searching
3. Deletion

Insertion
Store key-value pair.

Example
data = {}
data["id"] = 101
print(data)

Searching
Retrieve value using key.

Example
student = {
"name": "Ravi"
}
print(student["name"])

Deletion
Remove key-value pair.

Example
student = {
"name": "Ravi"
}
del student["name"]
print(student)

8.8 Advantages of Hashtables


1. Very fast searching
2. Fast insertion

Created by Rashesh Rehi 153


Sarvodaya College of Computer Science Programming in Python

3. Efficient for large data


4. Flexible key usage

8.9 Disadvantages of Hashtables


1. Collision handling needed
2. More memory usage
3. Complex implementation

----------**********----------

1 Mark Questions
1. What is exception handling?
2. What is try block?
3. What is except block?
4. What is assertion?
5. What is a class?
6. What is an object?
7. What is inheritance?
8. What is encapsulation?
9. What is information hiding?
[Link] is a search algorithm?
[Link] is linear search?
[Link] is binary search?
[Link] is sorting?
[Link] is bubble sort?
[Link] is a hashtable?

2 Marks Questions
1. Explain exception handling in Python.
2. Explain assertions with example.
3. Explain abstract data types.
4. Explain classes and objects.

Created by Rashesh Rehi 154


Sarvodaya College of Computer Science Programming in Python

5. Explain inheritance in Python.


6. Explain encapsulation and information hiding.
7. Difference between linear search and binary search.
8. Explain bubble sort algorithm.
9. Explain selection sort algorithm.
[Link] hashtables in Python.

5 Marks Questions
1. Explain exception handling with suitable example.
2. Explain exceptions as a control flow mechanism.
3. Explain assertions in Python with example.
4. Explain abstract data types and classes.
5. Explain inheritance with suitable example.
6. Explain encapsulation and information hiding.
7. Explain linear search and binary search algorithms.
8. Explain sorting algorithms with examples.
9. Explain bubble sort and selection sort.
[Link] hashtables with suitable examples.

Practical Tasks
1. Program using try-except block.
2. Program demonstrating assertion.
3. Program creating class and object.
4. Program demonstrating inheritance.
5. Program demonstrating encapsulation.
6. Program implementing linear search.
7. Program implementing binary search.
8. Program implementing bubble sort.
9. Program implementing selection sort.
10. Program using dictionary as hashtable.

END OF UNIT 2

Created by Rashesh Rehi 155


Sarvodaya College of Computer Science Programming in Python

Unit 3: Plotting using PyLab


1. Plotting using PyLab

Introduction to PyLab
PyLab is a Python module used for:
 Data visualization
 Mathematical plotting
 Scientific computing

PyLab combines features of:


 NumPy
 Matplotlib

Using PyLab, programmers can create:


 Graphs
 Charts
 Scientific plots
very easily.

Simple Meaning
PyLab is used to:
Draw graphs and visualize data in Python.

Why Plotting is Important?


Graphs help:
1. Understand data easily
2. Compare values visually
3. Analyze trends
4. Detect patterns
5. Present reports clearly

Real-Life Examples
1. Student result analysis
2. Weather forecasting

Created by Rashesh Rehi 156


Sarvodaya College of Computer Science Programming in Python

3. Stock market analysis


4. Sales reports
5. Scientific research

Graph Visualization Diagram

What is Matplotlib?
Matplotlib is a Python plotting library used to create:
 2D graphs
 Charts
 Visualizations
PyLab uses matplotlib internally.

Installation of Matplotlib
If matplotlib is not installed:

Installation Command
pip install matplotlib

Importing PyLab
from pylab import *

Created by Rashesh Rehi 157


Sarvodaya College of Computer Science Programming in Python

Recommended Import Method


import [Link] as plt

Why Use pyplot?


It provides:
1. Easy plotting functions
2. Better readability
3. Industry-standard plotting

1.1 Basic Plotting


Basic plotting means drawing simple graph.

Syntax
plot(x, y)
show()

Explanation
Function Purpose
plot() Draw graph
show() Display graph

Example
from pylab import *

x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plot(x, y)
show()

Output
Line graph displayed.

Created by Rashesh Rehi 158


Sarvodaya College of Computer Science Programming in Python

2. Plotting Mortgages and Extended Examples

Introduction
Mortgage plotting means using Python graphs to understand loan repayment.
A mortgage is a loan taken to buy property, usually a house. The borrower repays
the loan through monthly payments.
Plotting helps us understand:
 Monthly payment
 Total payment
 Interest amount
 Principal amount
 Remaining balance
 Comparison between loans

Simple Meaning
Mortgage plotting means:
Drawing graphs for loan repayment data.

Why Mortgage Plotting is Useful?


Mortgage plotting helps to:
1. Understand loan cost clearly
2. Compare different interest rates
3. Compare different loan terms
4. Analyze total interest paid
5. Understand balance reduction over time

Basic Mortgage Terms


Term Meaning
Principal Original loan amount
Interest Rate Extra amount charged by bank
Term Loan duration
EMI / Monthly Payment Monthly amount paid
Balance Remaining loan amount
Total Interest Extra amount paid above principal

Created by Rashesh Rehi 159


Sarvodaya College of Computer Science Programming in Python

Mortgage Payment Formula


M=P×r(1+r)n(1+r)n−1M = P \times \frac{r(1+r)^n}{(1+r)^n -
1}M=P×(1+r)n−1r(1+r)n

Where:
Symbol Meaning
M Monthly payment
P Principal loan amount
r Monthly interest rate
n Total number of months

Example
If:
 Loan amount = ₹10,00,000
 Annual interest = 8%
 Loan term = 10 years
Then:
 Monthly rate = 8 / 12 / 100
 Months = 10 × 12

Program 1: Calculate Monthly Mortgage Payment


from pylab import *

principal = 1000000
annual_rate = 8
years = 10

monthly_rate = annual_rate / 12 / 100


months = years * 12

payment = principal * (monthly_rate * (1 + monthly_rate) ** months) / ((1 +


monthly_rate) ** months - 1)

print("Monthly Payment:", round(payment, 2))

Created by Rashesh Rehi 160


Sarvodaya College of Computer Science Programming in Python

Output
Monthly Payment: 12132.76

Explanation
This program calculates the fixed monthly amount paid by borrower.

Program 2: Plot Remaining Loan Balance


from pylab import *

principal = 1000000
annual_rate = 8
years = 10

monthly_rate = annual_rate / 12 / 100


months = years * 12

payment = principal * (monthly_rate * (1 + monthly_rate) ** months) / ((1 +


monthly_rate) ** months - 1)

balance = principal
balances = []

for month in range(1, months + 1):


interest = balance * monthly_rate
principal_paid = payment - interest
balance = balance - principal_paid
[Link](balance)

plot(range(1, months + 1), balances)


xlabel("Month")
ylabel("Remaining Balance")
title("Mortgage Balance Over Time")
grid(True)
show()

Created by Rashesh Rehi 161


Sarvodaya College of Computer Science Programming in Python

Graph Meaning
The graph shows how loan balance decreases month by month.
At first:
 Balance decreases slowly
Later:
 Balance decreases faster
Reason:
 Early payments include more interest
 Later payments include more principal

Mortgage Balance Diagram

Program 3: Plot Interest Paid and Principal Paid


from pylab import *

principal = 1000000
annual_rate = 8
years = 10
monthly_rate = annual_rate / 12 / 100

Created by Rashesh Rehi 162


Sarvodaya College of Computer Science Programming in Python

months = years * 12

payment = principal * (monthly_rate * (1 + monthly_rate) ** months) / ((1 +


monthly_rate) ** months - 1)

balance = principal

interest_list = []
principal_list = []

for month in range(1, months + 1):


interest = balance * monthly_rate
principal_paid = payment - interest
balance = balance - principal_paid

interest_list.append(interest)
principal_list.append(principal_paid)

plot(range(1, months + 1), interest_list, label="Interest Paid")


plot(range(1, months + 1), principal_list, label="Principal Paid")

xlabel("Month")
ylabel("Amount")
title("Interest and Principal Payment")
legend()
grid(True)

show()

Explanation
This graph shows:
 Interest part decreases over time
 Principal part increases over time

This is called:
Amortization

Created by Rashesh Rehi 163


Sarvodaya College of Computer Science Programming in Python

3. Fibonacci Sequence Revisited

Introduction
The Fibonacci Sequence is one of the most famous mathematical sequences used
in:
 Mathematics
 Computer Science
 Algorithms
 Nature
 Artificial Intelligence

In this topic, we revisit Fibonacci sequence using:


 Python programming
 Plotting
 Recursion
 Iteration

What is Fibonacci Sequence?


A Fibonacci sequence is a series of numbers where:
Each number is the sum of previous two numbers.

Fibonacci Sequence Example


0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Why Fibonacci Sequence is Important?


Fibonacci sequence is used in:
1. Algorithms
2. Dynamic programming
3. Data structures
4. AI and ML
5. Financial analysis
6. Nature modeling

3.1 Fibonacci Using Iteration


Iteration means:
 Using loops

Created by Rashesh Rehi 164


Sarvodaya College of Computer Science Programming in Python

This is one of the most efficient methods.

Algorithm
1. Start with 0 and 1
2. Add previous two numbers
3. Print result
4. Repeat

Program
n = 10
a=0
b=1

print(a)
print(b)

for i in range(2, n):


c=a+b
print(c)
a=b
b=c

Output
0
1
1
2
3
5
8
13
21
34

Created by Rashesh Rehi 165


Sarvodaya College of Computer Science Programming in Python

Explanation
Variable Meaning
a Previous value
b Current value
c Next value

Advantages of Iteration
1. Faster execution
2. Less memory usage
3. Simple implementation

3.2 Fibonacci Using Recursion


Recursion means:
 Function calling itself

Program
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

for i in range(10):
print(fib(i))

Output
0
1
1
2
3
5
8
13
Created by Rashesh Rehi 166
Sarvodaya College of Computer Science Programming in Python

21
34

3.3 Plotting Fibonacci Sequence


PyLab can visualize Fibonacci growth.

Program
from pylab import *

n = 10
fib = [0, 1]

for i in range(2, n):


[Link](fib[i-1] + fib[i-2])

plot(range(n), fib)
xlabel("Position")
ylabel("Fibonacci Number")
title("Fibonacci Sequence")
grid(True)
show()

Output
Fibonacci graph displayed.

4. Dynamic Programming and the 0/1 Knapsack Algorithm

Introduction
Dynamic Programming (DP) is an important problem-solving technique used in:
 Algorithms
 Artificial Intelligence
 Optimization
 Data Science

Dynamic programming helps solve complex problems by:

Created by Rashesh Rehi 167


Sarvodaya College of Computer Science Programming in Python

 Breaking them into smaller subproblems


 Solving each subproblem once
 Reusing previous results
One famous application of dynamic programming is:
0/1 Knapsack Algorithm

Simple Meaning of Dynamic Programming


Dynamic Programming means:
Solving big problems using solutions of smaller problems.

Real-Life Example
Suppose a student prepares notes for exams.
Instead of studying same topic repeatedly:
 Student saves notes
 Reuses them later
Similarly:
 Dynamic programming stores previous solutions.

Dynamic Programming Diagram

Why Dynamic Programming is Important?


Dynamic programming helps:
1. Reduce repeated calculations
2. Improve speed
3. Save computation time
4. Solve optimization problems
5. Handle large problems efficiently
Created by Rashesh Rehi 168
Sarvodaya College of Computer Science Programming in Python

4.1 Approaches of Dynamic Programming


Two major approaches:
1. Memoization (Top-Down)
2. Tabulation (Bottom-Up)

Memoization
Stores recursive results.

Example
memo = {}

def fib(n):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
print(fib(10))

Output
55

Advantages of Memoization
1. Faster recursion
2. Avoid repeated calculations
3. Better performance

Tabulation
Builds solution from smallest values upward.

Example
def fib(n):
dp = [0] * (n + 1)
dp[1] = 1

Created by Rashesh Rehi 169


Sarvodaya College of Computer Science Programming in Python

for i in range(2, n + 1):


dp[i] = dp[i-1] + dp[i-2]
return dp[n]
print(fib(10))

Output
55

Advantages of Tabulation
1. Faster execution
2. No recursion overhead
3. Better memory control

Difference Between Memoization and Tabulation


Memoization Tabulation
Top-down Bottom-up
Uses recursion Uses loops
Stores recursive calls Builds table directly

4.2 What is Knapsack Problem?


Knapsack problem is a famous optimization problem.
Suppose:
 A bag has limited capacity
 Items have:
o Weight
o Profit
Goal:
Maximize profit without exceeding capacity.

Real-Life Example
Suppose a thief steals items:
 Gold
 Laptop
 Mobile
But bag capacity is limited.

Created by Rashesh Rehi 170


Sarvodaya College of Computer Science Programming in Python

The thief must choose:


 Most valuable combination

Knapsack Diagram

0/1 Knapsack
Item is either:
 Taken completely
OR
 Not taken
No partial selection allowed.

Why Called 0/1?


Value Meaning
0 Item not selected
1 Item selected

Created by Rashesh Rehi 171


Sarvodaya College of Computer Science Programming in Python

4.3 Problem Statement of 0/1 Knapsack


Given:
 Weights
 Values
 Capacity
Find:
Maximum profit
without exceeding capacity.

Example
Item Weight Profit
1 1 10
2 3 40
3 4 50
4 5 70
Capacity:
 8

Goal
Choose items giving maximum profit.

4.4 Recursive Solution of Knapsack


Two choices:
1. Include item
2. Exclude item

Program: Recursive Knapsack


def knapsack(W, wt, val, n):
if n == 0 or W == 0:
return 0

if wt[n-1] > W:
return knapsack(W, wt, val, n-1)
else:
include = val[n-1] + knapsack(W-wt[n-1], wt, val, n-1)

Created by Rashesh Rehi 172


Sarvodaya College of Computer Science Programming in Python

exclude = knapsack(W, wt, val, n-1)


return max(include, exclude)

values = [10, 40, 50, 70]


weights = [1, 3, 4, 5]
capacity = 8
n = len(values)
print(knapsack(capacity, weights, values, n))

Output
110

Explanation
Maximum profit:
 40 + 70 = 110

Problem with Recursive Method


1. Repeated calculations
2. Slow performance

Solution:
Dynamic Programming

4.5 Dynamic Programming Solution of Knapsack


DP stores already calculated values.

Program: DP Knapsack
def knapsack(W, wt, val, n):
dp = [[0 for x in range(W + 1)] for x in range(n + 1)]

for i in range(n + 1):


for w in range(W + 1):
if i == 0 or w == 0:
dp[i][w] = 0
elif wt[i-1] <= w:
dp[i][w] = max(

Created by Rashesh Rehi 173


Sarvodaya College of Computer Science Programming in Python

val[i-1] + dp[i-1][w-wt[i-1]],
dp[i-1][w]
)
else:
dp[i][w] = dp[i-1][w]

return dp[n][W]
values = [10, 40, 50, 70]
weights = [1, 3, 4, 5]

capacity = 8
n = len(values)
print(knapsack(capacity, weights, values, n))

Output
110

Advantages of DP Knapsack
1. Faster execution
2. Avoid repeated calculations
3. Efficient optimization

5. Dynamic Programming and Divide and Conquer

Introduction
Dynamic Programming (DP) and Divide and Conquer (D&C) are two important
algorithm design techniques used in:
 Computer Science
 Artificial Intelligence
 Data Structures
 Optimization Problems

Both techniques solve complex problems by:


 Breaking problems into smaller parts

Created by Rashesh Rehi 174


Sarvodaya College of Computer Science Programming in Python

But their working methods are different.

Simple Meaning
Technique Meaning
Divide and Conquer Divide problem into independent smaller problems
Dynamic Programming Solve overlapping smaller problems and store results
Real-Life Example
Suppose:
 A teacher distributes chapters among students.

Divide and Conquer


Each student studies separate chapter independently.

Dynamic Programming
Students share notes to avoid repeating same work.

Why These Techniques are Important?


They help:
1. Solve complex problems
2. Improve performance
3. Reduce computation time
4. Build efficient algorithms
5. Handle large datasets

5.1 Divide and Conquer Technique


Divide and Conquer works in three steps:
1. Divide
2. Conquer
3. Combine

Steps of Divide and Conquer


Step Meaning
Divide Break problem into subproblems
Conquer Solve subproblems
Combine Merge solutions

Created by Rashesh Rehi 175


Sarvodaya College of Computer Science Programming in Python

Divide and Conquer Diagram

Characteristics of Divide and Conquer


1. Independent subproblems
2. Recursive solving
3. Combines solutions
4. Efficient for sorting/searching

Examples of Divide and Conquer


1. Merge Sort
2. Quick Sort
3. Binary Search

5.2 Binary Search (Divide and Conquer Example)


Binary search repeatedly divides array into halves.

Program
def binary_search(arr, low, high, target):

if low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, low, mid - 1, target)

Created by Rashesh Rehi 176


Sarvodaya College of Computer Science Programming in Python

else:
return binary_search(arr, mid + 1, high, target)
return -1
arr = [10, 20, 30, 40, 50]
print(binary_search(arr, 0, len(arr)-1, 40))

Output
3

Advantages of Divide and Conquer


1. Faster algorithms
2. Efficient recursion
3. Good scalability
4. Simplifies complex problems

Disadvantages
1. Recursive overhead
2. Extra memory usage
3. Not suitable for overlapping subproblems

----------**********----------

1 Mark Questions
1. What is PyLab?
2. What is plotting?
3. What is matplotlib?
4. What is graph?
5. What is Fibonacci sequence?
6. What is dynamic programming?
7. What is divide and conquer?
8. What is knapsack problem?
9. What is 0/1 knapsack algorithm?
[Link] is plot() function?

Created by Rashesh Rehi 177


Sarvodaya College of Computer Science Programming in Python

2 Marks Questions
1. Explain plotting using PyLab.
2. Explain line graph in Python.
3. Explain Fibonacci sequence.
4. Explain dynamic programming.
5. Explain divide and conquer technique.
6. Explain 0/1 knapsack algorithm.
7. Explain mortgage plotting.
8. Explain advantages of plotting.

5 Marks Questions
1. Explain plotting using PyLab with example.
2. Explain mortgage plotting and extended examples.
3. Explain Fibonacci sequence with suitable example.
4. Explain dynamic programming in detail.
5. Explain 0/1 knapsack algorithm with example.
6. Explain divide and conquer technique.
7. Explain applications of dynamic programming.
8. Explain graph plotting functions in Python.

Practical Tasks
1. Program to plot simple line graph.
2. Program to plot multiple graphs using PyLab.
3. Program to plot mortgage graph.
4. Program to generate Fibonacci sequence.
5. Program using recursion for Fibonacci series.
6. Program implementing dynamic programming.
7. Program implementing 0/1 knapsack algorithm.
8. Program demonstrating divide and conquer technique.

END OF UNIT 3

Created by Rashesh Rehi 178


Sarvodaya College of Computer Science Programming in Python

Unit 4: Network Programming and GUI using Python


1. Network Programming

Introduction to Network Programming


Network programming means:
Writing programs that communicate with other computers over a network.

Using network programming, computers can:


 Send data
 Receive data
 Share resources
 Communicate through internet or local network
Python provides powerful libraries for network programming.

Simple Meaning
Network programming allows:
Communication between two or more computers using programs.

Real-Life Examples
1. WhatsApp messaging
2. Email systems
3. Video calling
4. Online gaming

1.1 Protocol
Definition
A protocol is:
A set of rules used for communication between computers.

Protocols define:
 Data format
 Transmission method
 Error handling

Created by Rashesh Rehi 179


Sarvodaya College of Computer Science Programming in Python

Real-Life Example
Suppose two people speak:
 Same language
 Same communication rules
Then communication becomes easy.
Similarly:
 Computers use protocols.

Protocol Diagram

TCP and UDP


Two important transport protocols.

TCP (Transmission Control Protocol)


TCP provides:
1. Reliable communication
2. Error checking
3. Ordered delivery

Created by Rashesh Rehi 180


Sarvodaya College of Computer Science Programming in Python

Features of TCP
1. Connection-oriented
2. Reliable
3. Slower but accurate

Applications of TCP
1. Email
2. Banking systems
3. Web applications

UDP (User Datagram Protocol)


UDP provides:
1. Fast communication
2. No guaranteed delivery

Features of UDP
1. Connectionless
2. Faster
3. Less reliable

Applications of UDP
1. Online gaming
2. Video streaming
3. Live broadcasting

Difference Between TCP and UDP


TCP UDP
Reliable Faster
Connection-oriented Connectionless
Error checking No guarantee
Slower Faster

1.2 IP Address
IP Address means:
Unique address of computer on network.

Created by Rashesh Rehi 181


Sarvodaya College of Computer Science Programming in Python

Example
[Link]

Types of IP Address
1. IPv4
2. IPv6

1.3 Port Number


Port identifies:
Specific application or service.

Example
Port Service
80 HTTP
443 HTTPS
21 FTP

Why Port is Needed?


One computer may run:
 Browser
 Email
 Chat application
Ports identify correct service.

1.4 Socket Programming


Definition
Socket is:
Endpoint of communication between two computers.
Python provides:
 socket module

Real-Life Example
Socket works like:
 Telephone connection
One side:
 Sends data

Created by Rashesh Rehi 182


Sarvodaya College of Computer Science Programming in Python

Other side:
 Receives data

Types of Socket
Socket Type Purpose
TCP Socket Reliable communication
UDP Socket Fast communication

Importing Socket Module


import socket

Creating Socket

Syntax
[Link](socket.AF_INET, socket.SOCK_STREAM)

Explanation
Part Meaning
AF_INET IPv4
SOCK_STREAM TCP socket

Example
import socket

s = [Link](socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")

Output
Socket Created

1.5 Client-Server Architecture


Network programming uses:
Client-Server Model

Created by Rashesh Rehi 183


Sarvodaya College of Computer Science Programming in Python

Server
Server:
 Provides services
Examples:
 Web server
 Email server

Client
Client:
 Requests services
Examples:
 Browser
 Mobile app

Working Process
1. Server starts
2. Client connects
3. Data exchanged
4. Connection closed

1.6 Server Program in Python

Example
import socket

server = [Link]()
[Link](("localhost", 9999))
[Link](1)
print("Waiting for connection...")

client, address = [Link]()

print("Connected from", address)


[Link](b"Welcome Client")
[Link]()

Created by Rashesh Rehi 184


Sarvodaya College of Computer Science Programming in Python

Explanation
Function Purpose
bind() Assign IP and port
listen() Wait for connection
accept() Accept client
send() Send data

1.7 Client Program in Python

Example
import socket

client = [Link]()
[Link](("localhost", 9999))
message = [Link](1024)
print([Link]())
[Link]()

Output
Welcome Client

1.8 Sending and Receiving Data

Sending Data
[Link]()

Receiving Data
[Link]()

Example
[Link](b"Hello")

Example
data = [Link](1024)
1024 Meaning

Created by Rashesh Rehi 185


Sarvodaya College of Computer Science Programming in Python

Maximum bytes received.


1.9 UDP Socket Example

Server
import socket

server = [Link](socket.AF_INET, socket.SOCK_DGRAM)


[Link](("localhost", 9999))
data, addr = [Link](1024)
print([Link]())

Client
import socket

client = [Link](socket.AF_INET, socket.SOCK_DGRAM)


[Link](b"Hello", ("localhost", 9999))

Difference Between TCP and UDP Socket


TCP Socket UDP Socket
Reliable Faster
SOCK_STREAM SOCK_DGRAM
Connection required No connection

1.10 Applications of Socket Programming


1. Chat applications
2. Multiplayer games
3. Video conferencing
4. Web servers
5. File sharing

Advantages of Socket Programming


1. Real-time communication
2. Fast data exchange
3. Distributed systems support
4. Internet application development

Created by Rashesh Rehi 186


Sarvodaya College of Computer Science Programming in Python

Disadvantages
1. Complex debugging
2. Security concerns
3. Network dependency

2. Knowing IP Address

Introduction
Every computer connected to a network or the internet has a unique address
called:
IP Address

IP Address helps computers:


 Identify each other
 Send data correctly
 Communicate over network
Without IP addresses:
 Internet communication is impossible.

Types of IP Addresses
Mainly:
1. IPv4
2. IPv6

2.1 IPv4 Address


IPv4 is:
32-bit address system

Format of IPv4
[Link]

Structure
IPv4 contains:
 Four numbers
 Separated by dots

Created by Rashesh Rehi 187


Sarvodaya College of Computer Science Programming in Python

Each part ranges:


 0 to 255

2.2 IPv6 Address


IPv6 is:
128-bit address system
Created because IPv4 addresses became limited.

Example
2001:0db8:85a3:0000:0000:8a2e:0370:7334

Advantages of IPv6
1. More addresses
2. Better security
3. Faster routing

2.3 Finding IP Address in Python


Python provides:
 socket module

Import Socket Module


import socket

Program: Find Host Name


import socket

hostname = [Link]()
print(hostname)

Output Example
DESKTOP-ABC123

Explanation
gethostname() returns:
 Computer name

Created by Rashesh Rehi 188


Sarvodaya College of Computer Science Programming in Python

Program: Find IP Address


import socket

hostname = [Link]()
ip = [Link](hostname)
print("Host Name:", hostname)
print("IP Address:", ip)

Output Example
Host Name: DESKTOP-ABC123
IP Address: [Link]

Explanation
Function Purpose
gethostname() Gets computer name
gethostbyname() Gets IP address

2.4 Getting Website IP Address


Python can also find:
 Website IP address

Example
import socket

ip = [Link]("[Link]")
print(ip)

Output Example
[Link]

Explanation
DNS converts:
 Domain name
to
 IP address

Created by Rashesh Rehi 189


Sarvodaya College of Computer Science Programming in Python

3. URL and Reading the Source Code of a Web Page

Introduction
When we open a website in browser:
 Browser sends request
 Server sends webpage source code
Python can:
 Access websites
 Read webpage source code
 Download webpage data
This is important in:
 Web development
 Web scraping
 Network programming
 Automation

3.1 What is URL?


Definition
URL means:
Uniform Resource Locator
A URL is:
Address of resource on internet.

Example URL
[Link]

URL Structure Diagram

Created by Rashesh Rehi 190


Sarvodaya College of Computer Science Programming in Python

Example Breakdown
[Link]

Explanation
Part Meaning
https Protocol
[Link] Domain
[Link] Web page

3.2 Web Page Source Code


A webpage contains:
HTML source code

HTML defines:
 Text
 Images
 Links
 Structure

Example HTML
<html>

<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>

Why Read Source Code?


Python reads webpage source code for:
1. Web scraping
2. Data extraction
3. Automation
4. Web analysis
Created by Rashesh Rehi 191
Sarvodaya College of Computer Science Programming in Python

3.3 urllib Module


Python provides:
urllib
Used for:
 Opening URLs
 Reading webpage data

Import urllib
import [Link]

3.4 Opening a URL

Syntax
[Link](url)

Example
import [Link]
page = [Link]("[Link]
print(page)

Output Example
<[Link] object>

Explanation
urlopen():
 Opens webpage connection

3.5 Reading Source Code


Use:
read()
to read webpage data.

Example
import [Link]
page = [Link]("[Link]

Created by Rashesh Rehi 192


Sarvodaya College of Computer Science Programming in Python

source = [Link]()
print(source)
Output
HTML source code displayed.

3.6 Decoding Source Code


Convert bytes into readable text.

Example
import [Link]

page = [Link]("[Link]
source = [Link]().decode()
print(source)

Explanation
Function Purpose
read() Reads webpage
decode() Converts bytes to text

3.7 Reading Specific Lines

Example
import [Link]

page = [Link]("[Link]
for line in page:
print([Link]())

Output
Displays webpage line by line.

Created by Rashesh Rehi 193


Sarvodaya College of Computer Science Programming in Python

3.8 Downloading Webpage Content

Example
import [Link]
url = [Link]
[Link](url, "python_page.html")

Explanation
Downloads webpage into local file.

3.9 Extracting Website Title


Simple extraction using string search.

Example
import [Link]

page = [Link]("[Link]
source = [Link]().decode()
start = [Link]("<title>")
end = [Link]("</title>")
title = source[start+7:end]
print(title)

Output Example
Welcome to [Link]

Explanation
Program extracts:
 HTML title tag

4. Downloading a Web Page from Internet

Introduction
Python allows us to:
 Connect to websites

Created by Rashesh Rehi 194


Sarvodaya College of Computer Science Programming in Python

 Access webpages
 Download webpage content from the internet

This is useful for:


 Web scraping
 Offline reading
 Automation
 Data collection
 Website backup
Python mainly uses:

urllib module
for downloading webpages.

4.1 urllib Module


Python provides:
urllib
for internet operations.

Main Features of urllib


1. Open URLs
2. Read webpages
3. Download files
4. Handle internet requests

Importing urllib
import [Link]

4.2 Opening a Web Page


Before downloading:
 Connection is opened
using:
urlopen()

Syntax
[Link](url)

Created by Rashesh Rehi 195


Sarvodaya College of Computer Science Programming in Python

Example
import [Link]

page = [Link]("[Link]
print(page)

Output Example
<[Link] object>

Explanation
urlopen():
 Connects to website
 Returns webpage object

4.3 Reading Web Page Content


Use:
read()
to read webpage content.

Example
import [Link]

page = [Link]("[Link]
content = [Link]()
print(content)

Output
HTML content displayed in bytes.

Why Output Appears in Bytes?


Internet data transfers as:
 Binary data (bytes)

4.4 Decoding Web Content


Convert bytes into readable text.

Created by Rashesh Rehi 196


Sarvodaya College of Computer Science Programming in Python

Example
import [Link]

page = [Link]("[Link]
content = [Link]().decode()
print(content)

Explanation
Function Purpose
read() Reads webpage
decode() Converts bytes to text

4.5 Downloading a Web Page


Python provides:
urlretrieve()
for downloading webpages.

Syntax
[Link](url, filename)

Example
import [Link]
url = "[Link]
[Link](url, "python_page.html")

Explanation
Part Meaning
url Website address
filename Saved file name

Result
Webpage saved locally as:
python_page.html

Created by Rashesh Rehi 197


Sarvodaya College of Computer Science Programming in Python

4.6 Opening Downloaded Web Page


Downloaded HTML file can be opened in:
 Browser
 Text editor

Steps
1. Locate downloaded file
2. Double-click file
3. Browser opens webpage

4.7 Downloading Multiple Web Pages

Example
import [Link]

sites = [
"[Link]
"[Link]
]
for i, site in enumerate(sites):
filename = "page" + str(i) + ".html"
[Link](site, filename)
print(filename, "Downloaded")

Output Example
[Link] Downloaded
[Link] Downloaded

4.8 Saving Webpage Content Manually

Example
import [Link]

page = [Link]("[Link]
content = [Link]().decode()

Created by Rashesh Rehi 198


Sarvodaya College of Computer Science Programming in Python

file = open("[Link]", "w", encoding="utf-8")


[Link](content)
[Link]()

print("Saved")

Explanation
Program:
1. Downloads webpage
2. Reads source code
3. Saves into local file

5. Downloading an Image from Internet

Introduction
Python allows us to:
 Connect to websites
 Access image URLs
 Download images from the internet
 Save images into computer
This is useful in:
 Web scraping
 Automation
 Data collection
 Machine learning
 Image processing

Python mainly uses:


urllib module
for downloading images.

5.1 urllib Module


Python provides:
urllib
for internet-related operations.

Created by Rashesh Rehi 199


Sarvodaya College of Computer Science Programming in Python

Features of urllib
1. Open URLs
2. Read webpages
3. Download files
4. Download images

Importing urllib
import [Link]
5.2 What is Image URL?

Every image on internet has:


URL (address)
Example Image URL
[Link]

5.3 Downloading Image Using urlretrieve()


Python provides:
urlretrieve()
for downloading files and images.

Syntax
[Link](
image_url,
filename
)

Example
import [Link]

image_url = "[Link]
[Link](
image_url,
"python_logo.png"
)
print("Image Downloaded")

Created by Rashesh Rehi 200


Sarvodaya College of Computer Science Programming in Python

Output
Image Downloaded

Result
Image saved into current folder.

Explanation
Part Meaning
image_url Internet image address
python_logo.png Saved image name

5.4 Downloading Multiple Images

Example
import [Link]

images = [
"[Link]
"[Link]
[Link]"
]

for i, url in enumerate(images):


filename = "image" + str(i) + ".png"
[Link](url, filename)
print(filename, "Downloaded")

Output Example
[Link] Downloaded
[Link] Downloaded

5.5 Reading Image Data


Images are downloaded as:
Binary data

Created by Rashesh Rehi 201


Sarvodaya College of Computer Science Programming in Python

Example
import [Link]

page = [Link](
"[Link]
)

data = [Link]()
print(type(data))

Output
<class 'bytes'>

Explanation
Image data transfers in:
 Bytes format

5.6 Saving Image Manually

Example
import [Link]

url = "[Link]
response = [Link](url)
data = [Link]()
file = open("python_logo.png", "wb")
[Link](data)
[Link]()
print("Image Saved")

5.7 Displaying Downloaded Image


Images can be opened using:
 Image viewer
 Browser
 Python libraries

Created by Rashesh Rehi 202


Sarvodaya College of Computer Science Programming in Python

Example Using PIL


from PIL import Image
img = [Link]("python_logo.png")
[Link]()

Installation of PIL
pip install pillow

6. A TCP/IP Server and A TCP/IP Client

Introduction
In network programming:
 Computers communicate using networks.
This communication mainly uses:

Client-Server Architecture
Two important parts are:
1. TCP/IP Server
2. TCP/IP Client

Python provides:
socket module
for creating server and client programs.

Real-Life Examples
Client Server
Web browser Website server
WhatsApp app WhatsApp server
Gmail app Mail server

What is TCP/IP?
TCP/IP is a set of networking protocols used for:
 Internet communication

Created by Rashesh Rehi 203


Sarvodaya College of Computer Science Programming in Python

TCP
TCP means:
Transmission Control Protocol
Provides:
1. Reliable communication
2. Error checking
3. Ordered delivery

IP
IP means:
Internet Protocol
Responsible for:
 Device addressing
 Routing data packets

6.1 TCP/IP Working Diagram

Features of TCP
1. Reliable
2. Connection-oriented
3. Error detection
4. Ordered transmission

Applications of TCP/IP
1. Web browsing
2. Email systems
3. Online banking
Created by Rashesh Rehi 204
Sarvodaya College of Computer Science Programming in Python

4. File transfer
5. Cloud computing

6.2 Creating TCP Socket

Syntax
[Link](socket.AF_INET, socket.SOCK_STREAM)

Example
import socket

s = [Link](
socket.AF_INET,
socket.SOCK_STREAM
)
print("Socket Created")

Output
Socket Created

6.3 TCP/IP Server


Definition
Server:
Waits for client connections and provides services.

Steps to Create Server


1. Create socket
2. Bind IP and port
3. Listen for connections
4. Accept client
5. Send/receive data
6. Close connection

Server Program
import socket

Created by Rashesh Rehi 205


Sarvodaya College of Computer Science Programming in Python

server = [Link](
socket.AF_INET,
socket.SOCK_STREAM
)
[Link](("localhost", 9999))
[Link](1)
print("Waiting for client...")
client, address = [Link]()
print("Connected from:", address)
[Link](b"Welcome Client")
[Link]()

Explanation
Function Purpose
bind() Assign IP and port
listen() Wait for client
accept() Accept connection
send() Send data
close() Close connection

Output Example
Waiting for client...
Connected from: ('[Link]', 54321)

Important Note
Server must run:
Before client starts.

6.4 TCP/IP Client


Definition
Client:
Connects to server and requests service.

Steps to Create Client


1. Create socket

Created by Rashesh Rehi 206


Sarvodaya College of Computer Science Programming in Python

2. Connect to server
3. Receive/send data
4. Close connection

Client Program
import socket

client = [Link](
socket.AF_INET,
socket.SOCK_STREAM
)
[Link](("localhost", 9999))
message = [Link](1024)
print([Link]())
[Link]()

Output
Welcome Client

Explanation
Function Purpose
connect() Connect to server
recv() Receive data
decode() Convert bytes to text

1024 Meaning
Maximum bytes received.

6.5 Sending Data from Client to Server

Server
import socket

server = [Link]()
[Link](("localhost", 9999))
[Link](1)
Created by Rashesh Rehi 207
Sarvodaya College of Computer Science Programming in Python

client, addr = [Link]()


data = [Link](1024)
print([Link]())
[Link]()

Client
import socket

client = [Link]()
[Link](("localhost", 9999))
[Link](b"Hello Server")
[Link]()

Output
Hello Server

7. A UDP Server and A UDP Client

Introduction
In network programming, computers communicate using:
 Protocols
Two important protocols are:
1. TCP
2. UDP
This topic explains:

UDP Client-Server Programming using Python


Python uses:
socket module
to create UDP servers and clients.

What is UDP?
UDP means:
User Datagram Protocol
UDP is a communication protocol used for:

Created by Rashesh Rehi 208


Sarvodaya College of Computer Science Programming in Python

 Fast data transfer


Unlike TCP:
 UDP does not guarantee delivery.

Why UDP is Fast?


UDP:
 Does not establish connection
 Does not check delivery
 Does not reorder packets
Therefore:
Communication becomes faster.

Features of UDP
1. Fast communication
2. Connectionless
3. Lightweight
4. No delivery guarantee
5. Low overhead

Advantages of UDP
1. Faster than TCP
2. Lower delay
3. Better for real-time systems

Disadvantages of UDP
1. No guaranteed delivery
2. Data loss possible
3. No error recovery

Difference Between TCP and UDP


TCP UDP
Reliable Faster
Connection-oriented Connectionless
Error checking No guarantee
More overhead Less overhead

Created by Rashesh Rehi 209


Sarvodaya College of Computer Science Programming in Python

7.1 Socket Programming for UDP


Python uses:
socket module
for UDP programming.

Import Socket Module


import socket

UDP Socket Type


UDP uses:
SOCK_DGRAM

Syntax
[Link](
socket.AF_INET,
socket.SOCK_DGRAM
)

Explanation
Part Meaning
AF_INET IPv4
SOCK_DGRAM UDP protocol

Example
import socket

s = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
print("UDP Socket Created")

Output
UDP Socket Created

Created by Rashesh Rehi 210


Sarvodaya College of Computer Science Programming in Python

7.2 UDP Server


Definition
UDP Server:
Receives messages from clients.

Steps to Create UDP Server


1. Create UDP socket
2. Bind IP and port
3. Receive data
4. Send response
5. Close socket

UDP Server Program


import socket

server = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](("localhost", 9999))

print("UDP Server Waiting...")


data, addr = [Link](1024)
print("Client Message:", [Link]())
[Link]()

Explanation
Function Purpose
bind() Assign IP and port
recvfrom() Receive data
decode() Convert bytes to text

Output Example
UDP Server Waiting...
Client Message: Hello Server

Created by Rashesh Rehi 211


Sarvodaya College of Computer Science Programming in Python

1024 Meaning
Maximum bytes received.

7.3 UDP Client


Definition
UDP Client:
Sends data to server.

Steps to Create UDP Client


1. Create UDP socket
2. Send message
3. Close socket

UDP Client Program


import socket

client = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](
b"Hello Server",
("localhost", 9999)
)
[Link]()

Explanation
Function Purpose
sendto() Send UDP message
close() Close socket

7.4 recvfrom() Function


UDP uses:
recvfrom()
instead of:
recv()

Created by Rashesh Rehi 212


Sarvodaya College of Computer Science Programming in Python

because UDP also returns:


 Sender address

Syntax
data, addr = [Link](1024)

Explanation
Variable Meaning
data Received message
addr Sender address

7.5 sendto() Function


UDP uses:
sendto()
instead of:
send()
because UDP directly specifies destination address.

Syntax
[Link](data, address)

Example
[Link](
b"Hello",
("localhost", 9999)
)

8. File Server and File Client

Introduction
In network programming:
 Computers can exchange files over networks.
This is done using:

Created by Rashesh Rehi 213


Sarvodaya College of Computer Science Programming in Python

File Server and File Client


A file server:
 Stores files
 Sends files to clients
A file client:
 Requests files
 Downloads files from server
Python uses:
socket programming
for file transfer.

Applications of File Server


1. Company file sharing
2. Online cloud storage
3. Software updates
4. Network backup systems
5. Data distribution

8.1 File Transfer Using Socket Programming


Python uses:
socket module
for transferring files.

Required Modules
import socket

Basic Process
1. Server opens file
2. Server reads file data
3. Server sends file data
4. Client receives data
5. Client saves file

Created by Rashesh Rehi 214


Sarvodaya College of Computer Science Programming in Python

File Transfer Workflow

8.2 Creating File Server


Definition
File server:
Sends files to clients.

Steps to Create File Server


1. Create socket
2. Bind IP and port
3. Listen for connection
4. Accept client
5. Open file
6. Send file data
7. Close connection

File Server Program


import socket

server = [Link]()
[Link](("localhost", 9999))
[Link](1)

Created by Rashesh Rehi 215


Sarvodaya College of Computer Science Programming in Python

print("Waiting for client...")

client, addr = [Link]()


file = open("[Link]", "rb")

data = [Link]()
[Link](data)

[Link]()
[Link]()
[Link]()

Explanation
Function Purpose
open() Open file
read() Read file content
send() Send file data
rb Read binary mode

Why Binary Mode?


Files transfer as:
Binary data

8.3 Creating File Client


Definition
File client:
Receives file from server.

Steps to Create File Client


1. Create socket
2. Connect to server
3. Receive file data
4. Save file
5. Close connection

Created by Rashesh Rehi 216


Sarvodaya College of Computer Science Programming in Python

File Client Program


import socket

client = [Link]()
[Link](("localhost", 9999))

data = [Link](1024)
file = open("[Link]", "wb")
[Link](data)
[Link]()

[Link]()
print("File Received")

Output
File Received

Explanation
Function Purpose
recv() Receive data
write() Save file
wb Write binary mode

8.4 Sending Large Files


Large files require:
 Multiple chunks
because:
 recv(1024) receives limited bytes.
Chunk-Based Transfer
Server sends:
Small parts repeatedly

Server Program for Large Files


import socket

server = [Link]()
Created by Rashesh Rehi 217
Sarvodaya College of Computer Science Programming in Python

[Link](("localhost", 9999))
[Link](1)

client, addr = [Link]()


file = open("[Link]", "rb")

while True:
data = [Link](1024)
if not data:
break
[Link](data)

[Link]()
[Link]()
[Link]()

Client Program for Large Files


import socket

client = [Link]()
[Link](("localhost", 9999))
file = open("[Link]", "wb")

while True:
data = [Link](1024)
if not data:
break
[Link](data)
[Link]()
[Link]()
print("Large File Received")

Advantages of Chunk Transfer


1. Supports large files
2. Better memory usage
3. Reliable transfer

Created by Rashesh Rehi 218


Sarvodaya College of Computer Science Programming in Python

9. Two-Way Communication between Server and Client

Introduction
In network programming:
 Communication can happen in both directions.
This is called:

Two-Way Communication
In two-way communication:
 Server sends messages to client
 Client sends messages to server
Python uses:
socket programming
to implement this communication.

Applications of Two-Way Communication


1. Chat applications
2. Multiplayer games
3. Banking systems
4. Video conferencing
5. Cloud systems

9.1 Client-Server Architecture


Server
Provides services and responds to clients.

Client
Requests services from server.

Communication Process
1. Server starts
2. Client connects
3. Client sends message
4. Server replies
5. Communication continues

Created by Rashesh Rehi 219


Sarvodaya College of Computer Science Programming in Python

9.2 Socket Programming


Python uses:
socket module
for communication.

Import Socket Module


import socket

Creating Socket

Syntax
[Link](
socket.AF_INET,
socket.SOCK_STREAM
)

Explanation
Part Meaning
AF_INET IPv4
SOCK_STREAM TCP protocol

Why TCP?
TCP provides:
1. Reliable communication
2. Ordered data transfer
3. Error checking

9.3 Two-Way TCP Communication


In TCP:
 Both sides can:
o send()
o recv()

Created by Rashesh Rehi 220


Sarvodaya College of Computer Science Programming in Python

Functions Used
Function Purpose
send() Send data
recv() Receive data
connect() Connect client
accept() Accept client

9.4 Server Program

Example
import socket

server = [Link](
socket.AF_INET,
socket.SOCK_STREAM
)
[Link](("localhost", 9999))
[Link](1)
print("Waiting for client...")
client, addr = [Link]()
msg = [Link](1024)

print("Client:", [Link]())
[Link](b"Hello Client")
[Link]()
[Link]()

Explanation
Step Purpose
bind() Assign address
listen() Wait for connection
accept() Accept client
recv() Receive client message
send() Send reply

Created by Rashesh Rehi 221


Sarvodaya College of Computer Science Programming in Python

Server Output Example


Waiting for client...
Client: Hello Server

9.5 Client Program

Example
import socket

client = [Link](
socket.AF_INET,
socket.SOCK_STREAM
)
[Link](("localhost", 9999))
[Link](b"Hello Server")
reply = [Link](1024)
print("Server:", [Link]())
[Link]()

Client Output
Server: Hello Client

9.6 Message Encoding and Decoding


Network communication transfers:
Bytes

Encoding
Convert text into bytes.

Example
[Link]()

Decoding
Convert bytes into text.

Created by Rashesh Rehi 222


Sarvodaya College of Computer Science Programming in Python

Example
[Link]()

9.7 Continuous Two-Way Communication


Communication can continue repeatedly.

Server Program
import socket

server = [Link]()
[Link](("localhost", 9999))
[Link](1)
client, addr = [Link]()
while True:
msg = [Link](1024).decode()
print("Client:", msg)
if msg == "bye":
break
reply = input("Server Reply: ")
[Link]([Link]())
[Link]()

Client Program
import socket

client = [Link]()
[Link](("localhost", 9999))
while True:
msg = input("Enter Message: ")
[Link]([Link]())
if msg == "bye":
break
reply = [Link](1024).decode()
print("Server:", reply)
[Link]()

Created by Rashesh Rehi 223


Sarvodaya College of Computer Science Programming in Python

9.8 Two-Way UDP Communication


UDP also supports:
 Bidirectional communication
using:
 sendto()
 recvfrom()

UDP Server Example


import socket

server = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](("localhost", 9999))
data, addr = [Link](1024)
print([Link]())
[Link](
b"Hello Client",
addr
)

UDP Client Example


import socket

client = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](
b"Hello Server",
("localhost", 9999)
)
reply, addr = [Link](1024)
print([Link]())

Created by Rashesh Rehi 224


Sarvodaya College of Computer Science Programming in Python

10. Sending a Simple Mail

Introduction
Python allows us to:
 Send emails automatically
 Connect to mail servers
 Create mail applications
This is done using:
SMTP Protocol
and Python’s:
smtplib module

Email programming is useful in:


 Automation
 Notifications
 Verification systems
 Online applications

Simple Meaning
Sending a simple mail means:

Sending email using Python program.

Real-Life Examples
1. OTP emails
2. Password reset emails
3. College notifications
4. Online shopping confirmations
5. Bank alerts

10.1 What is SMTP?


SMTP means:
Simple Mail Transfer Protocol
SMTP is used for:
Sending emails over internet.

Created by Rashesh Rehi 225


Sarvodaya College of Computer Science Programming in Python

Features of SMTP
1. Email transmission
2. Reliable communication
3. Internet-based messaging

Common Email Protocols


Protocol Purpose
SMTP Sending emails
POP3 Receiving emails
IMAP Managing emails

Difference Between SMTP and POP3


SMTP POP3
Sends emails Receives emails
Outgoing mail Incoming mail

10.2 smtplib Module


Python provides:

Created by Rashesh Rehi 226


Sarvodaya College of Computer Science Programming in Python

smtplib
for sending emails.

Importing smtplib
import smtplib

10.3 SMTP Server


SMTP server handles:
Sending email messages.

Example SMTP Servers


Provider SMTP Server
Gmail [Link]
Yahoo [Link]
Outlook [Link]

Gmail SMTP Port


Usually:
587

10.4 Sending Simple Email

Basic Steps
1. Import smtplib
2. Connect SMTP server
3. Login email account
4. Send email
5. Close connection

Syntax
server = [Link](server_name, port)

Example
import smtplib

server = [Link](
Created by Rashesh Rehi 227
Sarvodaya College of Computer Science Programming in Python

"[Link]",
587
)
[Link]()

[Link](
"your_email@[Link]",
"your_password"
)

message = "Hello from Python"

[Link](
"your_email@[Link]",
"receiver@[Link]",
message
)

[Link]()
print("Mail Sent")

Explanation
Function Purpose
SMTP() Connect SMTP server
starttls() Secure connection
login() Login email
sendmail() Send email
quit() Close server

Output
Mail Sent

Important Note
Modern Gmail usually requires:

Created by Rashesh Rehi 228


Sarvodaya College of Computer Science Programming in Python

 App Password
OR
 Less secure app access

10.5 starttls() Function


starttls() provides:
Secure encrypted communication.

Why Security is Important?


Protects:
1. Password
2. Email content
3. User data

10.6 Sending Email with Subject

Example
import smtplib

server = [Link](
"[Link]",
587
)
[Link]()

[Link](
"your_email@[Link]",
"your_password"
)
subject = "Test Mail"
body = "This is Python email"
message = f"Subject: {subject}\n\n{body}"

[Link](
"your_email@[Link]",
"receiver@[Link]",

Created by Rashesh Rehi 229


Sarvodaya College of Computer Science Programming in Python

message
)
[Link]()
print("Mail Sent")

Output
Mail Sent

Explanation
Email format contains:
1. Subject
2. Blank line
3. Body

10.7 Sending Email to Multiple Users

Example
import smtplib

server = [Link](
"[Link]",
587
)
[Link]()
[Link](
"your_email@[Link]",
"your_password"
)
receivers = [
"a@[Link]",
"b@[Link]"
]
message = "Hello Everyone"

[Link](
"your_email@[Link]",

Created by Rashesh Rehi 230


Sarvodaya College of Computer Science Programming in Python

receivers,
message
)
[Link]()

10.8 Sending HTML Email


Emails can contain:
 HTML formatting

Example
import smtplib

message = """
Subject: HTML Mail

<h1>Hello</h1>
<p>This is HTML email</p>
"""

11. GUI Programming: Event-driven programming paradigm

Introduction
GUI stands for:
Graphical User Interface
GUI allows users to interact with programs using:
 Buttons
 Menus
 Textboxes
 Windows
 Icons

Instead of typing commands, users can:


Click and interact visually.

Python provides GUI programming using:

Created by Rashesh Rehi 231


Sarvodaya College of Computer Science Programming in Python

Tkinter

What is Event-Driven Programming?


Event-driven programming is a programming style where:
Program execution depends on events.
An event may be:
 Mouse click
 Keyboard press
 Button click
 Window closing
 Menu selection
The program waits for events and responds when an event occurs.

11.1 Event-Driven Programming Diagram

Why Event-Driven Programming is Important?


It helps:
1. Create interactive applications
2. Improve user experience
3. Build graphical applications
4. Support real-time interaction
5. Make software user-friendly

Created by Rashesh Rehi 232


Sarvodaya College of Computer Science Programming in Python

11.2 Traditional Programming vs Event-Driven Programming


Traditional Programming Event-Driven Programming
Executes step by step Executes when event occurs
Fixed program flow Dynamic flow
User has less interaction User controls actions

Example
In calculator application:
 User clicks button
 Event occurs
 Program performs calculation

11.3 Components of Event-Driven Programming


Main components:
1. Event
2. Event Source
3. Event Handler
4. Event Loop

1. Event
An event is:
An action performed by user or system.
Examples:
 Button click
 Mouse movement
 Key press

2. Event Source
The object generating event.
Examples:
 Button
 Textbox
 Window

3. Event Handler
Function that responds to event.
Created by Rashesh Rehi 233
Sarvodaya College of Computer Science Programming in Python

Example
def hello():

print("Button Clicked")

4. Event Loop
Continuously checks:
Whether an event occurred.

12. Creating Simple GUI

Introduction
GUI stands for:
Graphical User Interface
GUI allows users to interact with programs using:
 Windows
 Buttons
 Textboxes
 Menus
 Labels
Instead of typing commands, users can:
Click and interact visually.
Python provides GUI programming using:
Tkinter
What is Tkinter?
Tkinter is:
Python’s standard GUI library.
It helps create:
 Windows
 Buttons
 Labels
 Input boxes
 Dialogs

Created by Rashesh Rehi 234


Sarvodaya College of Computer Science Programming in Python

Why GUI Programming is Important?


GUI helps:
1. Create user-friendly applications
2. Improve interaction
3. Build professional software
4. Make applications easy to use
5. Support event-driven programming

Steps to Create Simple GUI


1. Import Tkinter
2. Create main window
3. Add widgets
4. Run event loop

12.1 Importing Tkinter

Syntax
from tkinter import *

Explanation
Imports all Tkinter classes and functions.

12.2 Creating Main Window


Main window is created using:
Tk()

Example
from tkinter import *
window = Tk()

Explanation
Tk() creates:
Main application window.

12.3 Running GUI Window


GUI runs using:

Created by Rashesh Rehi 235


Sarvodaya College of Computer Science Programming in Python

mainloop()

Example
[Link]()

Why mainloop() is Important?


It:
 Waits for user events
 Keeps window open
Without mainloop():
 Window closes immediately.

Basic Window Program


from tkinter import *

window = Tk()
[Link]()

Output
A blank GUI window appears.

12.4 Setting Window Title


Window title is set using:
title()

Example
[Link]("My First GUI")

Complete Example
from tkinter import *

window = Tk()
[Link]("My First GUI")
[Link]()

Created by Rashesh Rehi 236


Sarvodaya College of Computer Science Programming in Python

Output
Window title becomes:
My First GUI

12.5 Setting Window Size


Window size is set using:
geometry()

Syntax
[Link]("widthxheight")

Example
[Link]("400x300")

Complete Program
from tkinter import *

window = Tk()
[Link]("Simple GUI")
[Link]("400x300")
[Link]()

Output
Window size becomes:
 Width = 400
 Height = 300

13. Buttons, Labels, Entry Fields, Dialogs in Tkinter

Introduction
GUI applications use different components called:
Widgets
Widgets help users:
 Enter data
 Display information

Created by Rashesh Rehi 237


Sarvodaya College of Computer Science Programming in Python

 Click buttons
 Interact with application
Important Tkinter widgets are:
1. Labels
2. Buttons
3. Entry Fields
4. Dialogs
Tkinter provides these widgets for creating interactive GUI applications.

Why Widgets are Important?


Widgets help:
1. Build interactive software
2. Accept user input
3. Display output
4. Improve user experience
5. Create professional interfaces

13.1 Label Widget


Label widget is used to:
Display text or information.

Syntax
Label(window, text="Text")

Example
from tkinter import *

window = Tk()
label = Label(
window,
text="Welcome to Python"
)

[Link]()
[Link]()

Created by Rashesh Rehi 238


Sarvodaya College of Computer Science Programming in Python

Output
Text appears on GUI window.

Explanation
Parameter Purpose
window Parent window
text Text displayed

Label Widget Diagram

Label Attributes
Attribute Purpose
text Display text
fg Text color
bg Background color
font Font style

Example with Colors and Font


from tkinter import *

window = Tk()

Created by Rashesh Rehi 239


Sarvodaya College of Computer Science Programming in Python

label = Label(
window,
text="Python GUI",
fg="blue",
bg="yellow",
font=("Arial", 16)
)

[Link]()
[Link]()

13.2 Button Widget


Button widget performs:
Action when clicked.

Syntax
Button(window, text="Button")

Example
from tkinter import *

window = Tk()

button = Button(
window,
text="Click Me"
)

[Link]()
[Link]()

Output
Button appears on window.

Created by Rashesh Rehi 240


Sarvodaya College of Computer Science Programming in Python

Button with Function

Example
from tkinter import *

def hello():

print("Button Clicked")

window = Tk()

button = Button(
window,
text="Click",
command=hello
)

[Link]()
[Link]()

Output
When button clicked:
Button Clicked

Explanation
Part Purpose
command Connects function
hello Event handler

Button Attributes
Attribute Purpose
text Button text
command Function called
fg Text color

Created by Rashesh Rehi 241


Sarvodaya College of Computer Science Programming in Python

Attribute Purpose
bg Background color
font Font style

13.3 Entry Widget


Entry widget accepts:
User input.

Syntax
Entry(window)

Example
from tkinter import *

window = Tk()
entry = Entry(window)
[Link]()
[Link]()

Output
Textbox appears on window.

Entry Widget Diagram

Created by Rashesh Rehi 242


Sarvodaya College of Computer Science Programming in Python

Getting Entry Data


Use:
get()

Example
from tkinter import *

def show():
print([Link]())

window = Tk()
entry = Entry(window)
[Link]()

button = Button(
window,
text="Show",
command=show
)

[Link]()
[Link]()

Output
Entered text displayed in console.

Entry Attributes
Attribute Purpose
width Width of field
fg Text color
bg Background color
font Font style

Created by Rashesh Rehi 243


Sarvodaya College of Computer Science Programming in Python

Example with Width


entry = Entry(
window,
width=30
)

13.4 Dialog Boxes


Dialogs are:
Small popup windows used for messages or input.
Tkinter provides:
messagebox

Importing Messagebox
from tkinter import messagebox

Types of Dialogs
Dialog Purpose
showinfo() Information message
showwarning() Warning message
showerror() Error message

Information Dialog Example


from tkinter import *
from tkinter import messagebox

window = Tk()
[Link](
"Information",
"Welcome to Python GUI"
)
[Link]()

Output
Information popup appears.

Created by Rashesh Rehi 244


Sarvodaya College of Computer Science Programming in Python

Dialog Box Diagram

Warning Dialog Example


from tkinter import *
from tkinter import messagebox

window = Tk()

[Link](
"Warning",
"Invalid Input"
)
[Link]()

Error Dialog Example


from tkinter import *
from tkinter import messagebox

Created by Rashesh Rehi 245


Sarvodaya College of Computer Science Programming in Python

window = Tk()

[Link](
"Error",
"Login Failed"
)
[Link]()

13.5 Complete GUI Example


from tkinter import *
from tkinter import messagebox

def submit():

name = [Link]()

[Link](
"Message",
"Welcome " + name
)

window = Tk()

[Link]("Student Form")

label = Label(
window,
text="Enter Name"
)

[Link]()

entry = Entry(window)

[Link]()

Created by Rashesh Rehi 246


Sarvodaya College of Computer Science Programming in Python

button = Button(
window,
text="Submit",
command=submit
)

[Link]()

[Link]()

Output
GUI contains:
 Label
 Entry field
 Button
 Dialog box

14. Widget Attributes – Sizes, Fonts, Colors

Introduction
In GUI programming, widgets can be customized using:
Attributes
Attributes help change:
 Size
 Font style
 Colors
 Appearance
Using widget attributes makes GUI applications:
Attractive and user-friendly.
Tkinter provides many attributes for customizing widgets.

Why Widget Attributes are Important?


Widget attributes help:
1. Improve GUI design
2. Increase readability

Created by Rashesh Rehi 247


Sarvodaya College of Computer Science Programming in Python

3. Make applications attractive


4. Improve user experience
5. Create professional interfaces

Common Widget Attributes


Attribute Purpose
width Widget width
height Widget height
font Font style
fg Text color
bg Background color

Widgets Supporting Attributes


1. Label
2. Button
3. Entry
4. Text
5. Frame

14.1 Widget Size Attributes


Size attributes control:
Width and height of widgets.

Syntax
widget = Widget(
window,
width=value,
height=value
)

Example
from tkinter import *

window = Tk()

Created by Rashesh Rehi 248


Sarvodaya College of Computer Science Programming in Python

button = Button(
window,
text="Submit",
width=20,
height=2
)
[Link]()
[Link]()

Output
Large button appears.

Explanation
Attribute Meaning
width=20 Button width
height=2 Button height

Example with Label Size


from tkinter import *

window = Tk()

label = Label(
window,
text="Python GUI",
width=25,
height=3
)
[Link]()
[Link]()

14.2 Font Attributes


Font attributes control:
Text style and appearance.

Created by Rashesh Rehi 249


Sarvodaya College of Computer Science Programming in Python

Syntax
font=("FontName", size, "style")

Example
from tkinter import *

window = Tk()

label = Label(
window,
text="Welcome",
font=("Arial", 20)
)
[Link]()
[Link]()

Output
Large Arial text displayed.

Common Font Styles


Style Meaning
bold Bold text
italic Italic text
underline Underlined text

Example with Bold Font


from tkinter import *

window = Tk()
label = Label(
window,
text="Python",
font=("Times New Roman", 18, "bold")
)
[Link]()
[Link]()
Created by Rashesh Rehi 250
Sarvodaya College of Computer Science Programming in Python

Example with Italic Font


label = Label(
window,
text="Tkinter",
font=("Calibri", 16, "italic")
)

14.3 Color Attributes


Colors improve:
Appearance of widgets.

Important Color Attributes


Attribute Purpose
fg Foreground/text color
bg Background color

Example
from tkinter import *

window = Tk()

label = Label(
window,
text="Python GUI",
fg="white",
bg="blue"
)
[Link]()
[Link]()

Output
White text on blue background.

Created by Rashesh Rehi 251


Sarvodaya College of Computer Science Programming in Python

Common Color Names


Color Usage
red Red color
blue Blue color
green Green color
yellow Yellow color
black Black color

Example with Button Colors


from tkinter import *

window = Tk()

button = Button(
window,
text="Login",
fg="white",
bg="green"
)
[Link]()
[Link]()

Output
Green button with white text.

14.4 Entry Widget Attributes


Entry widgets also support:
 Size
 Font
 Colors

Example
from tkinter import *

window = Tk()

Created by Rashesh Rehi 252


Sarvodaya College of Computer Science Programming in Python

entry = Entry(
window,
width=30,
fg="blue",
bg="lightyellow",
font=("Arial", 14)
)
[Link]()
[Link]()

Output
Styled textbox appears.

14.5 Combining Multiple Attributes


Widgets can use:
Multiple attributes together.

Example
from tkinter import *

window = Tk()

label = Label(
window,
text="Student Form",
width=20,
height=2,
fg="white",
bg="darkblue",
font=("Arial", 18, "bold")
)
[Link]()
[Link]()

Created by Rashesh Rehi 253


Sarvodaya College of Computer Science Programming in Python

Output
Styled label displayed.

14.6 Widget Configuration Using configure()


Widget appearance can be changed later using:
configure()

Example
from tkinter import *

window = Tk()

label = Label(
window,
text="Python"
)

[Link]()
[Link](
fg="red",
bg="yellow",
font=("Arial", 20)
)
[Link]()

15. Treeview, Layouts, Nested Frames

Introduction
GUI applications require:
 Proper arrangement of widgets
 Data display in tables
 Organized interface design
Tkinter provides:
1. Treeview widget
2. Layout managers

Created by Rashesh Rehi 254


Sarvodaya College of Computer Science Programming in Python

3. Frames and nested frames


These help create:
Professional and organized GUI applications.

15.1 Treeview Widget


Treeview widget is used to:
Display data in tabular form.
It is available in:
[Link]

Importing Treeview
from [Link] import Treeview

Why Treeview is Used?


Treeview helps:
1. Display tables
2. Show records
3. Organize large data

Treeview Example Diagram

Created by Rashesh Rehi 255


Sarvodaya College of Computer Science Programming in Python

Creating Simple Treeview

Example
from tkinter import *
from [Link] import Treeview
window = Tk()
tree = Treeview(window)
[Link]()
[Link]()

Output
Blank Treeview appears.

15.2 Adding Columns to Treeview

Example
from tkinter import *
from [Link] import Treeview

window = Tk()
tree = Treeview(
window,
columns=("Roll", "Name")
)
[Link]("#0", text="ID")
[Link]("Roll", text="Roll No")
[Link]("Name", text="Student Name")
[Link]()
[Link]()

Output
Treeview table with headings appears.

Explanation
Statement Purpose
columns Defines columns

Created by Rashesh Rehi 256


Sarvodaya College of Computer Science Programming in Python

Statement Purpose
heading() Sets heading text

15.3 Inserting Data into Treeview

Example
from tkinter import *
from [Link] import Treeview

window = Tk()

tree = Treeview(
window,
columns=("Roll", "Name")
)
[Link]("#0", text="ID")
[Link]("Roll", text="Roll No")
[Link]("Name", text="Name")
[Link](
"",
"end",
text="1",
values=(101, "Raj")
)

[Link](
"",
"end",
text="2",
values=(102, "Amit")
)
[Link]()
[Link]()

Output
Student records displayed in table.

Created by Rashesh Rehi 257


Sarvodaya College of Computer Science Programming in Python

Advantages of Treeview
1. Displays records neatly
2. Easy data management
3. Professional appearance

15.4 Layout Managers


Layouts control:
Positioning of widgets.
Tkinter provides:
1. pack()
2. grid()
3. place()

Why Layouts are Important?


Layouts help:
1. Arrange widgets properly
2. Prevent overlapping
3. Create responsive GUI

Layout Manager Diagram

Created by Rashesh Rehi 258


Sarvodaya College of Computer Science Programming in Python

15.5 pack() Layout


pack() places widgets:
One after another.

Example
from tkinter import *

window = Tk()

Label(window, text="First").pack()
Label(window, text="Second").pack()
[Link]()

Output
Labels appear vertically.

Advantages
1. Simple to use
2. Automatic arrangement

15.6 grid() Layout


grid() arranges widgets:
In rows and columns.

Example
from tkinter import *

window = Tk()

Label(
window,
text="Name"
).grid(row=0, column=0)

Entry(
window

Created by Rashesh Rehi 259


Sarvodaya College of Computer Science Programming in Python

).grid(row=0, column=1)

[Link]()

Output
Label and textbox arranged in grid format.

Advantages of grid()
1. Better alignment
2. Useful for forms
3. Professional layout

15.7 place() Layout


place() positions widgets using:
Exact coordinates.

Example
from tkinter import *

window = Tk()

button = Button(
window,
text="Login"
)
[Link](x=100, y=50)
[Link]()

Output
Button appears at exact position.

Advantages
1. Precise positioning
2. Flexible design

Created by Rashesh Rehi 260


Sarvodaya College of Computer Science Programming in Python

Layout Comparison
Layout Purpose
pack() Simple arrangement
grid() Table-like arrangement
place() Exact positioning

15.8 Frames in Tkinter


Frame is:
Container for widgets.
Frames help:
 Group related widgets

Syntax
Frame(window)

Example
from tkinter import *

window = Tk()

frame = Frame(window)

[Link]()

Button(
frame,
text="Button 1"
).pack()
[Link]()

Output
Button appears inside frame.

Created by Rashesh Rehi 261


Sarvodaya College of Computer Science Programming in Python

Frame Diagram

Why Frames are Important?


Frames help:
1. Organize GUI
2. Divide interface
3. Manage widgets easily

15.9 Nested Frames


Nested frames mean:
Frame inside another frame.
Used for:
 Complex GUI design

Example
from tkinter import *

window = Tk()

top_frame = Frame(window)
top_frame.pack()
bottom_frame = Frame(window)
bottom_frame.pack()

Created by Rashesh Rehi 262


Sarvodaya College of Computer Science Programming in Python

Button(
top_frame,
text="Top Button"
).pack()

Button(
bottom_frame,
text="Bottom Button"
).pack()

[Link]()

Output
Buttons appear in different frame sections.

Advantages of Nested Frames


1. Better organization
2. Easy layout management
3. Professional design
4. Supports large applications

15.10 Complete GUI Example


from tkinter import *
from [Link] import Treeview

window = Tk()

[Link]("Student System")
frame = Frame(window)

[Link]()
tree = Treeview(
frame,
columns=("Roll", "Name")
)

Created by Rashesh Rehi 263


Sarvodaya College of Computer Science Programming in Python

[Link]("#0", text="ID")
[Link]("Roll", text="Roll No")
[Link]("Name", text="Name")

[Link](
"",
"end",
text="1",
values=(101, "Raj")
)

[Link]()
[Link]()

Output
GUI displays:
 Frame
 Treeview table
 Student data

----------**********----------

1 Mark Questions
1. What is protocol?
2. What is socket?
3. What is IP address?
4. What is URL?
5. What is TCP/IP?
6. What is UDP?
7. What is server?
8. What is client?
9. What is GUI?
[Link] is Tkinter?
[Link] is event-driven programming?

Created by Rashesh Rehi 264


Sarvodaya College of Computer Science Programming in Python

[Link] is widget?
[Link] is Treeview?
[Link] is dialog box?
[Link] is mainloop()?

2 Marks Questions
1. Explain socket programming.
2. Explain IP address.
3. Explain URL in networking.
4. Difference between TCP and UDP.
5. Explain TCP server and client.
6. Explain UDP server and client.
7. Explain file server and file client.
8. Explain two-way communication between server and client.
9. Explain sending simple mail using Python.
[Link] GUI programming.
[Link] event-driven programming paradigm.
[Link] Label, Button, and Entry widgets.
[Link] dialog boxes in Tkinter.
[Link] widget attributes such as size, font, and color.
[Link] Treeview widget and layouts.

5 Marks Questions
1. Explain network programming in Python.
2. Explain socket programming with example.
3. Explain TCP/IP server and client communication.
4. Explain UDP server and client communication.
5. Explain downloading webpage and image from internet.
6. Explain file server and file client with example.
7. Explain two-way communication between server and client.
8. Explain sending simple mail using Python.
9. Explain event-driven programming paradigm.
[Link] creating simple GUI using Tkinter.
[Link] buttons, labels, entry fields, and dialogs.
[Link] widget attributes with examples.
[Link] Treeview, layouts, and nested frames.

Created by Rashesh Rehi 265


Sarvodaya College of Computer Science Programming in Python

[Link] GUI programming applications and advantages.


[Link] Python program creating GUI form with widgets.

Practical Tasks
1. Program to display IP address.
2. Program to read source code of webpage.
3. Program to download webpage from internet.
4. Program to download image from internet.
5. Program creating TCP server and client.
6. Program creating UDP server and client.
7. Program for file transfer using sockets.
8. Program for two-way communication between client and server.
9. Program sending simple email using Python.
[Link] creating simple GUI window.
[Link] using Label and Button widgets.
[Link] using Entry field and dialog box.
[Link] changing widget size, font, and color.
[Link] creating Treeview table.
[Link] using layouts and nested frames.

END OF UNIT 4

Created by Rashesh Rehi 266


Sarvodaya College of Computer Science Programming in Python

Unit 5: Connecting with Database


1. Verifying the MySQL DB Interface Installation

Introduction
Python can connect with MySQL database using a database interface or
connector.

The most commonly used connector is:


mysql-connector-python
It allows Python programs to:
 Connect to MySQL database
 Create databases
 Create tables
 Insert records
 Fetch records
 Update and delete records

1.1 What is MySQL?


MySQL is a popular relational database management system.

It stores data in the form of:


Tables

Example:
Roll No Name Marks
1 Raj 85
2 Amit 90

1.2 What is Database Interface?


A database interface is a bridge between:

Python Program and Database


It helps Python communicate with MySQL database.

Created by Rashesh Rehi 267


Sarvodaya College of Computer Science Programming in Python

Example
Python program sends query:
SELECT * FROM students;
MySQL returns result to Python.

1.3 MySQL Connector


MySQL connector is a Python library used to connect Python with MySQL.

Installation Command
pip install mysql-connector-python

1.4 Verifying Installation


After installation, open Python IDLE, VS Code, or terminal and run:
import [Link]
If no error appears, installation is successful.

Example Program
import [Link]
print("MySQL connector installed successfully")

Output
MySQL connector installed successfully

1.5 Checking Connector Version


import [Link]
print([Link].__version__)

Output Example
8.4.0

2. Working with MySQL Database

Introduction
Python can work with MySQL databases using:
mysql-connector-python

Created by Rashesh Rehi 268


Sarvodaya College of Computer Science Programming in Python

Python programs can:


 Create databases
 Create tables
 Insert records
 Display records
 Update records
 Delete records

2.1 Steps to Work with MySQL Database


Basic steps:
1. Import connector
2. Connect database
3. Create cursor
4. Execute SQL query
5. Commit changes
6. Close connection

Workflow Diagram

Created by Rashesh Rehi 269


Sarvodaya College of Computer Science Programming in Python

2.2 Importing MySQL Connector

Example
import [Link]

2.3 Connecting to MySQL Server

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password"
)

print("Connected Successfully")

Output
Connected Successfully

3. Using MySQL from Python

Introduction
Python can interact with MySQL databases using:
mysql-connector-python
Python programs can:
 Create databases
 Create tables
 Insert records
 Retrieve records
 Update records
 Delete records
This allows Python applications to store and manage data permanently.

Created by Rashesh Rehi 270


Sarvodaya College of Computer Science Programming in Python

Why Use MySQL with Python?


Using MySQL with Python helps:
1. Store data permanently
2. Manage large data easily
3. Create real-world applications
4. Handle user records
5. Build dynamic systems

3.1 Installing MySQL Connector


Python needs:
mysql-connector-python

Installation Command
pip install mysql-connector-python

Importing Connector
import [Link]

If Installation is Successful
No error appears.

3.2 Connecting Python with MySQL

Syntax
[Link](
host="localhost",
user="root",
password="your_password"
)

Example
import [Link]

connection = [Link](
host="localhost",
user="root",

Created by Rashesh Rehi 271


Sarvodaya College of Computer Science Programming in Python

password="your_password"
)
print("Connected Successfully")

Output
Connected Successfully

Explanation of Parameters
Parameter Meaning
host Database server
user Username
password MySQL password
database Database name

3.3 Creating Cursor Object


Cursor object is used to:
Execute SQL queries.

Example
cursor = [Link]()

Why Cursor is Important?


Cursor helps:
1. Execute queries
2. Fetch records
3. Communicate with database

3.4 Creating a Database

SQL Command
CREATE DATABASE school;

Python Program
import [Link]

Created by Rashesh Rehi 272


Sarvodaya College of Computer Science Programming in Python

connection = [Link](
host="localhost",
user="root",
password="your_password"
)

cursor = [Link]()
[Link]("CREATE DATABASE school")
print("Database Created")

Output
Database Created

Explanation
execute() runs SQL query.

3.5 Displaying Databases

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password"
)

cursor = [Link]()
[Link]("SHOW DATABASES")

for db in cursor:
print(db)

Created by Rashesh Rehi 273


Sarvodaya College of Computer Science Programming in Python

Output Example
('school',)
('mysql',)
('test',)

3.6 Connecting Specific Database

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)

print("Connected to school database")

3.7 Closing Database Connection

Example
[Link]()

Why Close Connection?


1. Saves memory
2. Improves performance
3. Prevents server overload

4. Creating Database Tables through Python

Introduction
A database stores information in the form of:
Tables
Python can create MySQL database tables using:

Created by Rashesh Rehi 274


Sarvodaya College of Computer Science Programming in Python

mysql-connector-python
Tables help organize data into:
 Rows
 Columns
Python programs can automatically create tables using SQL queries.

Database Table Diagram

4.1 Requirements
Before creating tables:
1. MySQL must be installed
2. mysql-connector-python must be installed
3. Database connection should work

4.2 SQL CREATE TABLE Command


SQL command used:

Created by Rashesh Rehi 275


Sarvodaya College of Computer Science Programming in Python

CREATE TABLE table_name(


column1 datatype,
column2 datatype
);

Example
CREATE TABLE students(
rollno INT,
name VARCHAR(50),
marks INT
);

Explanation
Column Data Type
rollno Integer
name Text
marks Integer

4.3 Creating Table Using Python

Example Program
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()

query = """
CREATE TABLE students(
rollno INT,
name VARCHAR(50),
marks INT
Created by Rashesh Rehi 276
Sarvodaya College of Computer Science Programming in Python

)
"""
[Link](query)
print("Table Created Successfully")

Output
Table Created Successfully

4.4 Common SQL Data Types


Data Type Purpose
INT Integer values
VARCHAR Variable-length text
FLOAT Decimal values
DATE Date values
CHAR Fixed-length text

Example
CREATE TABLE employee(
empid INT,
name VARCHAR(50),
salary FLOAT
);

4.5 Creating Table with Primary Key


Primary key uniquely identifies records.

Example
CREATE TABLE students(
rollno INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);

Why Primary Key is Important?


1. Prevents duplicate records

Created by Rashesh Rehi 277


Sarvodaya College of Computer Science Programming in Python

2. Uniquely identifies rows

4.6 Creating Multiple Tables

Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("""
CREATE TABLE teachers(
id INT,
name VARCHAR(50)
)
""")

[Link]("""
CREATE TABLE subjects(
subid INT,
subname VARCHAR(50)
)
""")
print("Tables Created")

4.7 Displaying Existing Tables

SQL Command
SHOW TABLES;

Python Program
import [Link]
connection = [Link](

Created by Rashesh Rehi 278


Sarvodaya College of Computer Science Programming in Python

host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("SHOW TABLES")
for table in cursor:
print(table)

Output Example
('students',)
('teachers',)

4.8 Describing Table Structure

SQL Command
DESC students;

Python Program
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("DESC students")

for row in cursor:


print(row)

Created by Rashesh Rehi 279


Sarvodaya College of Computer Science Programming in Python

Output Example
('rollno', 'int', 'YES', '', None, '')
('name', 'varchar(50)', 'YES', '', None, '')

4.9 Using IF NOT EXISTS


Avoids duplicate table creation errors.

Example
CREATE TABLE IF NOT EXISTS students(
rollno INT,
name VARCHAR(50)
);

Python Program
[Link]("""
CREATE TABLE IF NOT EXISTS students(
rollno INT,
name VARCHAR(50)
)
""")

Advantages
1. Prevents errors
2. Safer execution

5. Retrieving All Rows from a Table

Introduction
In MySQL databases, data is stored inside:
Tables
Python can retrieve data from database tables using:
SELECT query
and:
mysql-connector-python
Retrieving rows means:

Created by Rashesh Rehi 280


Sarvodaya College of Computer Science Programming in Python

Reading records stored in database tables.

Example Student Table


Roll No Name Marks
1 Raj 85
2 Amit 90
3 Neha 88

5.1 SQL SELECT Query


The SQL query used is:
SELECT * FROM students;

Query Explanation
Query Part Meaning
SELECT Retrieve data
* All columns
FROM students From students table

5.2 Executing SELECT Query

Example
[Link]("SELECT * FROM students")

Explanation
execute() runs SQL command.

5.3 fetchall() Method


fetchall() retrieves:
All rows from query result.

Example
records = [Link]()

Explanation

Created by Rashesh Rehi 281


Sarvodaya College of Computer Science Programming in Python

fetchall() returns:
 List of tuples

Example Result
[
(1, 'Raj', 85),
(2, 'Amit', 90)
]

5.4 Complete Program


Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)
[Link]()

Output Example
(1, 'Raj', 85)
(2, 'Amit', 90)
(3, 'Neha', 88)

5.5 fetchone() Method


fetchone() retrieves:
Only one row

Created by Rashesh Rehi 282


Sarvodaya College of Computer Science Programming in Python

Example
[Link]("SELECT * FROM students")
row = [Link]()
print(row)

Output Example
(1, 'Raj', 85)

fetchall() vs fetchone()
Method Purpose
fetchall() Retrieve all rows
fetchone() Retrieve single row

5.6 Retrieving Specific Columns


SQL Query
SELECT name, marks FROM students;
Python Program
[Link](
"SELECT name, marks FROM students"
)

records = [Link]()
for row in records:
print(row)

Output Example
('Raj', 85)
('Amit', 90)

Advantages
1. Faster retrieval
2. Less memory usage

5.7 Using WHERE Clause


Retrieve selected rows only.

Created by Rashesh Rehi 283


Sarvodaya College of Computer Science Programming in Python

SQL Query
SELECT * FROM students
WHERE marks > 85;

Python Program
[Link]("""
SELECT * FROM students
WHERE marks > 85
""")
records = [Link]()

for row in records:


print(row)

Output Example
(2, 'Amit', 90)
(3, 'Neha', 88)

5.8 Counting Rows

SQL Query
SELECT COUNT(*) FROM students;

Python Program
[Link](
"SELECT COUNT(*) FROM students"
)
count = [Link]()
print("Total Rows:", count[0])

Output
Total Rows: 3

5.9 Error Handling


Errors may occur due to:
 Wrong table name

Created by Rashesh Rehi 284


Sarvodaya College of Computer Science Programming in Python

 Database connection issue


 SQL syntax error

Example
import [Link]

try:
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)
except [Link] as e:
print("Error:", e)

6. Inserting Rows into a Table

Introduction
In MySQL databases, data is stored in:
Tables

Each record stored in a table is called:


Row

Python can insert rows into MySQL tables using:


INSERT query

and:
mysql-connector-python

Created by Rashesh Rehi 285


Sarvodaya College of Computer Science Programming in Python

Example Student Table


Roll No Name Marks
1 Raj 85
2 Amit 90

6.1 SQL INSERT Query


SQL command used:
INSERT INTO students
VALUES(1, 'Raj', 85);

Query Explanation
Part Meaning
INSERT INTO Insert record
students Table name
VALUES Values to insert

6.2 Inserting Single Row

Python Program
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
INSERT INTO students
VALUES(1, 'Raj', 85)
"""
[Link](query)
[Link]()
print("Record Inserted")

Created by Rashesh Rehi 286


Sarvodaya College of Computer Science Programming in Python

Output
Record Inserted

Why commit() is Important?


commit() saves changes permanently.
Without commit():
 Inserted data may not save.

6.3 Understanding execute()


execute() runs SQL query.

Example
[Link](query)

Workflow
1. Query sent to MySQL
2. MySQL executes query
3. Data inserted into table

6.4 Inserting Multiple Rows


Python supports inserting multiple records together.

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
INSERT INTO students
VALUES(%s, %s, %s)
"""

Created by Rashesh Rehi 287


Sarvodaya College of Computer Science Programming in Python

data = [
(1, "Raj", 85),
(2, "Amit", 90),
(3, "Neha", 88)
]
[Link](query, data)
[Link]()
print("Multiple Records Inserted")

Output
Multiple Records Inserted

executemany() Function
executemany() inserts:
Multiple rows together.

6.5 Using Parameters Safely


Using %s placeholders improves:
1. Security
2. Flexibility
3. Prevents SQL injection

Example
query = """
INSERT INTO students
VALUES(%s, %s, %s)
"""

6.6 Inserting User Input

Example
import [Link]

connection = [Link](
host="localhost",
user="root",

Created by Rashesh Rehi 288


Sarvodaya College of Computer Science Programming in Python

password="your_password",
database="school"
)
cursor = [Link]()
roll = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
query = """
INSERT INTO students
VALUES(%s, %s, %s)
"""
values = (roll, name, marks)
[Link](query, values)
[Link]()
print("Record Inserted")

Output Example
Enter Roll No: 4
Enter Name: Kiran
Enter Marks: 92
Record Inserted
6.7 rowcount Property
rowcount shows:
Number of inserted rows

Example
print([Link], "record inserted")

Output Example
1 record inserted

6.8 Error Handling


Errors may occur due to:
 Duplicate primary key
 Wrong datatype
 SQL syntax error

Created by Rashesh Rehi 289


Sarvodaya College of Computer Science Programming in Python

Example
import [Link]
try:
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
INSERT INTO students
VALUES(1, 'Raj', 85)
"""
[Link](query)
[Link]()
print("Inserted")
except [Link] as e:
print("Error:", e)

7. Updating Rows in a Table

Introduction
In MySQL databases, stored records can be modified using:
UPDATE query
Python can update rows in MySQL tables using:
mysql-connector-python

Updating rows means:


Changing existing data inside database tables.

Example Student Table


Roll No Name Marks
1 Raj 85
2 Amit 90

Created by Rashesh Rehi 290


Sarvodaya College of Computer Science Programming in Python

Example After Update


Roll No Name Marks
1 Raj 95
2 Amit 90

7.1 SQL UPDATE Query


SQL command used:
UPDATE students
SET marks = 95
WHERE rollno = 1;

Query Explanation
Part Meaning
UPDATE students Update table
SET New value
WHERE Select row

Important Note
Without:
WHERE clause
all rows may update.

7.2 Updating Single Row

Python Program
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """

Created by Rashesh Rehi 291


Sarvodaya College of Computer Science Programming in Python

UPDATE students
SET marks = 95
WHERE rollno = 1
"""
[Link](query)
[Link]()
print("Record Updated")

Output
Record Updated

7.3 Displaying Updated Records

Example
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)

Output Example
(1, 'Raj', 95)
(2, 'Amit', 90)

7.4 Updating Multiple Columns

SQL Query
UPDATE students
SET name = 'Ravi',
marks = 92
WHERE rollno = 1;

Python Program
query = """
UPDATE students
SET name = 'Ravi',
marks = 92

Created by Rashesh Rehi 292


Sarvodaya College of Computer Science Programming in Python

WHERE rollno = 1
"""
[Link](query)
[Link]()

7.5 Using Parameterized Query


Parameterized queries improve:
1. Security
2. Flexibility
3. Prevent SQL injection

Example
query = """
UPDATE students
SET marks = %s
WHERE rollno = %s
"""
values = (98, 1)
[Link](query, values)
[Link]()

Advantages
1. Safer queries
2. Dynamic values
3. Better programming practice

7.6 Updating User Input

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"

Created by Rashesh Rehi 293


Sarvodaya College of Computer Science Programming in Python

)
cursor = [Link]()
roll = int(input("Enter Roll No: "))
marks = int(input("Enter New Marks: "))
query = """
UPDATE students
SET marks = %s
WHERE rollno = %s
"""
values = (marks, roll)
[Link](query, values)
[Link]()
print("Record Updated")

Output Example
Enter Roll No: 1
Enter New Marks: 99
Record Updated

7.7 rowcount Property


rowcount shows:
Number of updated rows
Example
print([Link], "record updated")
Output Example
1 record updated

7.8 Error Handling


Errors may occur due to:
 Wrong table name
 Wrong column name
 SQL syntax error

Example
import [Link]

Created by Rashesh Rehi 294


Sarvodaya College of Computer Science Programming in Python

try:
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
UPDATE students
SET marks = 95
WHERE rollno = 1
"""
[Link](query)
[Link]()
print("Updated")
except [Link] as e:
print("Error:", e)

8. Deleting Rows from a Table

Introduction
In MySQL databases, records stored inside tables can be removed using:
DELETE query
Python can delete rows from MySQL tables using:
mysql-connector-python
Deleting rows means:
Removing records from database tables permanently.

Example Student Table Before Delete


Roll No Name Marks
1 Raj 85
2 Amit 90
3 Neha 88

Created by Rashesh Rehi 295


Sarvodaya College of Computer Science Programming in Python

Example After Delete


Roll No Name Marks
1 Raj 85
3 Neha 88

8.1 SQL DELETE Query


SQL command used:
DELETE FROM students
WHERE rollno = 2;

Query Explanation
Part Meaning
DELETE FROM Remove records
students Table name
WHERE Select row

Important Note
Without:
WHERE clause
all rows may be deleted.

8.2 Deleting Single Row

Python Program
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
DELETE FROM students

Created by Rashesh Rehi 296


Sarvodaya College of Computer Science Programming in Python

WHERE rollno = 2
"""
[Link](query)
[Link]()
print("Record Deleted")

Output
Record Deleted

8.3 Displaying Remaining Records

Example
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)

Output Example
(1, 'Raj', 85)
(3, 'Neha', 88)

8.4 Using Parameterized DELETE Query


Parameterized queries improve:
1. Security
2. Flexibility
3. Prevent SQL injection

Example
query = """
DELETE FROM students
WHERE rollno = %s
"""
value = (2,)
[Link](query, value)
[Link]()

Created by Rashesh Rehi 297


Sarvodaya College of Computer Science Programming in Python

Advantages
1. Safe queries
2. Dynamic values
3. Better coding practice

8.5 Deleting Records Using User Input

Example
import [Link]

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
roll = int(input("Enter Roll No to Delete: "))
query = """
DELETE FROM students
WHERE rollno = %s
"""
value = (roll,)
[Link](query, value)
[Link]()
print("Record Deleted")

Output Example
Enter Roll No to Delete: 3
Record Deleted

8.6 rowcount Property


rowcount shows:
Number of deleted rows

Created by Rashesh Rehi 298


Sarvodaya College of Computer Science Programming in Python

Example
print([Link], "record deleted")

Output Example
1 record deleted

8.7 Deleting Multiple Rows

SQL Query
DELETE FROM students
WHERE marks < 40;

Python Program
query = """
DELETE FROM students
WHERE marks < 40
"""
[Link](query)
[Link]()
print([Link], "records deleted")

8.8 Difference Between DELETE and DROP


DELETE DROP
Removes rows Removes whole table
Table remains Table deleted completely
Example
DROP TABLE students;

8.9 Error Handling


Errors may occur due to:
 Wrong table name
 Wrong column name
 SQL syntax error

Created by Rashesh Rehi 299


Sarvodaya College of Computer Science Programming in Python

Example
import [Link]

try:

connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)

cursor = [Link]()
query = """
DELETE FROM students
WHERE rollno = 2
"""

[Link](query)
[Link]()
print("Deleted")

except [Link] as e:
print("Error:", e)

----------**********----------

Created by Rashesh Rehi 300


Sarvodaya College of Computer Science Programming in Python

1 Mark Questions
1. What is MySQL?
2. What is database?
3. What is [Link]?
4. What is cursor?
5. What is SQL?
6. What is SELECT query?
7. What is INSERT query?
8. What is UPDATE query?
9. What is DELETE query?
[Link] is CREATE TABLE command?
[Link] is commit()?
[Link] is fetchall()?
[Link] is fetchone()?
[Link] is primary key?
[Link] is rowcount?

2 Marks Questions
1. Explain MySQL database interface installation.
2. Explain connecting MySQL with Python.
3. Explain cursor object.
4. Explain retrieving rows using SELECT query.
5. Explain inserting rows into table.
6. Explain updating rows in table.
7. Explain deleting rows from table.
8. Explain creating database tables through Python.
9. Explain fetchall() and fetchone().
[Link] commit() method.

5 Marks Questions
1. Explain working with MySQL database in Python.
2. Explain using MySQL from Python with example.
3. Explain retrieving all rows from a table.
4. Explain inserting rows into a table with example.
5. Explain deleting rows from a table with example.
6. Explain updating rows in a table with example.

Created by Rashesh Rehi 301


Sarvodaya College of Computer Science Programming in Python

7. Explain creating database tables through Python.


8. Explain Python-MySQL connectivity process.
9. Explain CRUD operations in MySQL using Python.
[Link] parameterized queries with examples.

Practical Tasks
1. Install mysql-connector-python.
2. Connect Python with MySQL database.
3. Create database using Python.
4. Create table using Python.
5. Insert records into table.
6. Retrieve all records from table.
7. Update records in table.
8. Delete records from table.
9. Use fetchall() and fetchone().
[Link] complete student database management program.

END OF UNIT 5

Created by Rashesh Rehi 302

You might also like