Python Programming – Class XII State Syllabus Guide

XII Class 

Part 1: Exception Handling

Program 1:
Syntax Error vs Exception
# Syntax Error Example (won't run)
# print("Hello

# Exception Example (will run but gives error)
a = 5
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("You cannot divide by zero!")


Program 2:
Try-Except-Else-Finally
try:
num = int(input("Enter a number: "))
print(100 / num)
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Zero is not allowed!")
else:
print("Division successful!")
finally:
print("End of program.")


Program 3:
Raising Exceptions
def check_age(age):
if age < 18:
raise ValueError("You must be 18 or older!")
return True

try:
check_age(15)
except ValueError as e:
print("Exception:", e)


Program 4:
User-Defined Exception
class UnderAgeError(Exception):
pass

def vote(age):
if age < 18:
raise UnderAgeError("You are under age!")
else:
print("You can vote!")

try:
vote(16)
except UnderAgeError as e:
print("Custom Exception:", e)


Program 5:
Built-in Exception Classes
print(dir(__builtins__)) # Shows all built-in exceptions



 Part 2: File Handling

Program 1:
Text File (Write & Read)
# writing to text file
with open("sample.txt", "w") as f:
f.write("Hello from CloudElixir!\n")
f.write("Python is easy.")

# reading from text file
with open("sample.txt", "r") as f:
content = f.read()
print("File content:\n", content)


Note: It creates a file automaticlaly

Program 2:
File Access Modes
# w = write, r = read, a = append, w+ = read/write
with open("sample.txt", "a") as f:
f.write("\nAppending more lines.")


Program 3:
Binary File Using
import pickle

data = {"name": "Venky", "age": 21, "city": "Bangalore"}

# writing binary
with open("data.pkl", "wb") as f:
pickle.dump(data, f)

# reading binary
with open("data.pkl", "rb") as f:
loaded = pickle.load(f)
print("Binary file content:", loaded)


Note: after the execution it will create file.

----------------------------------------------------------------------------------
Filename Description
sample.txt Text file with written content
data.pkl Binary file using pickle module
exceptions_filehandling.py Full program file combining everything
(For the full code by combining  all the code use the below one)

Full Python File

exceptions_filehandling.py

import pickle

# EXCEPTION HANDLING
print("\n--- Exception Handling ---")
try:
num = int(input("Enter a number: "))
print(100 / num)
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Zero is not allowed!")
else:
print("Division successful!")
finally:
print("End of division block.\n")

# RAISING EXCEPTION
def check_age(age):
if age < 18:
raise ValueError("You must be 18 or older!")

try:
check_age(16)
except ValueError as e:
print("Raised Exception:", e)

# USER DEFINED EXCEPTION
class UnderAgeError(Exception):
pass

def vote(age):
if age < 18:
raise UnderAgeError("You are under age!")

try:
vote(17)
except UnderAgeError as e:
print("Custom Exception:", e)

# FILE HANDLING
print("\n--- File Handling ---")
# Writing text file
with open("sample.txt", "w") as f:
f.write("Python File Handling\nLine 2 here.")

# Reading text file
with open("sample.txt", "r") as f:
print("Text File Content:\n", f.read())

# Writing binary file
data = {"name": "Venkatesh", "age": 21}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)

# Reading binary file
with open("data.pkl", "rb") as f:
print("Binary File Content:\n", pickle.load(f))

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

  Python Programming Chapter2


🔹 What is a Stack?

A Stack is a linear data structure that follows the LIFO (Last In First Out) principle.
Think of it like a stack of plates – you can only add (push) or remove (pop) the top one.

🔹 Basic Stack Operations in Python

  • PUSH (Add element to the top)
  • POP (Remove element from the top)

Program 1:
Stack Implementation using List
stack = []

# PUSH operation
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after push:", stack)

# POP operation
print("Popped element:", stack.pop())
print("Stack after pop:", stack)


Expressions – Prefix, Infix, Postfix

Notation Example Order
Infix A + B Operand + Operator + Operand
Prefix + A B Operator before operands
Postfix A B + Operator after operands

Program 2:
Infix to Postfix Conversion
def infix_to_postfix(expression):
precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
stack = []
result = ""
for char in expression:
if char.isalnum():
result += char
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
result += stack.pop()
stack.pop() # remove '('
else:
while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0):
result += stack.pop()
stack.append(char)
while stack:
result += stack.pop()
return result

# Test
exp = input("Enter Infix Expression: ")
print("Postfix Expression:", infix_to_postfix(exp))



Program 3:
Evaluate Postfix Expression
def evaluate_postfix(expression):
stack = []
for char in expression:
if char.isdigit():
stack.append(int(char))
else:
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
elif char == '*':
stack.append(a * b)
elif char == '/':
stack.append(a / b)
return stack.pop()

# Test
exp = input("Enter Postfix Expression (Single-digit operands): ")
print("Result:", evaluate_postfix(exp))

Final Python File (Full Code For Stack_Operation)

stack_operations.py

# Stack Operations, Infix to Postfix, and Evaluation

# PUSH and POP
stack = []

def push():
element = input("Enter element to push: ")
stack.append(element)
print("Stack:", stack)

def pop():
if not stack:
print("Stack is empty!")
else:
print("Popped element:", stack.pop())
print("Stack:", stack)

# Infix to Postfix
def infix_to_postfix(expression):
precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
stack = []
result = ""
for char in expression:
if char.isalnum():
result += char
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
result += stack.pop()
stack.pop()
else:
while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0):
result += stack.pop()
stack.append(char)
while stack:
result += stack.pop()
return result

# Evaluate Postfix
def evaluate_postfix(expression):
stack = []
for char in expression:
if char.isdigit():
stack.append(int(char))
else:
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
elif char == '*':
stack.append(a * b)
elif char == '/':
stack.append(a / b)
return stack.pop()

# Menu
while True:
print("\n1. PUSH\n2. POP\n3. Infix to Postfix\n4. Evaluate Postfix\n5. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
push()
elif ch == 2:
pop()
elif ch == 3:
infix = input("Enter Infix Expression: ")
print("Postfix:", infix_to_postfix(infix))
elif ch == 4:
postfix = input("Enter Postfix Expression (digits only): ")
print("Result:", evaluate_postfix(postfix))
elif ch == 5:
break
else:
print("Invalid choice!")


 Python Programming Chapter3

Queue (FIFO – First In First Out)

Program 1:
Queue Implementation using List
queue = []

def insert():
element = input("Enter element to insert: ")
queue.append(element)
print("Queue:", queue)

def delete():
if not queue:
print("Queue is empty!")
else:
removed = queue.pop(0)
print("Deleted element:", removed)
print("Queue:", queue)

while True:
print("\n1. INSERT\n2. DELETE\n3. EXIT")
choice = int(input("Enter your choice: "))
if choice == 1:
insert()
elif choice == 2:
delete()
elif choice == 3:
break
else:
print("Invalid choice!")


 Introduction to DeQueue (Double-Ended Queue)

A DeQueue (Double-Ended Queue) allows insertion and deletion from both ends:
  • Front & Rear insert
  • Front & Rear delete

Python provides this through the collections.deque module.

Program 2:
DeQueue Implementation using collections.deque

from collections import deque

dq = deque()

def add_front():
element = input("Enter element to add at front: ")
dq.appendleft(element)
print("DeQueue:", dq)

def add_rear():
element = input("Enter element to add at rear: ")
dq.append(element)
print("DeQueue:", dq)

def delete_front():
if not dq:
print("DeQueue is empty!")
else:
print("Deleted from front:", dq.popleft())
print("DeQueue:", dq)

def delete_rear():
if not dq:
print("DeQueue is empty!")
else:
print("Deleted from rear:", dq.pop())
print("DeQueue:", dq)

while True:
print("\n1. Add Front\n2. Add Rear\n3. Delete Front\n4. Delete Rear\n5. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
add_front()
elif ch == 2:
add_rear()
elif ch == 3:
delete_front()
elif ch == 4:
delete_rear()
elif ch == 5:
break
else:
print("Invalid choice!")


Final Python File (Full Code For Queue_Operation)

from collections import deque

# Simple Queue
queue = []

def insert():
element = input("Enter element to insert in Queue: ")
queue.append(element)
print("Queue:", queue)

def delete():
if not queue:
print("Queue is empty!")
else:
print("Deleted:", queue.pop(0))
print("Queue:", queue)

# DeQueue
dq = deque()

def add_front():
element = input("Enter element to add at front of DeQueue: ")
dq.appendleft(element)
print("DeQueue:", dq)

def add_rear():
element = input("Enter element to add at rear of DeQueue: ")
dq.append(element)
print("DeQueue:", dq)

def delete_front():
if not dq:
print("DeQueue is empty!")
else:
print("Deleted from front:", dq.popleft())
print("DeQueue:", dq)

def delete_rear():
if not dq:
print("DeQueue is empty!")
else:
print("Deleted from rear:", dq.pop())
print("DeQueue:", dq)

# Menu
while True:
print("\nQueue Operations:\n1. INSERT (Queue)\n2. DELETE (Queue)")
print("DeQueue Operations:\n3. Add Front\n4. Add Rear\n5. Delete Front\n6. Delete Rear\n7. Exit")
ch = int(input("Enter choice: "))
if ch == 1:
insert()
elif ch == 2:
delete()
elif ch == 3:
add_front()
elif ch == 4:
add_rear()
elif ch == 5:
delete_front()
elif ch == 6:
delete_rear()
elif ch == 7:
break
else:
print("Invalid choice!")


Comments

Popular posts from this blog

Mobile Application Development Lab

WEB PROGRAMMING LAB (html&php)

Python Programming