Programming in Python
Programming in Python
MATERIAL
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
Example
a = 10
print(a)
In this example:
Token Type
a Identifier
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.
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
Functions
Classes
Modules
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)
Float
Stores decimal numbers.
price = 99.99
print(type(price))
name = "Python"
print(type(name))
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
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
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
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.
Multi-line Comment
"""
This is
multi-line comment
"""
Advantages of Comments
1. Improves readability
2. Helps debugging
3. Makes code understandable
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
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.
Example
name = input("Enter your name: ")
print(name)
Example
x = "10"
y = int(x)
print(y)
print(type(y))
3. Branching Programs
Example:
If it is raining, take umbrella.
If marks are greater than 40, student passes.
If balance is low, recharge mobile.
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.
Output
Positive Number
Syntax
if condition:
statements
else:
statements
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output
Odd Number
Syntax
if condition1:
if condition2:
statements
if a > b:
if a > c:
print("A is largest")
Advantages of Nested if
1. Useful for complex conditions
Disadvantages of Nested if
1. Program becomes lengthy
2. Difficult to understand
3. Hard to debug
Syntax
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
Output
Grade B
Flowchart of if-elif-else
Example Using or
a=5
b = 10
if a > 0 or b > 0:
print("Positive Number Exists")
if not is_raining:
print("Go Outside")
Operator Meaning
< Smaller
>= Greater or Equal
<= Smaller or Equal
Example
a = 10
b = 20
if a < b:
print("A is smaller")
Correct Example
if 5 > 2:
print("Correct")
Wrong Example
if 5 > 2:
print("Error")
This produces:
IndentationError
Syntax
if condition: statement
Example
a = 10
if a > 5: print("Greater")
Syntax
statement1 if condition else statement2
Example
num = 8
print("Even") if num % 2 == 0 else print("Odd")
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.
String Representation
Example
word = "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
Syntax
string[start:end]
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
print(text[:4])
print(text[2:])
Step Slicing
Syntax:
string[start:end:step]
Example
text = "PYTHON"
print(text[0:6:2])
Output
PTO
Output
NOHTYP
Example
name = "Python"
# name[0] = "J" ❌ Error
Correct Method
name = "Python"
new_name = "J" + name[1:]
print(new_name)
Example
a = "Hello"
b = "World"
print(a + " " + b)
Example
print("Python " * 3)
Membership Operators
Checks presence of character or substring.
Example
text = "Python"
print("P" in text)
print("z" not in text)
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.
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))
Example
print("Hello\nPython")
Output
Hello
Python
Syntax
input("message")
Example
name = input("Enter your name: ")
print(name)
Important Note
input() always returns string data.
Example
age = input("Enter age: ")
print(type(age))
Output
<class 'str'>
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)
Using format()
name = "Python"
print("Welcome {}".format(name))
Using f-string
Modern and easy method.
name = "Python"
print(f"Welcome {name}")
5. Iteration
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
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
Explanation
Step Value of i Condition
1 1 True
2 2 True
3 3 True
4 4 True
5 5 True
6 6 False
Output
Sum = 15
Example
while True:
print("Hello")
Output
1
2
3
4
5
Output
P
Y
T
H
O
N
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
Reverse Loop
for i in range(10, 0, -1):
print(i)
Output
10
9
8
7
6
5
4
3
2
1
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
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.
Example
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
4
5
Example
for i in range(5):
pass
Example
for i in range(5):
print(i)
else:
print("Loop Completed")
Output
0
1
2
3
4
Loop Completed
String Iteration
text = "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)
Dictionary Iteration
student = {
"name": "Ravi",
"marks": 90
}
Advantages of Functions
1. Code Reusability
2. Better Program Structure
3. Easy Debugging
4. Easy Maintenance
5. Reduces Code Length
Built-in Functions
Examples:
print()
len()
input()
type()
max()
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
Example
def hello():
print("Hello Student")
hello()
hello()
Output
Hello Student
Hello Student
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
Syntax
def function():
return value
Example
def square(n):
return n * n
result = square(5)
print(result)
Output
25
Example
def greet(name="Student"):
print("Hello", name)
greet()
greet("Ravi")
Output
Hello Student
Hello Ravi
Example
def student(name, age):
print(name, age)
student(age=21, name="Ravi")
Advantages
1. Order not important
2. Improves readability
Example
def total(*numbers):
sum = 0
for n in numbers:
sum += n
print(sum)
total(1, 2, 3)
Output
6
Local Variable
Declared inside function.
Accessible only inside function.
Example
def demo():
x = 10
print(x)
demo()
Output
10
This produces:
NameError
Global Variable
Declared outside function.
Accessible everywhere.
Example
x = 100
def show():
print(x)
show()
Output
100
Example
x = 10
def change():
global x
x = 50
change()
print(x)
Output
50
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
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
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)
Example
def multiply(a: int, b: int) -> int:
return a * b
Explanation
Part Meaning
a: int a should be integer
-> int returns integer
8. Recursion
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)
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
return n * factorial(n - 1)
print(factorial(5))
Output
120
9. Modules
Modules help organize large programs into smaller and manageable parts.
Instead of writing all code in one file, Python allows dividing code into modules.
Types of Modules
Python mainly provides:
1. Built-in Modules
2. User-defined Modules
Syntax
import module_name
Example
import math
print([Link](25))
Output
5.0
Explanation
Part Meaning
import Keyword
math Module name
sqrt() Function
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
Example
from math import sqrt, factorial
print(sqrt(16))
print(factorial(4))
Syntax
import module_name as alias
Example
import math as m
print([Link](49))
Output
7.0
Example
import math
print(dir(math))
Output
Displays all members of math module.
Example
import math
help([Link])
Advantages of help()
1. Understand functions
2. Learn parameters
3. View documentation
math Module
Provides mathematical functions.
Common Functions
Function Purpose
sqrt() Square root
factorial() Factorial
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)
def square(n):
return n * n
import mymodule
print([Link](10, 20))
print([Link](5))
Output
30
25
Example
if __name__ == "__main__":
print("Program running directly")
Importance
1. Avoid unwanted execution
2. Separate reusable code
Package Structure
mypackage/
[Link]
[Link]
Advantages of Packages
1. Better organization
2. Large project management
3. Avoid naming conflicts
1. Open File
2. Perform Operation
3. Close File
Syntax
file_object = open("filename", "mode")
Parameters
Parameter Meaning
filename Name of file
mode File operation mode
Example
file = open("[Link]", "r")
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]()
Example
file = open("[Link]", "a")
[Link]("\nPython Programming")
[Link]()
Example
file = open("[Link]", "x")
[Link]()
Syntax
[Link]()
Example
file = open("[Link]", "r")
print([Link]())
[Link]()
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]()
Example
file = open("[Link]", "w")
[Link]("Ravi")
[Link]()
Syntax
with open("[Link]", "mode") as file:
statements
Example
with open("[Link]", "r") as file:
print([Link]())
2. Cleaner code
3. Better memory handling
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]()
Example
file = open("[Link]", "rb")
data = [Link]()
[Link]()
11. Tuples
Immutable means:
Values cannot be changed after creation
Example
numbers = (10, 20, 30)
print(numbers)
Output
(10, 20, 30)
Characteristics of Tuples
1. Ordered collection
2. Immutable
3. Allows duplicate values
4. Supports indexing
5. Supports slicing
6. Faster than lists
Real-Life Example
Examples of fixed data:
Days of week
Months of year
GPS coordinates
Example
data = (1, 2, 3)
print(data)
Empty Tuple
t = ()
print(t)
Correct Example
t = (5,)
print(type(t))
Wrong Example
t = (5)
print(type(t))
Output
<class 'int'>
Example
t = 1, 2, 3
print(t)
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
Positive Indexing
Index starts from 0.
Example
t = ("Python", "Java", "C++")
print(t[0])
print(t[1])
Output
Python
Java
Negative Indexing
Value Python Java C++
Index -3 -2 -1
Example
t = ("Python", "Java", "C++")
print(t[-1])
Output
C++
Example
t = (10, 20, 30)
# t[0] = 100 ❌ Error
Error
TypeError
Concatenation
Joining tuples using +.
Example
a = (1, 2)
b = (3, 4)
print(a + b)
Output
(1, 2, 3, 4)
Membership Operators
Example
t = (10, 20, 30)
print(20 in t)
Output
True
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))
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))
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
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
Example
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
Empty List
empty = []
print(empty)
Nested List
List inside another list.
Example
matrix = [[1, 2], [3, 4]]
print(matrix)
Positive Indexing
Index starts from 0.
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
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])
Output
[4, 3, 2, 1]
Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output
[10, 50, 30]
Concatenation
Joining lists using +.
Example
a = [1, 2]
b = [3, 4]
print(a + b)
Output
[1, 2, 3, 4]
Repetition
Using *.
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
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.
numbers = [1, 2, 3]
print(sum(numbers))
sorted()
Returns sorted list.
numbers = [30, 10, 20]
print(sorted(numbers))
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)
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))
Example
matrix = [[1, 2], [3, 4]]
print(matrix[0])
print(matrix[1][1])
Output
[1, 2]
4
Syntax
[expression for variable in sequence]
Example
squares = [x * x for x in range(5)]
print(squares)
Output
[0, 1, 4, 9, 16]
Direct Assignment
a = [1, 2, 3]
b=a
Both refer same list.
copy() Method
a = [1, 2, 3]
b = [Link]()
print(b)
Simple Meaning
A function in Python is not just code.
It is also an object that can be used like variables and data.
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()
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
Example
def outer():
def inner():
print("Inner Function")
return inner
x = outer()
x()
Output
Inner Function
Explanation
1. outer() returns inner function
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.
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}
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
Syntax
dictionary = {
key1: value1,
key2: value2
}
Example
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2025
}
print(car)
Empty Dictionary
data = {}
print(data)
Example
student = {
"name": "Ravi",
"marks": 90
}
print(student["name"])
Output
Ravi
Example
student = {
"name": "Ravi"
}
print([Link]("name"))
Output
None
Example
student = {
"name": "Ravi",
"marks": 80
}
student["marks"] = 95
print(student)
Output
{'name': 'Ravi', 'marks': 95}
Output
{'name': 'Ravi', 'age': 21}
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
}
[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)
len()
Returns total key-value pairs.
data = {
"a": 1,
"b": 2
}
print(len(data))
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))
keys()
Returns all keys.
student = {
"name": "Ravi",
"age": 21
}
print([Link]())
values()
Returns all values.
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)
}
for key, value in [Link]():
print(key, value)
Example
students = {
"student1": {
"name": "Ravi",
"marks": 90
},
"student2": {
"name": "Raj",
"marks": 85
}
}
print(students)
-----------**********----------
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?
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
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.
Syntax Error
Occurs due to wrong Python syntax.
Example
print("Hello"
Output
SyntaxError
Example
a = 10
b=0
print(a / b)
Output
ZeroDivisionError
Output
IndexError
Syntax
try:
statements
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
Example
try:
number = int(input("Enter number: "))
print(number)
except ValueError:
print("Invalid Input")
Output Example
Invalid Input
Syntax
try:
statements
except:
statements
else:
statements
Example
try:
a = 10
b=2
print(a / b)
except ZeroDivisionError:
print("Error")
else:
print("Division Successful")
Output
5.0
Division Successful
Syntax
try:
statements
except:
statements
finally:
statements
Example
try:
print(10 / 2)
except:
print("Error")
finally:
print("Program Finished")
Output
5.0
Program Finished
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
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")
Output
AssertionError
Exceptions can be used not only for handling errors, but also for controlling the
flow of a program.
This concept is called:
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.
Output
Step 1
Step 2
Step 3
print(10 / 0)
print("Step 3")
Output
ZeroDivisionError
Program stops immediately.
print("Step 1")
print(10 / 0)
print("Step 2")
except ZeroDivisionError:
print("Error Handled")
print("Program Continues")
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
Syntax of Assertion
assert condition
Example
x = 10
assert x > 0
print("Valid Number")
Output
Valid Number
Explanation
Condition:
x>0
is:
True
So:
Program runs normally
Example
x = -5
assert x > 0
print("Valid Number")
Output
AssertionError
Explanation
Condition:
x>0
is:
False
So:
AssertionError occurs
Syntax
assert condition, "message"
Example
age = -1
Output
AssertionError: Age cannot be negative
Output
Valid Marks
Output
AssertionError: Marks cannot exceed 100
Example
def divide(a, b):
assert b != 0, "Division by zero not allowed"
return a / b
print(divide(10, 2))
Output
5.0
Output
AssertionError:
Division by zero not allowed
Example
numbers = [2, 4, 6]
for n in numbers:
assert n % 2 == 0
print("All numbers are even")
Output
All numbers are even
Output
AssertionError:
Odd number found
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.
What is a Class?
A class is a blueprint or template used to create objects.
A class contains:
Variables (data)
Functions (methods)
Class Diagram
Syntax
class ClassName:
statements
Example
class Student:
name = "Ravi"
print([Link])
Output
Ravi
Explanation
Part Meaning
class Keyword
Student Class name
name Variable
Syntax
object_name = ClassName()
Example
class Car:
brand = "Toyota"
c1 = Car()
print([Link])
Output
Toyota
Syntax
class ClassName:
def __init__(self):
statements
Example
class Student:
def __init__(self):
print("Constructor Called")
s1 = Student()
Output
Constructor Called
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
Example
class Calculator:
def add(self, a, b):
return a + b
c1 = Calculator()
print([Link](5, 3))
Output
8
Example
class Student:
s1 = Student()
s2 = Student()
print([Link])
print([Link])
Output
ABC School
ABC School
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
Stack Diagram
def __init__(self):
[Link] = []
def pop(self):
return [Link]()
s = Stack()
[Link](10)
[Link](20)
print([Link]())
Output
20
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
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.
Example
class Parent:
pass
class Child(Parent):
pass
Explanation
Child class inherits Parent class.
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]()
Output
Animal makes sound
Explanation
Dog inherits method from Animal class.
Diagram
Example
class Father:
def show(self):
print("Father Class")
class Son(Father):
pass
s = Son()
[Link]()
Output
Father Class
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
Diagram
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
Diagram
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
Example Structure
class A:
pass
class B(A):
pass
class C(A):
pass
def sound(self):
print("Animal Sound")
class Dog(Animal):
def sound(self):
print("Bark")
d = Dog()
[Link]()
Output
Bark
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
Introduction
Encapsulation and Information Hiding are important concepts of Object-Oriented
Programming (OOP).
Encapsulation combines:
Data
Methods
Encapsulation means:
Wrapping data and functions together into one unit.
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.
Encapsulation Diagram
Example
class Student:
def __init__(self):
[Link] = "Ravi"
def display(self):
print([Link])
s1 = Student()
[Link]()
Output
Ravi
Explanation
Part Meaning
name Data
display() Method
Student Encapsulated unit
Encapsulation Working
Data and methods are combined together.
Example
class Car:
def __init__(self):
[Link] = "Toyota"
def show(self):
print([Link])
Example
class Student:
def __init__(self):
[Link] = "Ravi"
s1 = Student()
print([Link])
Output
Ravi
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
Example
class Bank:
def __init__(self):
self.__balance = 1000
b1 = Bank()
# print(b1.__balance) ❌Error
Output
AttributeError
Example
class Bank:
def __init__(self):
self.__balance = 5000
def show_balance(self):
print(self.__balance)
b1 = Bank()
b1.show_balance()
Output
5000
Example
class Student:
def __init__(self):
self.__marks = 80
def get_marks(self):
return self.__marks
s1 = Student()
print(s1.get_marks())
Output
80
Example
class Student:
def __init__(self):
self.__marks = 0
def set_marks(self, m):
if m >= 0:
self.__marks = m
def get_marks(self):
return self.__marks
s1 = Student()
s1.set_marks(95)
print(s1.get_marks())
Output
95
Example
class Demo:
def __init__(self):
self.__value = 10
d = Demo()
print(d._Demo__value)
Output
10
Explanation
Python converts:
__value
to:
_Demo__value
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
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
Introduction to Searching
Searching means:
Finding a specific element from collection of data.
Working
1. Start from first element
2. Compare target value
3. Continue until element found
Example
List:
[10, 20, 30, 40, 50]
Search:
30
Program
numbers = [10, 20, 30, 40, 50]
search = 30
found = False
for i in numbers:
if i == search:
found = True
break
if found:
print("Element Found")
else:
print("Element Not Found")
Output
Element Found
Disadvantages
1. Slow for large data
2. More comparisons
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
Example
Sorted List:
[10, 20, 30, 40, 50]
Search:
40
Program
numbers = [10, 20, 30, 40, 50]
search = 40
low = 0
high = len(numbers) - 1
found = False
Output
Element Found
Disadvantages
1. Requires sorted data
2. Slightly complex
Introduction to Sorting
Sorting means:
Arranging data in ascending or descending order.
Types of Sorting
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
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
Working
1. Find minimum value
2. Swap with first position
3. Repeat remaining list
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
Disadvantages
1. Slow for large data
Real-Life Example
Playing cards arrangement.
Program
numbers = [12, 11, 13, 5, 6]
Output
[5, 6, 11, 12, 13]
Advantages
1. Efficient for small data
2. Stable sorting
Disadvantages
1. Slow for large data
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)
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.
Real-Life Example
Suppose a library stores books using:
Book ID → Book details
Hashtable Diagram
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.
Example
student = {
"101": "Ravi",
"102": "Raj"
}
print(student["101"])
Output
Ravi
Explanation
Python internally uses hashing to access value quickly.
Example
print(hash("Python"))
Output Example
-145632478
Important Note
Hash values may vary on different systems.
Example
Suppose:
Key Hash Index
15 5
25 5
Example
student = {
"name": "Ravi",
"age": 21
}
print(student["name"])
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)
----------**********----------
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.
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
Introduction to PyLab
PyLab is a Python module used for:
Data visualization
Mathematical plotting
Scientific computing
Simple Meaning
PyLab is used to:
Draw graphs and visualize data in Python.
Real-Life Examples
1. Student result analysis
2. Weather forecasting
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 *
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.
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.
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
principal = 1000000
annual_rate = 8
years = 10
Output
Monthly Payment: 12132.76
Explanation
This program calculates the fixed monthly amount paid by borrower.
principal = 1000000
annual_rate = 8
years = 10
balance = principal
balances = []
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
principal = 1000000
annual_rate = 8
years = 10
monthly_rate = annual_rate / 12 / 100
months = years * 12
balance = principal
interest_list = []
principal_list = []
interest_list.append(interest)
principal_list.append(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
Introduction
The Fibonacci Sequence is one of the most famous mathematical sequences used
in:
Mathematics
Computer Science
Algorithms
Nature
Artificial Intelligence
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)
Output
0
1
1
2
3
5
8
13
21
34
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
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
Program
from pylab import *
n = 10
fib = [0, 1]
plot(range(n), fib)
xlabel("Position")
ylabel("Fibonacci Number")
title("Fibonacci Sequence")
grid(True)
show()
Output
Fibonacci graph displayed.
Introduction
Dynamic Programming (DP) is an important problem-solving technique used in:
Algorithms
Artificial Intelligence
Optimization
Data Science
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.
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
Output
55
Advantages of Tabulation
1. Faster execution
2. No recursion overhead
3. Better memory control
Real-Life Example
Suppose a thief steals items:
Gold
Laptop
Mobile
But bag capacity is limited.
Knapsack Diagram
0/1 Knapsack
Item is either:
Taken completely
OR
Not taken
No partial selection allowed.
Example
Item Weight Profit
1 1 10
2 3 40
3 4 50
4 5 70
Capacity:
8
Goal
Choose items giving maximum profit.
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)
Output
110
Explanation
Maximum profit:
40 + 70 = 110
Solution:
Dynamic Programming
Program: DP Knapsack
def knapsack(W, wt, val, n):
dp = [[0 for x in range(W + 1)] for x in range(n + 1)]
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
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
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.
Dynamic Programming
Students share notes to avoid repeating same work.
Program
def binary_search(arr, low, high, target):
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
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?
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
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
Real-Life Example
Suppose two people speak:
Same language
Same communication rules
Then communication becomes easy.
Similarly:
Computers use protocols.
Protocol Diagram
Features of TCP
1. Connection-oriented
2. Reliable
3. Slower but accurate
Applications of TCP
1. Email
2. Banking systems
3. Web applications
Features of UDP
1. Connectionless
2. Faster
3. Less reliable
Applications of UDP
1. Online gaming
2. Video streaming
3. Live broadcasting
1.2 IP Address
IP Address means:
Unique address of computer on network.
Example
[Link]
Types of IP Address
1. IPv4
2. IPv6
Example
Port Service
80 HTTP
443 HTTPS
21 FTP
Real-Life Example
Socket works like:
Telephone connection
One side:
Sends data
Other side:
Receives data
Types of Socket
Socket Type Purpose
TCP Socket Reliable communication
UDP Socket Fast communication
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
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
Example
import socket
server = [Link]()
[Link](("localhost", 9999))
[Link](1)
print("Waiting for connection...")
Explanation
Function Purpose
bind() Assign IP and port
listen() Wait for connection
accept() Accept client
send() Send data
Example
import socket
client = [Link]()
[Link](("localhost", 9999))
message = [Link](1024)
print([Link]())
[Link]()
Output
Welcome Client
Sending Data
[Link]()
Receiving Data
[Link]()
Example
[Link](b"Hello")
Example
data = [Link](1024)
1024 Meaning
Server
import socket
Client
import socket
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
Types of IP Addresses
Mainly:
1. IPv4
2. IPv6
Format of IPv4
[Link]
Structure
IPv4 contains:
Four numbers
Separated by dots
Example
2001:0db8:85a3:0000:0000:8a2e:0370:7334
Advantages of IPv6
1. More addresses
2. Better security
3. Faster routing
hostname = [Link]()
print(hostname)
Output Example
DESKTOP-ABC123
Explanation
gethostname() returns:
Computer name
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
Example
import socket
ip = [Link]("[Link]")
print(ip)
Output Example
[Link]
Explanation
DNS converts:
Domain name
to
IP address
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
Example URL
[Link]
Example Breakdown
[Link]
Explanation
Part Meaning
https Protocol
[Link] Domain
[Link] Web page
HTML defines:
Text
Images
Links
Structure
Example HTML
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Import urllib
import [Link]
Syntax
[Link](url)
Example
import [Link]
page = [Link]("[Link]
print(page)
Output Example
<[Link] object>
Explanation
urlopen():
Opens webpage connection
Example
import [Link]
page = [Link]("[Link]
source = [Link]()
print(source)
Output
HTML source code displayed.
Example
import [Link]
page = [Link]("[Link]
source = [Link]().decode()
print(source)
Explanation
Function Purpose
read() Reads webpage
decode() Converts bytes to text
Example
import [Link]
page = [Link]("[Link]
for line in page:
print([Link]())
Output
Displays webpage line by line.
Example
import [Link]
url = [Link]
[Link](url, "python_page.html")
Explanation
Downloads webpage into local file.
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
Introduction
Python allows us to:
Connect to websites
Access webpages
Download webpage content from the internet
urllib module
for downloading webpages.
Importing urllib
import [Link]
Syntax
[Link](url)
Example
import [Link]
page = [Link]("[Link]
print(page)
Output Example
<[Link] object>
Explanation
urlopen():
Connects to website
Returns webpage object
Example
import [Link]
page = [Link]("[Link]
content = [Link]()
print(content)
Output
HTML content displayed in bytes.
Example
import [Link]
page = [Link]("[Link]
content = [Link]().decode()
print(content)
Explanation
Function Purpose
read() Reads webpage
decode() Converts bytes to text
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
Steps
1. Locate downloaded file
2. Double-click file
3. Browser opens webpage
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
Example
import [Link]
page = [Link]("[Link]
content = [Link]().decode()
print("Saved")
Explanation
Program:
1. Downloads webpage
2. Reads source code
3. Saves into local file
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
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?
Syntax
[Link](
image_url,
filename
)
Example
import [Link]
image_url = "[Link]
[Link](
image_url,
"python_logo.png"
)
print("Image Downloaded")
Output
Image Downloaded
Result
Image saved into current folder.
Explanation
Part Meaning
image_url Internet image address
python_logo.png Saved image name
Example
import [Link]
images = [
"[Link]
"[Link]
[Link]"
]
Output Example
[Link] Downloaded
[Link] Downloaded
Example
import [Link]
page = [Link](
"[Link]
)
data = [Link]()
print(type(data))
Output
<class 'bytes'>
Explanation
Image data transfers in:
Bytes format
Example
import [Link]
url = "[Link]
response = [Link](url)
data = [Link]()
file = open("python_logo.png", "wb")
[Link](data)
[Link]()
print("Image Saved")
Installation of PIL
pip install pillow
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
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
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
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
Server Program
import socket
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.
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.
Server
import socket
server = [Link]()
[Link](("localhost", 9999))
[Link](1)
Created by Rashesh Rehi 207
Sarvodaya College of Computer Science Programming in Python
Client
import socket
client = [Link]()
[Link](("localhost", 9999))
[Link](b"Hello Server")
[Link]()
Output
Hello Server
Introduction
In network programming, computers communicate using:
Protocols
Two important protocols are:
1. TCP
2. UDP
This topic explains:
What is UDP?
UDP means:
User Datagram Protocol
UDP is a communication protocol used for:
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
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
server = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](("localhost", 9999))
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
1024 Meaning
Maximum bytes received.
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
Syntax
data, addr = [Link](1024)
Explanation
Variable Meaning
data Received message
addr Sender address
Syntax
[Link](data, address)
Example
[Link](
b"Hello",
("localhost", 9999)
)
Introduction
In network programming:
Computers can exchange files over networks.
This is done using:
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
server = [Link]()
[Link](("localhost", 9999))
[Link](1)
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
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
server = [Link]()
Created by Rashesh Rehi 217
Sarvodaya College of Computer Science Programming in Python
[Link](("localhost", 9999))
[Link](1)
while True:
data = [Link](1024)
if not data:
break
[Link](data)
[Link]()
[Link]()
[Link]()
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")
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.
Client
Requests services from server.
Communication Process
1. Server starts
2. Client connects
3. Client sends message
4. Server replies
5. Communication continues
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
Functions Used
Function Purpose
send() Send data
recv() Receive data
connect() Connect client
accept() Accept client
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
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
Encoding
Convert text into bytes.
Example
[Link]()
Decoding
Convert bytes into text.
Example
[Link]()
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]()
server = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](("localhost", 9999))
data, addr = [Link](1024)
print([Link]())
[Link](
b"Hello Client",
addr
)
client = [Link](
socket.AF_INET,
socket.SOCK_DGRAM
)
[Link](
b"Hello Server",
("localhost", 9999)
)
reply, addr = [Link](1024)
print([Link]())
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
Simple Meaning
Sending a simple mail means:
Real-Life Examples
1. OTP emails
2. Password reset emails
3. College notifications
4. Online shopping confirmations
5. Bank alerts
Features of SMTP
1. Email transmission
2. Reliable communication
3. Internet-based messaging
smtplib
for sending emails.
Importing smtplib
import smtplib
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"
)
[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:
App Password
OR
Less secure app access
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]",
message
)
[Link]()
print("Mail Sent")
Output
Mail Sent
Explanation
Email format contains:
1. Subject
2. Blank line
3. Body
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]",
receivers,
message
)
[Link]()
Example
import smtplib
message = """
Subject: HTML Mail
<h1>Hello</h1>
<p>This is HTML email</p>
"""
Introduction
GUI stands for:
Graphical User Interface
GUI allows users to interact with programs using:
Buttons
Menus
Textboxes
Windows
Icons
Tkinter
Example
In calculator application:
User clicks button
Event occurs
Program performs calculation
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.
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
Syntax
from tkinter import *
Explanation
Imports all Tkinter classes and functions.
Example
from tkinter import *
window = Tk()
Explanation
Tk() creates:
Main application window.
mainloop()
Example
[Link]()
window = Tk()
[Link]()
Output
A blank GUI window appears.
Example
[Link]("My First GUI")
Complete Example
from tkinter import *
window = Tk()
[Link]("My First GUI")
[Link]()
Output
Window title becomes:
My First GUI
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
Introduction
GUI applications use different components called:
Widgets
Widgets help users:
Enter data
Display information
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.
Syntax
Label(window, text="Text")
Example
from tkinter import *
window = Tk()
label = Label(
window,
text="Welcome to Python"
)
[Link]()
[Link]()
Output
Text appears on GUI window.
Explanation
Parameter Purpose
window Parent window
text Text displayed
Label Attributes
Attribute Purpose
text Display text
fg Text color
bg Background color
font Font style
window = Tk()
label = Label(
window,
text="Python GUI",
fg="blue",
bg="yellow",
font=("Arial", 16)
)
[Link]()
[Link]()
Syntax
Button(window, text="Button")
Example
from tkinter import *
window = Tk()
button = Button(
window,
text="Click Me"
)
[Link]()
[Link]()
Output
Button appears on window.
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
Attribute Purpose
bg Background color
font Font style
Syntax
Entry(window)
Example
from tkinter import *
window = Tk()
entry = Entry(window)
[Link]()
[Link]()
Output
Textbox appears on window.
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
Importing Messagebox
from tkinter import messagebox
Types of Dialogs
Dialog Purpose
showinfo() Information message
showwarning() Warning message
showerror() Error message
window = Tk()
[Link](
"Information",
"Welcome to Python GUI"
)
[Link]()
Output
Information popup appears.
window = Tk()
[Link](
"Warning",
"Invalid Input"
)
[Link]()
window = Tk()
[Link](
"Error",
"Login Failed"
)
[Link]()
def submit():
name = [Link]()
[Link](
"Message",
"Welcome " + name
)
window = Tk()
[Link]("Student Form")
label = Label(
window,
text="Enter Name"
)
[Link]()
entry = Entry(window)
[Link]()
button = Button(
window,
text="Submit",
command=submit
)
[Link]()
[Link]()
Output
GUI contains:
Label
Entry field
Button
Dialog box
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.
Syntax
widget = Widget(
window,
width=value,
height=value
)
Example
from tkinter import *
window = Tk()
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
window = Tk()
label = Label(
window,
text="Python GUI",
width=25,
height=3
)
[Link]()
[Link]()
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.
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
from tkinter import *
window = Tk()
label = Label(
window,
text="Python GUI",
fg="white",
bg="blue"
)
[Link]()
[Link]()
Output
White text on blue background.
window = Tk()
button = Button(
window,
text="Login",
fg="white",
bg="green"
)
[Link]()
[Link]()
Output
Green button with white text.
Example
from tkinter import *
window = Tk()
entry = Entry(
window,
width=30,
fg="blue",
bg="lightyellow",
font=("Arial", 14)
)
[Link]()
[Link]()
Output
Styled textbox appears.
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]()
Output
Styled label displayed.
Example
from tkinter import *
window = Tk()
label = Label(
window,
text="Python"
)
[Link]()
[Link](
fg="red",
bg="yellow",
font=("Arial", 20)
)
[Link]()
Introduction
GUI applications require:
Proper arrangement of widgets
Data display in tables
Organized interface design
Tkinter provides:
1. Treeview widget
2. Layout managers
Importing Treeview
from [Link] import Treeview
Example
from tkinter import *
from [Link] import Treeview
window = Tk()
tree = Treeview(window)
[Link]()
[Link]()
Output
Blank Treeview appears.
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
Statement Purpose
heading() Sets heading text
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.
Advantages of Treeview
1. Displays records neatly
2. Easy data management
3. Professional appearance
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
Example
from tkinter import *
window = Tk()
Label(
window,
text="Name"
).grid(row=0, column=0)
Entry(
window
).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
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
Layout Comparison
Layout Purpose
pack() Simple arrangement
grid() Table-like arrangement
place() Exact positioning
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.
Frame Diagram
Example
from tkinter import *
window = Tk()
top_frame = Frame(window)
top_frame.pack()
bottom_frame = Frame(window)
bottom_frame.pack()
Button(
top_frame,
text="Top Button"
).pack()
Button(
bottom_frame,
text="Bottom Button"
).pack()
[Link]()
Output
Buttons appear in different frame sections.
window = Tk()
[Link]("Student System")
frame = Frame(window)
[Link]()
tree = Treeview(
frame,
columns=("Roll", "Name")
)
[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?
[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.
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
Introduction
Python can connect with MySQL database using a database interface or
connector.
Example:
Roll No Name Marks
1 Raj 85
2 Amit 90
Example
Python program sends query:
SELECT * FROM students;
MySQL returns result to Python.
Installation Command
pip install mysql-connector-python
Example Program
import [Link]
print("MySQL connector installed successfully")
Output
MySQL connector installed successfully
Output Example
8.4.0
Introduction
Python can work with MySQL databases using:
mysql-connector-python
Workflow Diagram
Example
import [Link]
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password"
)
print("Connected Successfully")
Output
Connected Successfully
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.
Installation Command
pip install mysql-connector-python
Importing Connector
import [Link]
If Installation is Successful
No error appears.
Syntax
[Link](
host="localhost",
user="root",
password="your_password"
)
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
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
Example
cursor = [Link]()
SQL Command
CREATE DATABASE school;
Python Program
import [Link]
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.
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password"
)
cursor = [Link]()
[Link]("SHOW DATABASES")
for db in cursor:
print(db)
Output Example
('school',)
('mysql',)
('test',)
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
Example
[Link]()
Introduction
A database stores information in the form of:
Tables
Python can create MySQL database tables using:
mysql-connector-python
Tables help organize data into:
Rows
Columns
Python programs can automatically create tables using SQL queries.
4.1 Requirements
Before creating tables:
1. MySQL must be installed
2. mysql-connector-python must be installed
3. Database connection should work
Example
CREATE TABLE students(
rollno INT,
name VARCHAR(50),
marks INT
);
Explanation
Column Data Type
rollno Integer
name Text
marks Integer
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
Example
CREATE TABLE employee(
empid INT,
name VARCHAR(50),
salary FLOAT
);
Example
CREATE TABLE students(
rollno INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);
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")
SQL Command
SHOW TABLES;
Python Program
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("SHOW TABLES")
for table in cursor:
print(table)
Output Example
('students',)
('teachers',)
SQL Command
DESC students;
Python Program
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
[Link]("DESC students")
Output Example
('rollno', 'int', 'YES', '', None, '')
('name', 'varchar(50)', 'YES', '', None, '')
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
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:
Query Explanation
Query Part Meaning
SELECT Retrieve data
* All columns
FROM students From students table
Example
[Link]("SELECT * FROM students")
Explanation
execute() runs SQL command.
Example
records = [Link]()
Explanation
fetchall() returns:
List of tuples
Example Result
[
(1, 'Raj', 85),
(2, 'Amit', 90)
]
Output Example
(1, 'Raj', 85)
(2, 'Amit', 90)
(3, 'Neha', 88)
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
records = [Link]()
for row in records:
print(row)
Output Example
('Raj', 85)
('Amit', 90)
Advantages
1. Faster retrieval
2. Less memory usage
SQL Query
SELECT * FROM students
WHERE marks > 85;
Python Program
[Link]("""
SELECT * FROM students
WHERE marks > 85
""")
records = [Link]()
Output Example
(2, 'Amit', 90)
(3, 'Neha', 88)
SQL Query
SELECT COUNT(*) FROM students;
Python Program
[Link](
"SELECT COUNT(*) FROM students"
)
count = [Link]()
print("Total Rows:", count[0])
Output
Total Rows: 3
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)
Introduction
In MySQL databases, data is stored in:
Tables
and:
mysql-connector-python
Query Explanation
Part Meaning
INSERT INTO Insert record
students Table name
VALUES Values to insert
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")
Output
Record Inserted
Example
[Link](query)
Workflow
1. Query sent to MySQL
2. MySQL executes query
3. Data inserted into table
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
INSERT INTO students
VALUES(%s, %s, %s)
"""
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.
Example
query = """
INSERT INTO students
VALUES(%s, %s, %s)
"""
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
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
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)
Introduction
In MySQL databases, stored records can be modified using:
UPDATE query
Python can update rows in MySQL tables using:
mysql-connector-python
Query Explanation
Part Meaning
UPDATE students Update table
SET New value
WHERE Select row
Important Note
Without:
WHERE clause
all rows may update.
Python Program
import [Link]
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("Record Updated")
Output
Record Updated
Example
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)
Output Example
(1, 'Raj', 95)
(2, 'Amit', 90)
SQL Query
UPDATE students
SET name = 'Ravi',
marks = 92
WHERE rollno = 1;
Python Program
query = """
UPDATE students
SET name = 'Ravi',
marks = 92
WHERE rollno = 1
"""
[Link](query)
[Link]()
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
Example
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
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
Example
import [Link]
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)
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.
Query Explanation
Part Meaning
DELETE FROM Remove records
students Table name
WHERE Select row
Important Note
Without:
WHERE clause
all rows may be deleted.
Python Program
import [Link]
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = [Link]()
query = """
DELETE FROM students
WHERE rollno = 2
"""
[Link](query)
[Link]()
print("Record Deleted")
Output
Record Deleted
Example
[Link]("SELECT * FROM students")
records = [Link]()
for row in records:
print(row)
Output Example
(1, 'Raj', 85)
(3, 'Neha', 88)
Example
query = """
DELETE FROM students
WHERE rollno = %s
"""
value = (2,)
[Link](query, value)
[Link]()
Advantages
1. Safe queries
2. Dynamic values
3. Better coding practice
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
Example
print([Link], "record deleted")
Output Example
1 record deleted
SQL Query
DELETE FROM students
WHERE marks < 40;
Python Program
query = """
DELETE FROM students
WHERE marks < 40
"""
[Link](query)
[Link]()
print([Link], "records deleted")
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)
----------**********----------
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.
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