Day-2 Programs Practice Set (Board Oriented)
FUNCTIONS
1. List Update (Value based) Logic: Isme index nhi, balki value check krni h. if
x % 5 == 0 se divisibility check hogi aur square k liye ** 2 use krenge.
def Change_Val(L):
for i in range(len(L)):
if L[i] % 5 == 0:
L[i] = L[i] ** 2 # Square of the element
else:
L[i] = L[i] + 10 # Increment by 10
print("Updated List:", L)
# Example:
# L = [5, 2, 10, 3]
# Change_Val(L) -> [25, 12, 100, 13]
2. String Stats (Lowercase Vowels & Special Characters) Logic: islower() aur
isalnum() ka use krke special characters identify krenge. Jo character na
alphabet h na digit, wo special h.
def Count_Alpha(S):
v_count = 0
sp_count = 0
vowels = "aeiou" # Only Lowercase Vowels
for char in S:
if char in vowels:
v_count += 1
if not [Link]() and not [Link]():
sp_count += 1
print("Lowercase Vowels:", v_count)
print("Special Characters:", sp_count)
3. Global Scope (global Keyword) Logic: Function k andr agar humein kisi
bahar wale variable ko update krna h, toh global keyword likhna padta h,
wrna Python use local maan leta h.
Score = 100 # Global Variable
def Update():
global Score # Permitting function to modify Score
Score = Score + 50
print("Score inside function:", Score)
Update()
print("Score outside function:", Score)
4. List Filter (Exact Length) Logic: len(n) == 4 check krna h. Ek empty list m
matching results ko append krte jayenge.
def Get_Short(Names):
NewList = []
for n in Names:
if len(n) == 4: # Exactly 4 characters
[Link](n)
return NewList
# Example:
# names = ["Nitin", "Arun", "Amit", "Rahul"]
# print(Get_Short(names)) -> ["Arun", "Amit"]
5. Argument Types (Positional & Keyword) Logic: Positional args m order fix
rhta h, keyword args m hum explicitly name define krte h toh order change kr
skte h.
def Calc_Volume(L, B=10, H=5):
vol = L * B * H
print("Volume is:", vol)
# 1. Positional Argument (L=2, B=3, H=4)
Calc_Volume(2, 3, 4)
# 2. Keyword Argument (Order change allowed)
Calc_Volume(H=10, L=5, B=2)
# 3. Using Default Values (Only L provided)
Calc_Volume(7)
TEXT FILE HANDLING
1. Word Search ("is" or "are") Logic: read() se pura data lo, split() krke words ki
list banao, aur fir check kro. Case sensitivity hamesha handle krna safe rhta h.
def Search_Word():
with open("[Link]", "r") as f:
data = [Link]()
words = [Link]()
count = 0
for w in words:
if [Link]() == "is" or [Link]() == "are":
count += 1
print("Total count of 'is' or 'are':", count)
2. Line Logic (Starts with Digit) Logic: readlines() se lines ki list lo. line[0] check
kro ki wo isdigit() h ya nhi, ya fir range 0-9 m h.
def Start_Digit():
with open("[Link]", "r") as f:
lines = [Link]()
for line in lines:
if line[0].isdigit(): # Checks if first char is 0-9
print(line, end="")
3. Vowel Count (Total Vowels) Logic: Pura content read() kro aur check kro ki
har character aeiouAEIOU string ka hissa h ya nhi.
def Total_Vowels():
with open("[Link]", "r") as f:
data = [Link]()
count = 0
vowels = "aeiouAEIOU"
for char in data:
if char in vowels:
count += 1
print("Total Vowels found:", count)
4. Specific Display (Length < 3) Logic: Words nikalne k liye split() use kro, fir
len(w) < 3 check krke print krdo.
def Small_Words():
with open("[Link]", "r") as f:
words = [Link]().split()
for w in words:
if len(w) < 3:
print(w)
5. File Shift (Copy "Error" Lines) Logic: Source file ko "r" aur destination ko "w"
ya "a" mode m open kro. if "Error" in line condition check kro.
def Move_Lines():
try:
with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
lines = [Link]()
for line in lines:
if "Error" in line:
[Link](line)
print("Lines containing 'Error' shifted successfully!")
except FileNotFoundError:
print("Source file not found.")
BINARY FILE
1. Add Data (Insert Record) Logic: ab mode use kro taaki naya record file k
end m add ho. Data ko list format m dump krna h.
import pickle
def Add_Record():
# 'ab' for append binary
with open("[Link]", "ab") as f:
bid = int(input("Enter Book ID: "))
title = input("Enter Title: ")
author = input("Enter Author: ")
rec = [bid, title, author]
[Link](rec, f)
print("Book Record Added!")
2. Search ID (Find Title) Logic: rb mode m loop chalao. EOFError aate hi
search stop krdo. found flag se check kro record mila ya nhi.
import pickle
def Find_Book(BID):
found = False
try:
with open("[Link]", "rb") as f:
while True:
try:
rec = [Link](f)
if rec[0] == BID:
print("Book Title:", rec[1])
found = True
break
except EOFError:
break
if not found:
print("Missing")
except FileNotFoundError:
print("File Missing")
3. Price Update (List-Copy Method) Logic: Pura data list m read kro, ID match
hone pr price update kro, aur fir wb mode se file rewrite krdo.
import pickle
def Revise_Price(ID, NewP):
temp = []
found = False
try:
with open("[Link]", "rb") as f:
while True:
try:
rec = [Link](f)
if rec[0] == ID:
rec[2] = NewP # Update Price
found = True
[Link](rec)
except EOFError:
break
if found:
with open("[Link]", "wb") as f:
for r in temp:
[Link](r, f)
print("Price Updated!")
else:
print("Product ID Not Found")
except FileNotFoundError:
print("File Not Found")
4. Filter Records (Score > 100) Logic: rb mode m read kro aur condition
rec[index] > 100 check krke sirf matching names print kro.
import pickle
def High_Scorers():
try:
with open("[Link]", "rb") as f:
print("Players with Score > 100:")
while True:
try:
rec = [Link](f) # [Name, Score]
if rec[1] > 100:
print(rec[0])
except EOFError:
break
except FileNotFoundError:
print("Data File Missing")
5. File Copy (Conditional Transfer) Logic: Dono files ek sath open kro. Pehli se
read kro aur condition match hote hi dusri m dump krdo.
import pickle
def Filter_Copy():
try:
with open("[Link]", "rb") as f1, open("[Link]", "wb") as f2:
while True:
try:
rec = [Link](f1) # [ID, Name, Age]
if rec[2] > 60:
[Link](rec, f2)
except EOFError:
break
print("Seniors data copied successfully!")
except FileNotFoundError:
print("Source file not found.")
CSV FILE
1. Create CSV (New User) Logic: newline='' lagana mandatory h taaki extra
blank lines na aayein. writerow() se list ko CSV row m convert krte h.
import csv
def New_User():
# Inputs lena
uid = int(input("Enter UserID: "))
uname = input("Enter Username: ")
dept = input("Enter Dept: ")
rec = [uid, uname, dept]
# 'with' use krne se [Link]() ki tension khtm
with open("[Link]", "a", newline="") as f:
writer = [Link](f)
[Link](rec)
print("User Added Successfully!")
2. Search CSV (Find Dept) Logic: [Link]() se loop chalao. row[1] m
username check kro aur match hone pr row[2] (Dept) print krdo.
import csv
def Find_Dept(User):
found = False
try:
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
# Case insensitive search using lower()
if row[1].lower() == [Link]():
print("Department of", User, "is:", row[2])
found = True
break
if not found:
print("User not found.")
except FileNotFoundError:
print("File Missing")
3. Tabular View (Stock Display) Logic: Proper table dikhane k liye \t (tab) ka
use kro header aur rows k beech m.
import csv
def View_Stock():
try:
with open("[Link]", "r") as f:
reader = [Link](f)
print("ID\tNAME\tPRICE\tQTY") # Table Header
print("-" * 30)
for row in reader:
for val in row:
print(val, end="\t")
print() # Next row
except FileNotFoundError:
print("Stock File Not Found")
4. Counter (Sales Dept) Logic: Counter variable use kro. strip() use krna safe
rhta h taaki extra spaces count m problem na karein.
import csv
def Count_Dept(DName):
count = 0
try:
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
# row[2] assumes Dept column
if row[2].strip().lower() == [Link]():
count += 1
print("Total employees in", DName, ":", count)
except FileNotFoundError:
print("File Not Found")
5. Price Logic (Between 500 and 1000) Logic: CSV data string hota h, isliye
float() ya int() m convert krke range 500 <= price <= 1000 check kro.
import csv
def Budget_Items():
try:
with open("[Link]", "r") as f:
reader = [Link](f)
print("Items within budget (500-1000):")
for row in reader:
# row[2] assumes Price column
price = float(row[2])
if 500 <= price <= 1000:
print(row[1]) # Displaying Item Name
except FileNotFoundError:
print("Gift File Missing")
except ValueError:
print("Error: Price column contains non-numeric data")
STACK
1. Odd Stack (Odd Numbers) Logic: Pehle list se odd numbers filter krke
append() kro, fir pop() krne se pehle Underflow check krna mat bhulna.
def Push_Odd(Nums, S):
for x in Nums:
if x % 2 != 0:
[Link](x)
def Pop_Odd(S):
if len(S) == 0:
print("Stack Empty (Underflow)")
else:
print("Popped Odd Number:", [Link]())
2. Dict Filter (Costly Items) Logic: Dictionary k keys (Items) pr loop chalao aur
agar value (Price) 1000 se upar h, toh key ko stack m append krdo.
def Push_Costly(D, S):
for item in D:
if D[item] > 1000:
[Link](item)
print("Costly items pushed to stack.")
3. Consonant Stack (Starts with Consonant) Logic: Pehla alphabet check kro.
Agar wo vowels (aeiou) m nhi h, toh wo consonant h. Pop krte waqt if not S
check kro.
def Push_Con(Words, S):
vowels = "aeiou"
for w in Words:
if w[0].lower() not in vowels:
[Link](w)
def Pop_Con(S):
if not S:
print("Underflow! No consonants to pop.")
else:
print("Popped Word:", [Link]())
4. List Stack (Grade 'A' Filter) Logic: Nested list m index check kro. rec[2] agar
'A' h, toh rec[1] (Name) ko stack m push kro.
def Push_GradeA(Students, S):
# Students = [[1, 'Nitin', 'A'], [2, 'Rahul', 'B']]
for rec in Students:
if rec[2] == 'A':
[Link](rec[1]) # Pushing only Name
print("Grade A student names pushed.")
5. Full Stack Op (Menu-Driven - Mobiles) Logic: Display operation k liye hmesa
stack ko reverse order m dikhao taaki "Top" element upar dikhe.
def Mobile_Stack():
Mobiles = []
while True:
print("\n--- MOBILE STACK MENU ---")
print("1. PUSH (Add Mobile)")
print("2. POP (Remove Mobile)")
print("3. DISPLAY (Peek & View)")
print("4. EXIT")
ch = int(input("Enter Choice (1-4): "))
if ch == 1:
name = input("Enter Mobile Name: ")
[Link](name)
elif ch == 2:
if not Mobiles:
print("Underflow! Stack is empty.")
else:
print("Popped Mobile:", [Link]())
elif ch == 3:
if not Mobiles:
print("Nothing to display.")
else:
print("Stack (Top to Bottom):")
for i in range(len(Mobiles)-1, -1, -1):
print(Mobiles[i])
elif ch == 4:
print("Exiting...")
break
else:
print("Invalid Choice, try again.")