Important CS Programs
Master your practical exams with our curated list of essential Python programs for Class 12 Computer Science. Click on any program to view the code, copy it, or run it instantly.
In each topic the programs go from Easy to Hard. A CBSE tag shows the paper or practical list a program comes from; Rare marks less common programs that are still in the syllabus.
FUNCTIONS 21 programs
-
Write a function once and call it as many times as you need, with a different argument each time.
def greet(name): print("Hello,", name) print("Welcome to Class 12 Computer Science.") greet("Riya") greet("Aman") -
return sends the answer back to the caller, which can store it or print it.
def area_of_circle(r): return 3.14 * r * r a = area_of_circle(7) print("Area of circle:", a) -
A function can return several values; Python packs them into a tuple.
def min_max(L): return min(L), max(L) small, big = min_max([45, 12, 89, 33, 7]) print("Smallest:", small) print("Largest:", big) -
Default values are used when an argument is left out; keyword arguments can be given in any order.
def simple_interest(p, r=5, t=1): return p * r * t / 100 print(simple_interest(1000)) # r = 5 and t = 1 (default values) print(simple_interest(1000, 8)) # t = 1 (default value) print(simple_interest(t=2, p=5000)) # keyword arguments, in any order -
Take a list of words and return a new list with each word capitalized.
def capitalize_words(words): result = [] for w in words: result.append(w.capitalize()) return result print(capitalize_words(["python", "computer", "science"])) -
Print the sum of only the positive numbers in a list.
def sum_positive(list1): total = 0 for num in list1: if num > 0: total += num print(total) sum_positive([10, -5, 20, -3, 7]) # 37 -
A random number generator that gives numbers from 1 to 6, like rolling a dice.
import random def roll_dice(): return random.randint(1, 6) # 1 and 6 are both included for i in range(5): print("Roll", i + 1, ":", roll_dice()) -
A variable made inside a function is local. Use the global keyword to change a global variable.
count = 0 # global variable def show(): count = 5 # local variable (a different 'count') print("Inside show():", count) def increase(): global count # use the global 'count' count = count + 1 show() increase() increase() print("Global count:", count) # 2 -
A list passed to a function can be changed inside it; an integer cannot.
def change(n, L): n = n + 10 # int is immutable: the caller's number does not change L.append(10) # list is mutable: the caller's list changes num = 5 marks = [1, 2, 3] change(num, marks) print("num =", num) # 5 print("marks =", marks) # [1, 2, 3, 10] -
The corrected code of an error-finding question: return the reverse of a number.
def revNumber(num): rev = 0 while num > 0: rem = num % 10 rev = rev * 10 + rem num = num // 10 return rev # outside the loop print(revNumber(1234)) # 4321 -
The corrected code of an error-finding question: return the number of vowels in a string.
def CountVowels(s): c = 0 for ch in s: # not range(s) if ch in 'aeiouAEIOU': # is ch one of the vowels? c += 1 # += , not =+ return c # return the count, not ch print(CountVowels("Computer Science")) # 6 -
Return a tuple with the length of each word of a string.
def lenWords(STRING): T = () for word in STRING.split(): T = T + (len(word),) # (x,) is a tuple with one item return T print(lenWords("Come let us have some fun")) # (4, 3, 2, 4, 4, 3) -
Take a dictionary of places and display, in uppercase, the names longer than 5 characters.
def countNow(PLACES): for place in PLACES.values(): if len(place) > 5: print(place.upper()) PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Doha"} countNow(PLACES) # LONDON, NEW YORK -
A dictionary holds Name: [Eng, Math, Science]. Display each student's grade: A (90+), B (60-89), C (below 60).
def showGrades(S): for name in S: marks = S[name] avg = sum(marks) / len(marks) if avg >= 90: grade = "A" elif avg >= 60: grade = "B" else: grade = "C" print(name, "-", grade) S = {"AMIT": [92, 86, 64], "NAGMA": [65, 42, 43], "DAVID": [92, 90, 88]} showGrades(S) -
Return the word with every Nth letter replaced by an underscore.
def Puzzle(W, N): result = "" for i in range(len(W)): if (i + 1) % N == 0: # positions N, 2N, 3N ... (counting from 1) result += "_" else: result += W[i] return result print(Puzzle("TELEVISION", 3)) # TE_EV_SI_N print(Puzzle("TELEVISION", 4)) # TEL_VIS_ON -
Count the pairs (a, b) in a tuple of pairs where both a and b are even.
def cnt_even(pairs): c = 0 for a, b in pairs: if a % 2 == 0 and b % 2 == 0: c += 1 return c pairs = ((2, 5), (4, 2), (9, 8), (12, 10)) print("Pairs with both numbers even:", cnt_even(pairs)) # 2 -
Remove n from the list if it is there; otherwise print "Element not found".
def remove_element(L, n): if n in L: L.remove(n) else: print("Element not found") L = [10, 20, 30, 40] remove_element(L, 30) print(L) # [10, 20, 40] remove_element(L, 99) # Element not found -
A tuple cannot be changed, so build a new tuple with the first and last elements swapped.
def swap_ends(T): if len(T) < 2: return T return (T[-1],) + T[1:-1] + (T[0],) print(swap_ends((10, 20, 30, 40))) # (40, 20, 30, 10) -
Return a dictionary showing how many times each word appears in a sentence.
def word_frequency(text): freq = {} for word in text.lower().split(): freq[word] = freq.get(word, 0) + 1 # 0 when the word is new return freq print(word_frequency("The cat and the dog and the bird")) # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1} -
is_armstrong() checks one number; armstrong_in_range() uses it to find all of them in a range.
def is_armstrong(n): digits = str(n) power = len(digits) total = 0 for d in digits: total += int(d) ** power return total == n # True or False def armstrong_in_range(a, b): result = [] for n in range(a, b + 1): if is_armstrong(n): # calling the other function result.append(n) return result print(armstrong_in_range(100, 999)) # [153, 370, 371, 407] -
Two words are anagrams if they use the same letters, e.g. LISTEN and SILENT.
def is_anagram(w1, w2): return sorted(w1.lower()) == sorted(w2.lower()) print(is_anagram("Listen", "Silent")) # True print(is_anagram("Python", "Typhon")) # True print(is_anagram("Hello", "World")) # False
Recommended books optional
Practise more for the board exam. Want more board-style questions and programs than this page has? These printed books are optional extras.
-
Oswaal CBSE Question Bank — Computer ScienceSee price on Amazon
Class 12 · Chapterwise & topicwise · for the 2027 exam
-
Sumita Arora — Progress in Computer Science with PythonSee price on Amazon
Class 12 · 2026–27 edition · Dhanpat Rai & Co.
-
Together With CBSE Question Bank — Computer ScienceSee price on Amazon
Class 12 · Question bank
-
Arihant All in One — Computer ScienceSee price on Amazon
Class 12 · Theory + practice questions
-
Preeti Arora — Computer Science with PythonSee price on Amazon
Class 12 · Sultan Chand & Sons
You don't need to buy anything: the notes, programs, quizzes and papers on CSIP12 are free. As an Amazon Associate, CSIP12 earns from qualifying purchases.
EXCEPTION HANDLING 7 programs
-
try runs the risky code; except catches the error so the program does not crash.
a = 10 b = 0 try: print(a / b) except ZeroDivisionError: print("Error: cannot divide by zero.") print("The program continues.") -
int() raises ValueError when the input is not a whole number.
try: age = int(input("Enter your age: ")) print("Next year you will be", age + 1) except ValueError: print("Please enter a whole number, e.g. 16.") -
Catch different errors separately and show a suitable message for each.
def divide_item(L, i, d): try: print("Result:", L[i] // d) except IndexError: print("Error: index", i, "is out of range.") except ZeroDivisionError: print("Error: cannot divide by zero.") except TypeError: print("Error: use numbers only.") L = [10, 20, 30] divide_item(L, 1, 5) # Result: 4 divide_item(L, 7, 5) # IndexError divide_item(L, 1, 0) # ZeroDivisionError divide_item(L, 1, "2") # TypeError -
else runs only when there is no error; finally always runs.
def safe_divide(a, b): try: result = a / b except ZeroDivisionError: print("Cannot divide by zero.") else: print("Answer:", result) # only when there is no error finally: print("Done.") # always safe_divide(10, 4) safe_divide(10, 0) -
Use raise to report wrong data yourself, then catch it with except.
def set_marks(m): if m < 0 or m > 100: raise ValueError("Marks must be between 0 and 100") print("Marks saved:", m) try: set_marks(85) set_marks(120) except ValueError as e: print("Error:", e) -
A while loop with try-except asks again and again until a proper number is entered.
while True: try: n = int(input("Enter a number from 1 to 10: ")) if 1 <= n <= 10: break # valid: leave the loop print("Out of range, try again.") except ValueError: print("That is not a number, try again.") print("You entered", n) -
Opening a file that does not exist in read mode raises FileNotFoundError.
def show_file(name): try: with open(name, "r") as f: print(f.read()) except FileNotFoundError: print("Sorry,", name, "does not exist.") with open("notes.txt", "w") as f: f.write("Exception handling stops a program from crashing.") show_file("notes.txt") show_file("missing.txt")
TEXT FILES 21 programs
-
Mode "w" creates the file (or empties it); mode "r" reads it.
f = open("story.txt", "w") f.write("Python is easy to learn.\n") f.write("Files store data permanently.\n") f.close() f = open("story.txt", "r") print(f.read()) f.close() -
Mode "a" adds to the end of the file; with closes the file by itself.
with open("diary.txt", "w") as f: f.write("Monday: Revised functions.\n") with open("diary.txt", "a") as f: # old data stays f.write("Tuesday: Solved file handling questions.\n") f.writelines(["Wednesday: Stack practice.\n", "Thursday: SQL joins.\n"]) with open("diary.txt", "r") as f: print(f.read()) -
read() gives a string, readline() gives one line, readlines() gives a list of lines.
with open("poem.txt", "w") as f: f.write("Twinkle twinkle\nLittle star\nHow I wonder\n") f = open("poem.txt", "r") print(f.read(7)) # first 7 characters: Twinkle f.seek(0) # back to the start print(f.readline()) # one line (keeps the \n) print(f.readlines()) # list of the remaining lines f.close() -
Count the lines, words and characters in a text file.
with open("story.txt", "w") as f: f.write("Python is fun.\nFiles keep data safe.\nPractice daily.\n") lines = words = chars = 0 with open("story.txt", "r") as f: for line in f: lines += 1 words += len(line.split()) chars += len(line) print("Lines:", lines) print("Words:", words) print("Characters:", chars) -
tell() gives the position of the file pointer; seek() moves it.
with open("abc.txt", "w") as f: f.write("HELLO WORLD") with open("abc.txt", "r") as f: print(f.read(5)) # HELLO print(f.tell()) # 5 f.seek(0) # to the beginning print(f.read(3)) # HEL f.seek(6) # to position 6 print(f.read()) # WORLD -
Read a text file line by line and display each word separated by a #.
with open("story.txt", "w") as f: f.write("Python is fun\nKeep practising daily\n") with open("story.txt", "r") as f: for line in f: words = line.split() print("#".join(words)) -
Read a text file and display the number of vowels, consonants, uppercase and lowercase characters.
with open("Poem.txt", "w") as f: f.write("Python Is Easy\nPractice Every Day!") vowels = consonants = upper = lower = 0 with open("Poem.txt", "r") as f: text = f.read() for ch in text: if ch.isalpha(): if ch in "aeiouAEIOU": vowels += 1 else: consonants += 1 if ch.isupper(): upper += 1 else: lower += 1 print("Vowels:", vowels) print("Consonants:", consonants) print("Uppercase:", upper) print("Lowercase:", lower) -
Read Alpha.txt and display the lines that begin with the word You.
def show_you_lines(): f = open("Alpha.txt", "r") for line in f: words = line.split() if len(words) > 0 and words[0] == "You": # skip empty lines print(line, end="") f.close() with open("Alpha.txt", "w") as f: f.write("You are a good student.\nAlways be on time.\nYou can do it!\nYour book is here.\n") show_you_lines() -
Display how many times the word Python appears in Prog.txt.
def count_python(): count = 0 with open("Prog.txt", "r") as f: for word in f.read().split(): if word.strip(".,!?").lower() == "python": # ignore punctuation and case count += 1 print("The word Python appears", count, "times.") with open("Prog.txt", "w") as f: f.write("Python is popular. I like python!\nLearning Python is fun.") count_python() # 3 -
Display the lines of Elections.txt that contain the word vote.
def show_vote_lines(): with open("Elections.txt", "r") as f: for line in f: if "vote" in line: print(line, end="") with open("Elections.txt", "w") as f: f.write("Every citizen should vote.\nElections are held every five years.\nYour vote is your voice.\n") show_vote_lines() -
Display the lines of Colors.txt that end with a dot (.).
def show_dot_lines(): with open("Colors.txt", "r") as f: for line in f: if line.rstrip().endswith("."): # rstrip() removes the \n print(line, end="") with open("Colors.txt", "w") as f: f.write("Red is bright.\nBlue is calm\nGreen means go.\n") show_dot_lines() -
Display the lines of a text file that do not start with a vowel.
def no_vowel_start(): with open("Story.txt", "r") as f: for line in f: if line[0] not in "aeiouAEIOU": print(line, end="") with open("Story.txt", "w") as f: f.write("Once upon a time\nThere was a king\nAn honest man\nHe ruled well\n") no_vowel_start() -
Count and return the number of digits in the text file Space.txt.
def count_digits(): with open("Space.txt", "r") as f: text = f.read() count = 0 for ch in text: if ch.isdigit(): count += 1 return count with open("Space.txt", "w") as f: f.write("Chandrayaan-3 landed in 2023.\nISRO launched 104 satellites in 2017.") print("Digits:", count_digits()) # 12 -
Display the words in which the lowercase letter e appears at least twice.
def ee_words(): with open("Space.txt", "r") as f: for word in f.read().split(): if word.count("e") >= 2: print(word) with open("Space.txt", "w") as f: f.write("The tree near the green fence\nSeven people need help") ee_words() -
Remove all the lines that contain the character a and write them to another file.
def remove_a_lines(): fin = open("source.txt", "r") lines = fin.readlines() fin.close() keep = open("source.txt", "w") # lines without 'a' stay here moved = open("with_a.txt", "w") # lines with 'a' go here for line in lines: if "a" in line: moved.write(line) else: keep.write(line) keep.close() moved.close() with open("source.txt", "w") as f: f.write("Python is great\nIt is free\nCode every day\nJust do it\n") remove_a_lines() print("source.txt:\n" + open("source.txt").read()) print("with_a.txt:\n" + open("with_a.txt").read()) -
Display the words that start and end with a vowel, separated by a space.
def vowel_words(): vowels = "aeiouAEIOU" result = [] with open("Report.txt", "r") as f: for word in f.read().split(): if word[0] in vowels and word[-1] in vowels: result.append(word) print(" ".join(result)) with open("Report.txt", "w") as f: f.write("India is an ancient area\nUse one apple every time") vowel_words() # India area Use one apple -
Display the lines that contain a four-digit year such as 1999 or 2024.
def year_lines(): f = open("History.txt", "r") for line in f: for w in line.split(): if w.isdigit() and len(w) == 4: print(line, end="") break # print each line only once f.close() with open("History.txt", "w") as f: f.write("India became independent in 1947\nThe Taj Mahal is in Agra\nThe Constitution began in 1950 and 26 January\n") year_lines() -
Display the line that has the maximum number of vowels.
def max_vowel_line(): best_line = "" best_count = -1 with open("Novel.txt", "r") as f: for line in f: count = 0 for ch in line: if ch in "aeiouAEIOU": count += 1 if count > best_count: best_count = count best_line = line print(best_line.rstrip(), "(", best_count, "vowels )") with open("Novel.txt", "w") as f: f.write("The sky was dark\nAn eerie audio echoed outside\nWe ran home\n") max_vowel_line() -
A sentence ends with . ? or ! - display every sentence of STORY.TXT on a separate line.
def showInLines(): with open("STORY.TXT", "r") as f: text = f.read() sentence = "" for ch in text: sentence += ch if ch in ".?!": print(sentence.strip()) sentence = "" with open("STORY.TXT", "w") as f: f.write("Our parents told us that we must eat vegetables to be healthy. " "And it turns out, our parents were right! So, what else did our parents tell?") showInLines() -
Copy a file line by line, replacing one word with another.
def replace_word(old, new): fin = open("source.txt", "r") fout = open("result.txt", "w") for line in fin: fout.write(line.replace(old, new)) fin.close() fout.close() with open("source.txt", "w") as f: f.write("I like Java.\nJava is useful.\n") replace_word("Java", "Python") print(open("result.txt").read()) -
Find and display the longest word in a text file.
def longest_word(): longest = "" with open("story.txt", "r") as f: for word in f.read().split(): if len(word) > len(longest): longest = word print("Longest word:", longest, "(", len(longest), "letters )") with open("story.txt", "w") as f: f.write("Programming needs patience\nand regular practice") longest_word() # Programming
BINARY FILES (PICKLE) 12 programs
-
pickle.dump() writes a Python object to a binary file; pickle.load() reads it back.
import pickle marks = [85, 92, 78, 64] f = open("marks.dat", "wb") # wb = write binary pickle.dump(marks, f) f.close() f = open("marks.dat", "rb") # rb = read binary data = pickle.load(f) f.close() print("Read from file:", data) -
Each dump() writes one record; read until EOFError to get all of them.
import pickle students = [[1, "Riya", 88], [2, "Aman", 75], [3, "Sara", 93]] with open("student.dat", "wb") as f: for rec in students: pickle.dump(rec, f) # one record at a time with open("student.dat", "rb") as f: try: while True: rec = pickle.load(f) print(rec) except EOFError: # no more records pass -
Read records one by one and count them.
import pickle with open("student.dat", "wb") as f: for rec in [[1, "Riya", 88], [2, "Aman", 75], [3, "Sara", 93]]: pickle.dump(rec, f) def count_records(): count = 0 with open("student.dat", "rb") as f: try: while True: pickle.load(f) count += 1 except EOFError: pass return count print("Number of records:", count_records()) -
Create a binary file with name and roll number. Search for a roll number and display the name, or a message if it is not found.
import pickle def create(): with open("roll.dat", "wb") as f: pickle.dump([1, "Riya"], f) pickle.dump([2, "Aman"], f) pickle.dump([3, "Sara"], f) def search(roll): found = False with open("roll.dat", "rb") as f: try: while True: rec = pickle.load(f) if rec[0] == roll: print("Name:", rec[1]) found = True break except EOFError: pass if not found: print("Roll number", roll, "not found.") create() search(2) search(7) -
EMP.DAT stores [Emp_Id, Name, Salary]. Display the employees whose salary is below 25000.
import pickle def disp_Detail(): f = open("EMP.DAT", "rb") try: while True: emp = pickle.load(f) if emp[2] < 25000: print(emp) except EOFError: pass f.close() with open("EMP.DAT", "wb") as f: for rec in [[101, "Neha", 32000], [102, "Ravi", 21000], [103, "John", 18500]]: pickle.dump(rec, f) disp_Detail() -
items.dat stores {item_id: [item_name, amount]}. Copy the records with amount greater than 1000 to new_items.dat.
import pickle def Copy_new(): fin = open("items.dat", "rb") fout = open("new_items.dat", "wb") try: while True: rec = pickle.load(fin) # e.g. {1: ['Pen', 50]} for item_id in rec: if rec[item_id][1] > 1000: pickle.dump(rec, fout) except EOFError: pass fin.close() fout.close() with open("items.dat", "wb") as f: for rec in [{1: ["Pen", 50]}, {2: ["Printer", 8500]}, {3: ["Mouse", 1200]}]: pickle.dump(rec, f) Copy_new() with open("new_items.dat", "rb") as f: try: while True: print(pickle.load(f)) except EOFError: pass -
SPORT.DAT stores [SportName, TeamName, No_Players]. Copy the Basket Ball records to BASKET.DAT and return how many were copied.
import pickle def copyData(): fin = open("SPORT.DAT", "rb") fout = open("BASKET.DAT", "wb") count = 0 try: while True: rec = pickle.load(fin) if rec[0] == "Basket Ball": pickle.dump(rec, fout) count += 1 except EOFError: pass fin.close() fout.close() return count with open("SPORT.DAT", "wb") as f: for rec in [["Basket Ball", "Eagles", 5], ["Cricket", "Lions", 11], ["Basket Ball", "Hawks", 5]]: pickle.dump(rec, f) print("Records copied:", copyData()) # 2 -
CINEMA.DAT stores {MNO: [MNAME, MTYPE]}. Display the records whose movie type is mtype.
import pickle def findType(mtype): f = open("CINEMA.DAT", "rb") try: while True: rec = pickle.load(f) # e.g. {1: ['Lagaan', 'Sports']} for mno in rec: if rec[mno][1] == mtype: print(mno, rec[mno][0], rec[mno][1]) except EOFError: pass f.close() with open("CINEMA.DAT", "wb") as f: for rec in [{1: ["Lagaan", "Sports"]}, {2: ["Taare Zameen Par", "Drama"]}, {3: ["Dangal", "Sports"]}]: pickle.dump(rec, f) findType("Sports") -
DOCTORS.DAT stores [D_ID, D_Name, D_Dept, Experience]. Write a function to add a doctor and one to display all records.
import pickle def add_doctor(rec): with open("DOCTORS.DAT", "ab") as f: # ab = append binary pickle.dump(rec, f) def show_all(): with open("DOCTORS.DAT", "rb") as f: try: while True: print(pickle.load(f)) except EOFError: pass open("DOCTORS.DAT", "wb").close() # start with an empty file add_doctor([1, "Dr. Mehta", "Cardiology", 12]) add_doctor([2, "Dr. Rao", "Neurology", 8]) show_all() -
Create a binary file with roll number, name and marks. Input a roll number and update the marks.
import pickle with open("result.dat", "wb") as f: for rec in [[1, "Riya", 70], [2, "Aman", 65], [3, "Sara", 90]]: pickle.dump(rec, f) def update_marks(roll, new_marks): records = [] found = False with open("result.dat", "rb") as f: # 1. read every record try: while True: rec = pickle.load(f) if rec[0] == roll: rec[2] = new_marks # 2. change the one we want found = True records.append(rec) except EOFError: pass with open("result.dat", "wb") as f: # 3. write them all back for rec in records: pickle.dump(rec, f) print("Updated." if found else "Roll number not found.") roll = int(input("Roll number: ")) marks = int(input("New marks: ")) update_marks(roll, marks) -
RESOURCES.DAT stores (R_ID, R_Name, R_Expertise, Charges). Append() adds a record; Update() increases every charge by 500.
import pickle def Append(): rid = int(input("Resource ID: ")) name = input("Name: ") expertise = input("Expertise: ") charges = int(input("Charges: ")) with open("RESOURCES.DAT", "ab") as f: pickle.dump((rid, name, expertise, charges), f) def Update(): records = [] with open("RESOURCES.DAT", "rb") as f: try: while True: r = pickle.load(f) # a tuple cannot be changed, so make a new one records.append((r[0], r[1], r[2], r[3] + 500)) except EOFError: pass with open("RESOURCES.DAT", "wb") as f: for r in records: pickle.dump(r, f) # Try it: two sample records (call Append() to type your own) with open("RESOURCES.DAT", "wb") as f: pickle.dump((1, "Asha", "Python", 2000), f) pickle.dump((2, "Vikram", "SQL", 1500), f) Update() with open("RESOURCES.DAT", "rb") as f: try: while True: print(pickle.load(f)) except EOFError: pass -
Keep every record except the one to delete, then write the file again.
import pickle with open("student.dat", "wb") as f: for rec in [[1, "Riya", 88], [2, "Aman", 75], [3, "Sara", 93]]: pickle.dump(rec, f) def delete_record(roll): keep = [] with open("student.dat", "rb") as f: try: while True: rec = pickle.load(f) if rec[0] != roll: # keep all the others keep.append(rec) except EOFError: pass with open("student.dat", "wb") as f: for rec in keep: pickle.dump(rec, f) delete_record(2) with open("student.dat", "rb") as f: try: while True: print(pickle.load(f)) except EOFError: pass
CSV FILES 11 programs
-
csv.writer() writes lists as comma-separated rows. Use newline="" to avoid blank lines.
import csv f = open("students.csv", "w", newline="") w = csv.writer(f) w.writerow(["Roll", "Name", "Marks"]) # header row w.writerow([1, "Riya", 88]) w.writerow([2, "Aman", 75]) f.close() print(open("students.csv").read()) -
writerows() takes a list of rows and writes all of them.
import csv rows = [["Roll", "Name", "Marks"], [1, "Riya", 88], [2, "Aman", 75], [3, "Sara", 93]] with open("students.csv", "w", newline="") as f: csv.writer(f).writerows(rows) print(open("students.csv").read()) -
csv.reader() gives each row as a list of strings.
import csv with open("students.csv", "w", newline="") as f: csv.writer(f).writerows([["Roll", "Name", "Marks"], [1, "Riya", 88], [2, "Aman", 75]]) with open("students.csv", "r") as f: for row in csv.reader(f): print(row) -
next() reads the header row so that only the data rows are processed.
import csv with open("students.csv", "w", newline="") as f: csv.writer(f).writerows([["Roll", "Name", "Marks"], [1, "Riya", 88], [2, "Aman", 75], [3, "Sara", 93]]) total = 0 with open("students.csv", "r") as f: r = csv.reader(f) next(r) # skip the header for row in r: total += int(row[2]) # values are read as strings print("Total marks:", total) -
Create a CSV file of user-ids and passwords, then search the password for a given user-id.
import csv def create(): with open("users.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["riya01", "sun@123"]) w.writerow(["aman02", "moon#45"]) def find_password(uid): with open("users.csv", "r") as f: for row in csv.reader(f): if row[0] == uid: print("Password:", row[1]) return print("User-id not found.") create() find_password(input("Enter user-id: ")) -
Peripheral.csv stores [P_id, P_name, Price]. Add_Device() adds a record; Count_Device() counts devices priced below 1000.
import csv def Add_Device(): pid = int(input("Device ID: ")) name = input("Device name: ") price = int(input("Price: ")) with open("Peripheral.csv", "a", newline="") as f: csv.writer(f).writerow([pid, name, price]) def Count_Device(): count = 0 with open("Peripheral.csv", "r") as f: for row in csv.reader(f): if int(row[2]) < 1000: count += 1 print("Devices priced below 1000:", count) # Try it: sample records (call Add_Device() to type your own) with open("Peripheral.csv", "w", newline="") as f: csv.writer(f).writerows([[1, "Mouse", 450], [2, "Printer", 9500], [3, "Keyboard", 800]]) Count_Device() # 2 -
Result.csv stores [St_Id, St_Name, Game_Name, Result]. Accept() adds a record (with headings on top); wonCount() counts the students who won.
import csv def Accept(sid, name, game, result): f = open("Result.csv", "a", newline="") w = csv.writer(f) if f.tell() == 0: # empty file: write the headings first w.writerow(["St_Id", "St_Name", "Game_Name", "Result"]) w.writerow([sid, name, game, result]) f.close() def wonCount(): count = 0 with open("Result.csv", "r") as f: r = csv.reader(f) next(r) # skip the headings for row in r: if row[3] == "Won": count += 1 print("Students who won:", count) open("Result.csv", "w").close() # start with an empty file Accept(1, "Riya", "Chess", "Won") Accept(2, "Aman", "Kabaddi", "Lost") Accept(3, "Sara", "Badminton", "Won") wonCount() # 2 -
CLUB.CSV stores [Mno, Name, Mobile, Fee]. NewMembers() adds records; PriorityMember() shows members paying more than 35000.
import csv def NewMembers(): n = int(input("How many members? ")) with open("CLUB.CSV", "a", newline="") as f: w = csv.writer(f) for i in range(n): mno = int(input("Member no: ")) name = input("Name: ") mobile = input("Mobile: ") fee = int(input("Fee: ")) w.writerow([mno, name, mobile, fee]) def PriorityMember(): with open("CLUB.CSV", "r") as f: for row in csv.reader(f): if int(row[3]) > 35000: print(row) # Try it: sample records (call NewMembers() to type your own) with open("CLUB.CSV", "w", newline="") as f: csv.writer(f).writerows([[1, "Kiran", "9800000001", 40000], [2, "Dev", "9800000002", 25000], [3, "Meera", "9800000003", 52000]]) PriorityMember() -
Rentals.csv stores Vehicle_ID, Vehicle_Type, Hours_Rented, Rate_Per_Hour. Add a rental and calculate the total rent (hours x rate).
import csv def AddRental(): vid = input("Vehicle ID: ") vtype = input("Vehicle type: ") hours = int(input("Hours rented: ")) rate = int(input("Rate per hour: ")) with open("Rentals.csv", "a", newline="") as f: csv.writer(f).writerow([vid, vtype, hours, rate]) def CalculateTotalRent(): total = 0 with open("Rentals.csv", "r") as f: for row in csv.reader(f): total += int(row[2]) * int(row[3]) return total # Try it: sample records (call AddRental() to type your own) with open("Rentals.csv", "w", newline="") as f: csv.writer(f).writerows([["V1", "Car", 5, 300], ["V2", "Bike", 3, 100], ["V3", "Car", 2, 300]]) print("Total rent earned:", CalculateTotalRent()) # 2400 -
States.csv stores [State, Capital, Population, Language]. Skip the header and append the records with population above 10000000 to More.csv.
import csv def copy_big_states(): fin = open("States.csv", "r") fout = open("More.csv", "a", newline="") r = csv.reader(fin) w = csv.writer(fout) next(r) # skip the header row for row in r: if int(row[2]) > 10000000: w.writerow(row) fin.close() fout.close() with open("States.csv", "w", newline="") as f: csv.writer(f).writerows([["State", "Capital", "Population", "Language"], ["Kerala", "Thiruvananthapuram", 33406061, "Malayalam"], ["Goa", "Panaji", 1458545, "Konkani"], ["Punjab", "Chandigarh", 27743338, "Punjabi"]]) open("More.csv", "w").close() # start with an empty file copy_big_states() print(open("More.csv").read()) -
Read all the rows into a list, change the one you need, then write the file again.
import csv with open("students.csv", "w", newline="") as f: csv.writer(f).writerows([["Roll", "Name", "Marks"], ["1", "Riya", "88"], ["2", "Aman", "75"]]) def update_marks(roll, new_marks): with open("students.csv", "r") as f: rows = list(csv.reader(f)) # all rows in a list for row in rows[1:]: # skip the header if row[0] == str(roll): row[2] = str(new_marks) with open("students.csv", "w", newline="") as f: csv.writer(f).writerows(rows) update_marks(2, 81) print(open("students.csv").read())
DATA STRUCTURE (STACK) 10 programs
-
A stack is LIFO: the last item pushed is the first popped. append() pushes, pop() pops.
stack = [] stack.append(10) # push stack.append(20) stack.append(30) print("Stack:", stack) print("Popped:", stack.pop()) # 30 (the last one in) print("Popped:", stack.pop()) # 20 print("Stack now:", stack) -
Check for an empty stack, look at the top item, and display from top to bottom.
def isEmpty(stk): return len(stk) == 0 def peek(stk): if isEmpty(stk): return "Stack Empty" return stk[-1] # top item, not removed def display(stk): for i in range(len(stk) - 1, -1, -1): # top to bottom print(stk[i]) books = ["Maths", "Physics", "Chemistry"] print("Top:", peek(books)) display(books) print(isEmpty([])) # True -
Implement a stack using a list, with a menu to push, pop, peek and display.
stack = [] def push(item): stack.append(item) def pop(): if len(stack) == 0: print("Underflow: stack is empty") else: print("Popped:", stack.pop()) def peek(): if len(stack) == 0: print("Stack is empty") else: print("Top:", stack[-1]) def display(): print("Stack (top first):", stack[::-1]) while True: print("1.Push 2.Pop 3.Peek 4.Display 5.Exit") ch = input("Enter choice: ") if ch == "1": push(int(input("Number: "))) elif ch == "2": pop() elif ch == "3": peek() elif ch == "4": display() elif ch == "5": break else: print("Invalid choice") -
Push the numbers of Nums that have 5 or more digits, then pop and display them, then "Stack Empty".
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765] BigNums = [] def PushBig(): for n in Nums: if len(str(n)) >= 5: BigNums.append(n) def PopBig(): while len(BigNums) > 0: print(BigNums.pop()) print("Stack Empty") PushBig() print("Stack:", BigNums) PopBig() -
NList holds [City, Country, Distance]. Push [City, Country] for cities not in India and less than 3500 km from Delhi, then pop them.
travel = [] def Push_element(NList): for L in NList: if L[1] != "India" and L[2] < 3500: travel.append([L[0], L[1]]) def Pop_element(): while len(travel) > 0: print(travel.pop()) print("Stack Empty") NList = [["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka", 3405]] Push_element(NList) Pop_element() -
Push the (title, price) records with price above 250 to the stack Books, then pop and display them.
B = [("Machine Learning Basics", 550), ("World Geography", 450), ("Wonder World", 140), ("AI Revolution", 750)] Books = [] def Push_element(): for item in B: if item[1] > 250: Books.append(item) def Pop_element(): while Books: # True while the stack is not empty print(Books.pop()) print("Stack Empty") Push_element() Pop_element() -
Accept 10 integers, push the 3-digit even ones to a stack, then pop and display them all.
stack = [] for i in range(10): n = int(input("Enter integer " + str(i + 1) + ": ")) if 100 <= abs(n) <= 999 and n % 2 == 0: # 3 digits and even stack.append(n) while stack: print(stack.pop()) print("Stack Empty") -
Push every character, then pop them all: they come out in reverse order.
def reverse_string(s): stack = [] for ch in s: stack.append(ch) # push result = "" while stack: result += stack.pop() # pop return result word = "COMPUTER" print(reverse_string(word)) # RETUPMOC print("Palindrome?", reverse_string("MADAM") == "MADAM") -
Push the remainders of division by 2, then pop them to get the binary number.
def to_binary(n): if n == 0: return "0" stack = [] while n > 0: stack.append(n % 2) # push the remainder n = n // 2 binary = "" while stack: binary += str(stack.pop()) return binary print(to_binary(13)) # 1101 print(to_binary(40)) # 101000 -
Push each opening bracket and pop when its closing bracket comes. Balanced if the stack ends empty.
def is_balanced(expr): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in expr: if ch in "([{": stack.append(ch) elif ch in ")]}": if not stack or stack.pop() != pairs[ch]: return False return len(stack) == 0 print(is_balanced("(a+b)*[c-d]")) # True print(is_balanced("{(a+b]}")) # False print(is_balanced("((a+b)")) # False
PYTHON-MYSQL CONNECTIVITY 9 programs
-
Connect with mysql.connector and check the connection. Needs MySQL and mysql-connector-python on your computer.
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="tiger", database="school") if con.is_connected(): print("Connected to MySQL") con.close() -
Run SQL with cursor.execute(). Changes (INSERT, UPDATE, DELETE) need commit().
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="tiger", database="school") cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS student (rno INT PRIMARY KEY, name VARCHAR(20), marks INT)") cur.execute("INSERT INTO student VALUES (1, 'Riya', 88)") cur.execute("INSERT INTO student VALUES (2, 'Aman', 75)") con.commit() # save the changes print("Records inserted") con.close() -
Display all the details from the table flight in the database Travel (user root, password airplane).
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="airplane", database="Travel") cur = con.cursor() cur.execute("SELECT * FROM flight") data = cur.fetchall() # list of tuples, one per row for row in data: print(row) con.close() -
Display the records from the table Account in the database SCHOOL whose fees is less than 5000.
import mysql.connector con = mysql.connector.connect(host="localhost", user="admin", password="root", database="SCHOOL") cur = con.cursor() cur.execute("SELECT * FROM Account WHERE fees < 5000") for row in cur.fetchall(): print(row) con.close() -
Accept rno, name, DOB and fee and insert them into the table Student in the database SCHOOL.
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="tiger", database="SCHOOL") cur = con.cursor() rno = int(input("Roll number: ")) name = input("Name: ") dob = input("Date of birth (YYYY-MM-DD): ") fee = float(input("Fee: ")) query = "INSERT INTO Student VALUES ({}, '{}', '{}', {})".format(rno, name, dob, fee) cur.execute(query) con.commit() print("Record added") con.close() -
In the database Keeper, set Qty to 20 for item code 111 in the table shop.
import mysql.connector con = mysql.connector.connect(host="localhost", user="admin", password="Shopping", database="Keeper") cur = con.cursor() cur.execute("UPDATE shop SET Qty = 20 WHERE Item_code = 111") con.commit() print(cur.rowcount, "record(s) updated") con.close() -
In the database LibraryDB, change the Book_Title to Data Structures in Python for Book_ID 109.
import mysql.connector con = mysql.connector.connect(host="localhost", user="librarian", password="lib@2025", database="LibraryDB") cur = con.cursor() cur.execute("UPDATE book_records SET Book_Title = 'Data Structures in Python' WHERE Book_ID = 109") con.commit() print("Book title updated") con.close() -
fetchone() gives one row at a time (None at the end); rowcount tells how many rows were read.
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="tiger", database="school") cur = con.cursor() cur.execute("SELECT name, marks FROM student WHERE marks >= 80") row = cur.fetchone() while row is not None: print(row[0], row[1]) row = cur.fetchone() print("Rows read:", cur.rowcount) con.close() -
Pass values separately with %s; the connector puts them into the query safely.
import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="tiger", database="school") cur = con.cursor() rno = int(input("Roll number to delete: ")) cur.execute("DELETE FROM student WHERE rno = %s", (rno,)) con.commit() if cur.rowcount == 0: print("No such roll number") else: print("Record deleted") con.close()