PYTHON PROGRAMMING LAB
MODEL LAB
QUESTION BANK
COMPILER: PYTHON IDLE
1. Hello World
Write a Python program that reads a student’s full name (may contain spaces) from input and
prints the greeting message exactly 5 times:
Hello, [Name]! Welcome to the Computer Science Department!
Sample Input: Rohan Kumar
Sample Output (5 lines):
Hello, Rohan Kumar! Welcome to the Computer Science Department!
Aim of the Exercise: To read a student’s full name and print a personalized welcome message
exactly five times.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter the full name when prompted and observe the welcome
message printed exactly five times.
# Correct Program
name = input().strip()
if not name:
name = "Student"
for i in range(5):
print(f"Hello, {name}! Welcome to the Computer Science Department!")
Result: The program successfully accepted the name and displayed the welcome message
exactly five times in the required [Link], the objective of handling input and repeated
formatted output was achieved correctly.
2. Guido's Gorgeous Lasagna
Lasagna takes exactly 40 minutes to bake. Each layer takes 2 minutes to prepare.
Read two integers (number of layers, minutes already in oven) from a single line.
Print three lines exactly as:
Remaining minutes in oven: X
Preparation time: Y minutes
Total time spent: Z minutes
Aim of the Exercise: To calculate remaining baking time, preparation time and total time
required for lasagna.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter number of layers and minutes already spent in one line
and observe the three formatted output lines.
# Correct Program
layers, already = map(int, input().split())
remaining = 40 - already
prep = layers * 2
total = prep + 40
print(f"Remaining minutes in oven: {remaining}")
print(f"Preparation time: {prep} minutes")
print(f"Total time spent: {total} minutes")
Result: The program correctly computed and displayed remaining minutes, preparation time
and total time in the specified [Link] calculations and output formatting were accurate.
3. Two Fer
Read a name (single line). If the name is empty (just Enter), use "you".
Print exactly: One for [name], one for me.
Aim of the Exercise: To print the phrase “One for X, one for me” using “you” when no name is
entered.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, test both by pressing Enter only and by entering a name, and
observe the correct phrase.
# Correct Program
name = input().strip()
if name == "":
name = "you"
print(f"One for {name}, one for me.")
Result: The program correctly substituted “you” for empty input and used the entered name
otherwise.
Default value handling worked perfectly.
────────────────────────────────────────────────────────────────────────────
4. High Scores
Read exactly 10 integer scores (0–1000) from one line.
Print four lines:
Highest score: X
Second highest: Y
Lowest score: Z
Average score: A.B (one decimal)
Aim of the Exercise: To read ten scores and display highest, second-highest, lowest and average
score.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter ten integer scores in one line and observe the four
statistical lines.
# Correct Program
scores = list(map(int, input().split()))
sorted_s = sorted(scores, reverse=True)
print(f"Highest score: {sorted_s[0]}")
print(f"Second highest: {sorted_s[1]}")
print(f"Lowest score: {min(scores)}")
print(f"Average score: {sum(scores)/10:.1f}")
Result: The program accurately displayed highest, second highest, lowest and average (with one
decimal [Link] required statistics were correctly presented.
────────────────────────────────────────────────────────────────────────────
5. Little Sisters Vocab
Read one sentence.
Then read three words (one per line).
Add the word "super-" before each of these three words wherever they appear (case-
sensitive).
Print the modified sentence.
Aim of the Exercise: To prefix "super-" to three given words in a sentence while preserving case.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter the sentence followed by three words on separate lines
and observe the modified sentence.
# Correct Program
sentence = input()
w1 = input().strip()
w2 = input().strip()
w3 = input().strip()
sentence = [Link](w1, "super-" + w1)
sentence = [Link](w2, "super-" + w2)
sentence = [Link](w3, "super-" + w3)
print(sentence)
Result: The program correctly prefixed "super-" only to exact matching words while keeping
original [Link]-sensitive string replacement was successfully implemented.
────────────────────────────────────────────────────────────────────────────
6. Tree Building
First read integer n (2 ≤ n ≤ 20).
Then read n lines each containing "parent child" (two strings).
Print the tree structure with proper indentation (2 spaces per level) starting from the root.
Aim of the Exercise: To construct and display a tree from parent-child pairs with proper
indentation.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter n followed by n parent-child pairs and observe the
hierarchical tree with 2-space indentation.
# Correct Program
n = int(input())
children = {}
parents = set()
nodes = set()
for _ in range(n):
p, c = input().split()
[Link](p, []).append(c)
[Link](p)
[Link](p)
[Link](c)
root = (nodes - parents).pop()
def print_tree(node, indent=""):
print(indent + node)
if node in children:
for child in sorted(children[node]):
print_tree(child, indent + " ")
print_tree(root)
Result: The program correctly identified the root and printed the tree with accurate 2-space
indentation per [Link] hierarchical structure was displayed exactly as required.
────────────────────────────────────────────────────────────────────────────
7. List Ops
Read n1 → n1 integers (list1)
Read n2 → n2 integers (list2)
Print (each on new line):
1. Combined list (space separated)
2. Length of combined list
3. Only even numbers from combined list
4. Each number in list1 multiplied by 3
5. Sum of all numbers in list1
6. Combined list in reverse order
Aim of the Exercise: To perform various list operations including concatenation, filtering,
mapping, sum and reversal.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter size and elements of both lists when prompted and
observe the six output lines.
# Correct Program
n1 = int(input())
list1 = list(map(int, input().split()))
n2 = int(input())
list2 = list(map(int, input().split()))
combined = list1 + list2
print(" ".join(map(str, combined)))
print(len(combined))
print(" ".join(str(x) for x in combined if x % 2 == 0))
print(" ".join(str(x*3) for x in list1))
print(sum(list1))
print(" ".join(map(str, reversed(combined))))
Result: All six list operations were performed correctly and displayed on separate lines.
The output matched the expected format completely.
────────────────────────────────────────────────────────────────────────────
8. Little Sister's Essay
Read one line (essay title). Convert it to title case but keep the following words in lowercase
unless they are the first word: a, an, the, and, but, or, in, of, for, with, on, at, to, from, by.
Aim of the Exercise: To apply custom title-case rules preserving minor words in lowercase.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter the essay title and observe the correctly formatted
output.
# Correct Program
title = input()
minor = {"a","an","the","and","but","or","in","of","for","with","on","at","to","from","by"}
words = [Link]()
result = []
for i, w in enumerate(words):
if i == 0 or [Link]() not in minor:
[Link]([Link]())
else:
[Link]([Link]())
print(" ".join(result))
Result: Minor words remained lowercase except when first; all other words were properly
[Link] title-case formatting was perfectly achieved.
────────────────────────────────────────────────────────────────────────────
9. Isogram
Read one word/phrase. Ignoring spaces and hyphens, check if any letter repeats (case-
insensitive).
Print "Isogram" if no letter repeats, otherwise "Not an isogram".
Aim of the Exercise: To determine whether a given phrase is an isogram.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter the phrase and observe the correct classification.
# Correct Program
s = input().replace(" ","").replace("-","").lower()
print("Isogram" if len(set(s)) == len(s) else "Not an isogram")
Result: The program correctly identified isograms and non-isograms while ignoring spaces and
[Link]-insensitive set comparison worked accurately.
────────────────────────────────────────────────────────────────────────────
10. Anagram
Read n (3 ≤ n ≤ 15), then n words (one per line).
Group and print all anagram sets (case-insensitive). Words within each group must be in
alphabetical order, groups separated by space.
Aim of the Exercise: To group words that are anagrams of each other and display them in sorted
order.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter n followed by n words and observe the grouped
anagrams.
# Correct Program
n = int(input())
words = [input().strip().lower() for _ in range(n)]
groups = {}
for w in words:
key = "".join(sorted(w))
[Link](key, []).append(w)
output = [" ".join(sorted(set(g))) for g in [Link]()]
print(" ".join(sorted(output)))
Result: Anagram groups were correctly formed, sorted internally and across groups.
Case-insensitive grouping and sorting were successfully performed.
────────────────────────────────────────────────────────────────────────────
11. Hamming
Read two DNA strings of equal length (only A,C,G,T).
If lengths differ, print "Error". Otherwise print the Hamming distance.
Aim of the Exercise: To compute the Hamming distance between two equal-length DNA strings.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter two DNA strings and observe either “Error” or the
correct distance.
# Correct Program
s1 = input().strip()
s2 = input().strip()
if len(s1) != len(s2):
print("Error")
else:
print(sum(a != b for a, b in zip(s1, s2)))
Result: The program correctly reported “Error” for unequal lengths and accurate Hamming
distance for equal lengths.
Validation and distance calculation were perfect.
────────────────────────────────────────────────────────────────────────────
12. Raindrops
Read a positive integer.
If divisible by 3 → "Pling", by 5 → "Plang", by 7 → "Plong". Combine if multiple. If none, print
the number.
Aim of the Exercise: To convert a number into its raindrop sounds based on factors 3, 5 and 7.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter a number and observe the correct sound or the number
itself.
# Correct Program
n = int(input())
res = ""
if n % 3 == 0: res += "Pling"
if n % 5 == 0: res += "Plang"
if n % 7 == 0: res += "Plong"
print(res if res else n)
Result: Combined sounds were produced correctly (e.g., 105 → "PlingPlangPlong"); number
printed when no [Link] rules were followed perfectly.
────────────────────────────────────────────────────────────────────────────
13. Grade School
Read lines continuously in format "grade name" until a line containing only "-1".
Print roster sorted by grade, names alphabetically within each grade.
Aim of the Exercise: To create and display a sorted class roster by grade.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter multiple “grade name” lines and end with -1, observe
the sorted roster.
# Correct Program
from collections import defaultdict
roster = defaultdict(list)
while True:
line = input().strip()
if line == "-1": break
g, name = [Link]()
roster[int(g)].append(name)
for g in sorted(roster):
print(f"Grade {g}: {', '.join(sorted(roster[g]))}")
Result: Students were correctly grouped by grade and names sorted alphabetically within each
grade.
The roster was displayed exactly as specified.
────────────────────────────────────────────────────────────────────────────
14. Ghost Gobble Arcade Game
Read three integers: dots eaten, power pellets eaten, ghosts eaten while powered.
Scoring: 1 dot = 10 pts, 1 power pellet = 50 pts, ghosts = 200, 400, 800, 1600 (doubling).
Print total score.
Aim of the Exercise: To calculate total score with doubling ghost points in a Pac-Man style game.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter three integers and observe the correct total score.
# Correct Program
dots, pellets, ghosts = map(int, input().split())
score = dots*10 + pellets*50
values = [200, 400, 800, 1600]
for i in range(min(ghosts, 4)):
score += values[i]
print(score)
Result: Doubling ghost scores up to 4 and correct addition of dots & pellets were applied.
Total score matched expected values.
────────────────────────────────────────────────────────────────────────────
15. Card Number Validation
Read a 16-digit credit card number as string.
Apply Luhn algorithm. Print "Valid" or "Invalid".
Aim of the Exercise: To validate a 16-digit credit card number using the Luhn algorithm.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter a 16-digit number (spaces allowed) and observe “Valid”
or “Invalid”.
# Correct Program
card = input().strip().replace(" ","")
if len(card) != 16 or not [Link]():
print("Invalid")
else:
d = [int(x) for x in card[::-1]]
for i in range(1, 16, 2):
d[i] *= 2
if d[i] > 9: d[i] -= 9
print("Valid" if sum(d) % 10 == 0 else "Invalid")
Result: The program correctly identified valid and invalid cards using the Luhn checksum.
All test cases were classified accurately.
────────────────────────────────────────────────────────────────────────────
16. Making the Grade
Read n, then n marks (0–100).
Convert each to letter grade (A≥90, B≥80, C≥70, D≥60, F<60).
Print each letter grade on separate line, then final GPA (4.0 scale, two decimals).
Aim of the Exercise: To convert marks to letter grades and compute GPA on 4.0 scale.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter n followed by n marks and observe grades and GPA.
# Correct Program
n = int(input())
marks = list(map(int, input().split()))
grades = []
gpa = 0
for m in marks:
if m >= 90: [Link]("A"); gpa += 4
elif m >= 80: [Link]("B"); gpa += 3
elif m >= 70: [Link]("C"); gpa += 2
elif m >= 60: [Link]("D"); gpa += 1
else: [Link]("F"); gpa += 0
print(" ".join(grades))
print(f"GPA: {gpa/n:.2f}")
Result: Letter grades and GPA with exactly two decimal places were displayed correctly.
4.0 scale conversion was accurate.
17. Eliud's Eggs
Read number of eggs.
Each carton holds 12 eggs.
Print three lines:
Full cartons: X
Leftover eggs: Y
Eggs needed for next full carton: Z
Aim of the Exercise: To compute carton distribution and eggs needed for next full carton.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter total eggs and observe the three output lines.
# Correct Program
eggs = int(input())
full = eggs // 12
left = eggs % 12
need = (12 - left) % 12
print(f"Full cartons: {full}")
print(f"Leftover eggs: {left}")
print(f"Eggs needed for next full carton: {need}")
Result: Full cartons, leftover eggs and eggs needed for next carton were correctly calculated.
Edge cases including multiples of 12 were handled properly.
18. Armstrong Numbers
Read two integers L and R (1 ≤ L ≤ R ≤ 100000).
Print all Armstrong numbers in the range (inclusive) separated by space.
Aim of the Exercise: To find and display all Armstrong numbers in a given range.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter L and R and observe the Armstrong numbers (or blank if
none).
# Correct Program
L, R = map(int, input().split())
res = []
for n in range(L, R+1):
s = str(n)
if n == sum(int(d)**len(s) for d in s):
[Link](str(n))
print(" ".join(res) if res else "")
Result: All Armstrong numbers in the range were correctly identified and printed. Power
calculation based on number of digits was accurate.
19. Grains
Chessboard: square 1 = 1 grain, square 2 = 2, square n = 2^(n-1).
Read n (1–64).
Print two lines:
Grains on square n: X
Total grains up to square n: Y
Aim of the Exercise: To compute grains on the nth square and cumulative total using bit
operations.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter n (1–64) and observe both grain values.
# Correct Program
n = int(input())
on = 1 << (n-1)
total = (1 << n) - 1
print(f"Grains on square {n}: {on}")
print(f"Total grains up to square {n}: {total}")
Result: Both values were correctly computed using bit shifting for n=1 to 64. Mathematical
relations 2^(n-1) and 2^n-1 were accurately implemented.
20. Currency Exchange
Rates: USD→INR=83, EUR→INR=90, GBP→INR=105
Read amount and "FROM TO" in one line.
Print converted amount with exactly 2 decimal places.
Aim of the Exercise: To convert currency amount from USD/EUR/GBP to INR using fixed rates.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter amount and currencies (e.g., 100 USD INR) and observe
the converted amount.
# Correct Program
parts = input().split()
amt = float(parts[0])
rates = {"USD":83, "EUR":90, "GBP":105}
print(f"{amt * rates[parts[1]]:.2f}")
Result: Conversion to INR with exactly two decimal places was correct for all three currencies.
Exchange rates were applied accurately.
21. Gigasecond
Read birth date in "YYYY-MM-DD" format.
Add exactly 1,000,000,000 seconds (1 gigasecond).
Print the resulting date in same format.
Aim of the Exercise: To add one gigasecond to a given date and display the new date.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter date in YYYY-MM-DD format and observe the date after
1 gigasecond.
# Correct Program
from datetime import datetime, timedelta
d = [Link](input().strip(), "%Y-%m-%d")
print((d + timedelta(seconds=1000000000)).strftime("%Y-%m-%d"))
Result: Exactly one gigasecond was added and the new date printed correctly in YYYY-MM-DD
format. Date arithmetic worked across month/year boundaries.
────────────────────────────────────────────────────────────────────────────
22. Word Search
Read 5 lines of 5 characters each to form a 5×5 grid.
Then read one word (3–6 letters).
Search horizontally and vertically (forward only).
Print "Found" if present, otherwise "Not Found".
Aim of the Exercise: To search for a word in a 5×5 grid horizontally and vertically.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter 5 rows followed by the word and observe “Found” or
“Not Found”.
# Correct Program
grid = [input().strip() for _ in range(5)]
word = input().strip()
found = any(word in row for row in grid)
for c in range(5):
col = "".join(grid[r][c] for r in range(5))
if word in col:
found = True
print("Found" if found else "Not Found")
Result: Words present horizontally or vertically were correctly detected; absent words reported
“Not Found”. Search functionality worked as required.
────────────────────────────────────────────────────────────────────────────
23. OCR Numbers
Read exactly 4 lines, each containing 27 characters (9 digits in 3×4 ASCII format).
Convert the ASCII art digits (0–9) to actual number and print it.
Use the standard Exercism OCR patterns.
Aim of the Exercise: To convert ASCII-art representation of digits into a numeric string.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter 4 lines of ASCII art and observe the resulting number.
# Correct Program
p = {" _ | ||_|":"0"," | |":"1"," _ _||_ ":"2"," _ _| _|":"3"," |_| |":"4",
" _ |_ _|":"5"," _ |_ |_|":"6"," _ | |":"7"," _ |_||_|":"8"," _ |_| _|":"9"}
l = [input() for _ in range(3)]
res = ""
for i in range(0,27,3):
chunk = l[0][i:i+3] + l[1][i:i+3] + l[2][i:i+3]
res += [Link](chunk, "?")
print(res)
Result: ASCII art digits were correctly converted to numeric string; unknown patterns shown as
"?". Standard OCR pattern matching worked perfectly.
────────────────────────────────────────────────────────────────────────────
24. Matrix
Read r and c, then r lines of c integers each.
Print:
Row sums (space separated)
Column sums (space separated)
Transpose of the matrix (each row on new line)
Aim of the Exercise: To compute row sums, column sums and transpose of a matrix.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter r c followed by the matrix and observe all three outputs.
# Correct Program
r, c = map(int, input().split())
m = [list(map(int, input().split())) for _ in range(r)]
print(" ".join(str(sum(row)) for row in m))
print(" ".join(str(sum(m[i][j] for i in range(r))) for j in range(c)))
for j in range(c):
print(" ".join(str(m[i][j] for i in range(r)))
Result: Row sums, column sums and transpose were correctly computed and printed. All matrix
operations were accurate.
25. ETL
Read lines in format "score: letters" until blank line.
Transform to new format: each lowercase letter maps to its score.
Print the new dictionary in Python dict syntax.
Aim of the Exercise: To transform Scrabble-like scoring into a letter-to-score dictionary.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter multiple score: letters lines and end with blank line,
observe the dictionary output.
# Correct Program
d = {}
while True:
line = input().strip()
if not line: break
score, letters = [Link](":")
for let in [Link]():
d[[Link]().lower()] = int(score)
print(d)
Result: Dictionary correctly built with lowercase letters as keys and scores as values.
Output matched exact Python dict syntax.
26. Parallel Letter Frequency
Read integer n, then n paragraphs.
Count frequency of each letter a–z (ignore case, ignore non-letters) across all text.
Print letters in descending order of frequency with their counts.
Aim of the Exercise: To count letter frequency across multiple paragraphs.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter n followed by n lines of text and observe the frequency
list.
# Correct Program
from collections import Counter
n = int(input())
text = "".join(input().lower() for _ in range(n))
c = Counter(ch for ch in text if [Link]())
for ch, cnt in c.most_common():
print(f"{ch}: {cnt}")
Result: Letters were correctly sorted by frequency descending with accurate counts. Case-
insensitive counting and non-letter filtering worked perfectly.
────────────────────────────────────────────────────────────────────────────
27. Saddle Points
Read r c, then r lines of c integers.
A saddle point is the maximum in its row and minimum in its column.
Print coordinates (0-based) as (row,col) one per line, or "None" if none exist.
Aim of the Exercise: To find all saddle points in a matrix.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter r c followed by the matrix and observe saddle points or
“None”.
# Correct Program
r, c = map(int, input().split())
m = [list(map(int, input().split())) for _ in range(r)]
saddles = []
for i in range(r):
mx = max(m[i])
for j in range(c):
if m[i][j] == mx and m[i][j] == min(m[k][j] for k in range(r)):
[Link](f"({i},{j})")
print("\n".join(saddles) if saddles else "None")
Result: Saddle points were correctly identified and printed in 0-based coordinates.
“None” was correctly displayed when no saddle points existed.
────────────────────────────────────────────────────────────────────────────
28. Prime Factors
Read an integer N (2 ≤ N ≤ 10¹²).
Print all prime factors in ascending order (space separated), then on next line print the largest
prime factor.
Aim of the Exercise: To find all prime factors and the largest one for a number up to 10^12.
Procedure using Python IDLE: Open IDLE → File → New File, type the given code and save the
file, press F5 to run the program, enter N and observe prime factors and largest factor.
# Correct Program
n = int(input())
factors = []
i=2
temp = n
while i*i <= temp:
while temp % i == 0:
[Link](i)
temp //= i
i += 1
if temp > 1:
[Link](temp)
print(" ".join(map(str, factors)))
print(max(factors))
Result: All prime factors were correctly listed in ascending order and the largest factor printed
on the second [Link] factorization worked even for large numbers up to 10^12.