Class XI Computer Science – Unit 2: Computational Thinking and Programming-1 | 50 Advanced Python Programs
Class 11 · Computer Science
Class XI Computer Science — Unit 2
Computational Thinking and Programming-1
50 Advanced Python Programs
These programs are based on real-world and application-oriented situations such as ATM systems, ticket booking, student records, inventory management, text processing and data analysis.
The programs combine fundamental Python concepts and are useful for board examination preparation, practical work, programming practice and computational thinking.
Topic 1: Flow of Control, Conditionals & Loops
- if, if-else and if-elif-else
- for loop and while loop
- Nested loops
- break and continue
- for-else and while-else
- Conditional expressions
- Real-world problem solving using control flow
Program 1: ATM PIN Verification with for-else
Scenario: Design an ATM system that allows a user three attempts to enter the correct PIN. After successful verification, the user can check balance, withdraw cash or exit.
balance = 10000.00
correct_pin = "1234"
for attempt in range(1, 4):
pin = input(f"Attempt {attempt}/3 - Enter 4-digit PIN: ")
if pin == correct_pin:
print("\nVerification Successful!")
while True:
print("\n1. Check Balance")
print("2. Withdraw Cash")
print("3. Exit")
choice = int(input("Select option: "))
if choice == 1:
print(f"Current Balance: Rs. {balance}")
elif choice == 2:
amt = float(input("Enter withdrawal amount: Rs. "))
if amt > balance:
print("Insufficient balance!")
elif amt <= 0:
print("Invalid amount!")
else:
balance -= amt
print(f"Rs. {amt} withdrawn successfully.")
elif choice == 3:
print("Thank you for using our ATM.")
break
else:
print("Invalid transaction option.")
break
else:
print("\n[ALERT] 3 incorrect attempts. Your card is blocked for 24 hours!")
This program demonstrates for-else, nested while, break, conditional statements and user input.
The else associated with the for loop executes only when the loop completes normally without encountering break.
Program 2: Movie Ticket Booking System
Scenario: Create a simple seat-booking system in which a customer can reserve three seats from a 3 × 4 seating arrangement.
rows, cols = 3, 4
seats = [["O" for _ in range(cols)] for _ in range(rows)]
booked = 0
while booked < 3:
r = int(input("Enter row (0-2): "))
c = int(input("Enter column (0-3): "))
if 0 <= r < rows and 0 <= c < cols:
if seats[r][c] == "O":
seats[r][c] = "X"
booked += 1
print("Seat booked!")
else:
print("Seat already taken. Choose another.")
else:
print("Invalid seat number.")
for row in seats:
print(row)
Program 3: Number Guessing Game with Limited Chances
import random
secret = random.randint(1, 50)
chances = 5
while chances > 0:
guess = int(input(
f"Guess the number ({chances} chances left): "
))
if guess == secret:
print("Correct! You win!")
break
elif guess < secret:
print("Too low!")
else:
print("Too high!")
chances -= 1
else:
print(f"Out of chances! The number was {secret}.")
random.randint(), while loop, conditional statements,
counter and loop-else.
Program 4: Electricity Bill Calculator
units = float(input("Enter units consumed: "))
if units <= 100:
bill = units * 3.5
elif units <= 300:
bill = 100 * 3.5 + (units - 100) * 5
else:
bill = 100 * 3.5 + 200 * 5 + (units - 300) * 7
surcharge = bill * 0.10 if bill > 1000 else 0
print(f"Total Bill: Rs. {bill + surcharge:.2f}")
Program 5: Multiplication Table Generator
n = int(input("Enter number: "))
for i in range(1, 11):
print(f"{n} x {i:2} = {n*i:3}")
Program 6: Password Strength Checker
pwd = input("Enter password: ")
has_upper = has_lower = has_digit = has_special = False
special_chars = "!@#$%^&*"
for ch in pwd:
if ch.isupper():
has_upper = True
elif ch.islower():
has_lower = True
elif ch.isdigit():
has_digit = True
elif ch in special_chars:
has_special = True
score = sum([
has_upper,
has_lower,
has_digit,
has_special,
len(pwd) >= 8
])
levels = {
5: "Very Strong",
4: "Strong",
3: "Moderate"
}
print(levels.get(score, "Weak"))
sum().
Program 7: Floyd's Triangle
n = int(input("Enter number of rows: "))
num = 1
for i in range(1, n + 1):
for j in range(i):
print(num, end=" ")
num += 1
print()
Program 8: Simple Interest and Compound Interest Comparison
p = float(input("Principal: "))
r = float(input("Rate: "))
years = int(input("Years: "))
si = p
ci = p
for y in range(1, years + 1):
si += p * r / 100
ci += ci * r / 100
print(
f"Year {y}: SI Balance={si:.2f}, "
f"CI Balance={ci:.2f}"
)
Program 9: Prime Numbers in a Range
start, end = 10, 50
for num in range(start, end + 1):
if num < 2:
continue
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Program 10: Vending Machine Simulation
items = {
"Water": 20,
"Chips": 30,
"Soda": 35
}
print(items)
choice = input("Select item: ")
if choice in items:
price = items[choice]
paid = 0
while paid < price:
paid += int(
input(
f"Insert coin (Rs. {price-paid} remaining): "
)
)
change = paid - price
print(
f"Dispensing {choice}. "
f"Change returned: Rs. {change}"
)
else:
print("Item not available.")
Topic 2: Strings
- String traversal
- String methods
- Slicing
- split() and join()
- Character classification
- String searching and comparison
Program 11: Sentence Case Converter
text = input("Enter paragraph: ")
sentences = text.split(". ")
result = ". ".join(
s.strip().capitalize()
for s in sentences
)
print(result)
split(), capitalize(),
generator expression and join().
Program 12: Caesar Cipher Encoder
text = input("Enter message: ")
shift = int(input("Enter shift value: "))
result = ""
for ch in text:
if ch.isalpha():
base = ord('A') if ch.isupper() else ord('a')
result += chr(
(ord(ch) - base + shift) % 26 + base
)
else:
result += ch
print("Encrypted:", result)
ord(), chr(), modulo arithmetic
and string traversal.
Program 13: Word Frequency Counter
text = input("Enter text: ").lower()
words = text.split()
freq = {}
for w in words:
w = w.strip(".,!?")
freq[w] = freq.get(w, 0) + 1
for word, count in freq.items():
print(f"{word}: {count}")
Program 14: Palindrome Phrase Checker
s = input("Enter phrase: ")
cleaned = "".join(
ch.lower()
for ch in s
if ch.isalnum()
)
print(
"Palindrome"
if cleaned == cleaned[::-1]
else "Not a Palindrome"
)
isalnum(), string slicing, generator expression
and join().
Program 15: Longest Word Finder
sentence = input("Enter sentence: ")
words = sentence.split()
longest = max(words, key=len)
print(
f"Longest word: {longest} "
f"({len(longest)} letters)"
)
split(), max() and the
key parameter.
Program 16: Vowel Removal
s = input("Enter string: ")
no_vowels = ""
for ch in s:
if ch.lower() not in "aeiou":
no_vowels += ch
print("Without vowels:", no_vowels)
Program 17: Anagram Checker
s1 = input("Enter first word: ").lower()
s2 = input("Enter second word: ").lower()
if sorted(s1) == sorted(s2):
print("Anagrams")
else:
print("Not Anagrams")
sorted() and string comparison.
Program 18: Text Justification Formatter
paragraph = input("Enter text: ")
words = paragraph.split()
line = ""
for word in words:
if len(line) + len(word) + 1 <= 20:
line += word + " "
else:
print(line.strip().ljust(20, '.'))
line = word + " "
print(line.strip().ljust(20, '.'))
ljust() and line-wrapping logic.
Program 19: Separate Digits, Alphabets and Special Characters
s = input("Enter mixed string: ")
digits = ""
alphabets = ""
specials = ""
for ch in s:
if ch.isdigit():
digits += ch
elif ch.isalpha():
alphabets += ch
else:
specials += ch
print("Digits:", digits)
print("Alphabets:", alphabets)
print("Specials:", specials)
isdigit(), isalpha() and character
classification.
Program 20: Run-Length Encoding
s = input("Enter string: ")
encoded = ""
i = 0
while i < len(s):
count = 1
while i + 1 < len(s) and s[i] == s[i + 1]:
i += 1
count += 1
encoded += s[i] + str(count)
i += 1
print("Encoded:", encoded)
Topic 3: Lists
- List traversal
- Nested lists
- List slicing
- List methods
- Searching and sorting
- List of tuples and dictionaries
Program 21: Student Grade Management
students = [
["Aarav", 85],
["Diya", 45],
["Kabir", 72],
["Meera", 91]
]
for s in students:
if s[1] >= 90:
grade = "A"
elif s[1] >= 75:
grade = "B"
elif s[1] >= 50:
grade = "C"
else:
grade = "Fail"
print(
f"{s[0]}: {s[1]} marks -> Grade {grade}"
)
Program 22: Matrix Addition
A = [
[1, 2, 3],
[4, 5, 6]
]
B = [
[7, 8, 9],
[1, 2, 3]
]
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j] + B[i][j])
result.append(row)
print("Sum Matrix:", result)
Program 23: Remove Duplicates while Preserving Order
L = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = []
for item in L:
if item not in unique:
unique.append(item)
print("Unique elements:", unique)
Program 24: Second Largest Element
L = [23, 45, 12, 67, 34, 89, 2]
largest = second = float('-inf')
for num in L:
if num > largest:
second = largest
largest = num
elif num > second and num != largest:
second = num
print("Second Largest:", second)
Program 25: Rotate a List by K Positions
L = [1, 2, 3, 4, 5, 6, 7]
k = int(input("Enter rotation count: ")) % len(L)
rotated = L[k:] + L[:k]
print("Rotated List:", rotated)
Program 26: Merge Two Sorted Lists
L1 = [1, 3, 5, 7]
L2 = [2, 4, 6, 8]
merged = []
i = j = 0
while i < len(L1) and j < len(L2):
if L1[i] < L2[j]:
merged.append(L1[i])
i += 1
else:
merged.append(L2[j])
j += 1
merged.extend(L1[i:])
merged.extend(L2[j:])
print("Merged List:", merged)
Program 27: Matrix Transpose
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transpose = [
[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))
]
print("Transpose:", transpose)
Program 28: Sales Data Analysis
sales = [
("Jan", 45000),
("Feb", 52000),
("Mar", 38000),
("Apr", 61000)
]
amounts = [s[1] for s in sales]
best = max(sales, key=lambda x: x[1])
worst = min(sales, key=lambda x: x[1])
print(f"Best Month: {best[0]} (Rs.{best[1]})")
print(f"Worst Month: {worst[0]} (Rs.{worst[1]})")
print(
f"Average Sales: "
f"Rs.{sum(amounts)/len(amounts):.2f}"
)
Program 29: Bubble Sort
L = [64, 34, 25, 12, 22, 11, 90]
n = len(L)
for i in range(n - 1):
for j in range(n - 1 - i):
if L[j] > L[j + 1]:
L[j], L[j + 1] = L[j + 1], L[j]
print("Sorted List:", L)
Program 30: Inventory Stock Alert System
inventory = [
{"item": "Pen", "qty": 5},
{"item": "Notebook", "qty": 25},
{"item": "Eraser", "qty": 2}
]
for stock in inventory:
if stock["qty"] < 10:
print(
f"LOW STOCK ALERT: "
f"{stock['item']} - only {stock['qty']} left!"
)
else:
print(
f"{stock['item']}: "
f"Stock OK ({stock['qty']})"
)
Topic 4: Tuples
- Tuple indexing
- Tuple unpacking
- Tuple of tuples
- Immutability
- Tuple slicing
Program 31: Coordinate Distance Calculator
import math
p1 = (2, 3)
p2 = (7, 9)
distance = math.sqrt(
(p2[0] - p1[0]) ** 2 +
(p2[1] - p1[1]) ** 2
)
print(f"Distance: {distance:.2f}")
Program 32: Employee Records Using Tuple of Tuples
employees = (
("Raj", "Manager", 75000),
("Priya", "Developer", 62000),
("Aman", "Intern", 20000)
)
for name, role, salary in employees:
bonus = salary * 0.1 if role != "Intern" else 0
print(
f"{name} ({role}): "
f"Bonus = Rs.{bonus}"
)
Program 33: Highest and Lowest Salary
records = (
("Aarav", 55000),
("Diya", 72000),
("Kabir", 48000)
)
highest = max(records, key=lambda x: x[1])
lowest = min(records, key=lambda x: x[1])
print("Highest paid:", highest)
print("Lowest paid:", lowest)
Program 34: Swapping Values Using Tuple Unpacking
a, b, c = 10, 20, 30
a, b, c = c, a, b
print(f"a={a}, b={b}, c={c}")
Program 35: Tuple-Based Stack for Bracket Matching
expr = input("Enter expression: ")
stack = ()
balanced = True
for ch in expr:
if ch == '(':
stack += (ch,)
elif ch == ')':
if len(stack) == 0:
balanced = False
break
stack = stack[:-1]
print(
"Balanced"
if balanced and len(stack) == 0
else "Not Balanced"
)
Program 36: Convert List of Tuples to Dictionary
data = [
("Math", 88),
("Science", 92),
("English", 75)
]
subject_marks = dict(data)
print(subject_marks)
print(
"Highest scoring subject:",
max(subject_marks, key=subject_marks.get)
)
Topic 5: Dictionaries
- Key-value pairs
- Dictionary traversal
- get() and pop()
- Nested dictionaries
- Dictionary frequency counting
- Dictionary merging
Program 37: Contact Book Manager
contacts = {}
while True:
print("\n1.Add 2.Search 3.Delete 4.Exit")
ch = int(input("Choice: "))
if ch == 1:
name = input("Name: ")
contacts[name] = input("Phone: ")
elif ch == 2:
name = input("Search name: ")
print(
contacts.get(name, "Not found")
)
elif ch == 3:
name = input("Delete name: ")
contacts.pop(name, None)
print("Deleted (if existed).")
elif ch == 4:
break
print("Final Contacts:", contacts)
Program 38: Word Frequency Using Dictionary
text = (
"the quick brown fox jumps over "
"the lazy dog the fox runs"
)
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
sorted_freq = dict(
sorted(
freq.items(),
key=lambda x: x[1],
reverse=True
)
)
print(sorted_freq)
Program 39: Exam Result Dictionary
results = {
"Aarav": {
"Maths": 90,
"Science": 85
},
"Diya": {
"Maths": 78,
"Science": 92
}
}
for student, subjects in results.items():
total = sum(subjects.values())
print(
f"{student}: "
f"Total = {total}, "
f"Average = {total / len(subjects):.2f}"
)
Program 40: Merging Two Dictionaries
d1 = {
"apple": 10,
"banana": 5,
"mango": 8
}
d2 = {
"banana": 7,
"grape": 12,
"mango": 3
}
merged = d1.copy()
for key, value in d2.items():
if key in merged:
merged[key] += value
else:
merged[key] = value
print("Merged Inventory:", merged)
Program 41: Most Common Character
s = input("Enter string: ")
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
most_common = max(freq, key=freq.get)
print(
f"Most frequent character: "
f"'{most_common}' "
f"({freq[most_common]} times)"
)
Program 42: Dictionary-Based Voting System
votes = {}
n = int(input("Number of votes: "))
for _ in range(n):
candidate = input("Vote for: ")
votes[candidate] = votes.get(candidate, 0) + 1
winner = max(votes, key=votes.get)
print("Vote Count:", votes)
print(
f"Winner: {winner} "
f"with {votes[winner]} votes"
)
Program 43: Employee Database Using setdefault()
emp = {}
emp.setdefault("E101", []).append("Raj")
emp.setdefault("E101", []).append("Developer")
emp.setdefault("E102", []).append("Priya")
print(emp)
Program 44: Grade Distribution Counter
marks = [
45, 78, 92, 34, 67,
88, 55, 23, 99, 60
]
grades = {
"A": 0,
"B": 0,
"C": 0,
"Fail": 0
}
for m in marks:
if m >= 90:
grades["A"] += 1
elif m >= 75:
grades["B"] += 1
elif m >= 40:
grades["C"] += 1
else:
grades["Fail"] += 1
print(grades)
Topic 6: Operators & Expressions
Program 45: BMI Calculator with Category Classification
weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
bmi = weight / height ** 2
category = (
"Underweight" if bmi < 18.5 else
"Normal" if bmi < 25 else
"Overweight" if bmi < 30 else
"Obese"
)
print(
f"BMI: {bmi:.2f} -> {category}"
)
Program 46: Leap Year Checker
year = int(input("Enter year: "))
is_leap = (
(year % 4 == 0 and year % 100 != 0)
or
(year % 400 == 0)
)
print(
f"{year} is "
f"{'a Leap Year' if is_leap else 'not a Leap Year'}"
)
Program 47: Temperature Conversion
scale = input(
"Convert from (C/F): "
).upper()
temp = float(
input("Enter temperature: ")
)
if scale in ("C", "c"):
print(
f"Fahrenheit: "
f"{temp * 9 / 5 + 32:.2f}"
)
elif scale in ("F", "f"):
print(
f"Celsius: "
f"{(temp - 32) * 5 / 9:.2f}"
)
else:
print("Invalid scale")
Program 48: Calculator Using Augmented Assignment
result = 0
ops = [
"+5",
"-3",
"*4",
"//2",
"**2"
]
for op in ops:
if op.startswith("+"):
value = int(op[1:])
result += value
elif op.startswith("-"):
value = int(op[1:])
result -= value
elif op.startswith("**"):
value = int(op[2:])
result **= value
elif op.startswith("*"):
value = int(op[1:])
result *= value
elif op.startswith("//"):
value = int(op[2:])
result //= value
print(
f"After {op}: {result}"
)
+=, -=, *=,
//= and **=.
Topic 7: Modules — math, random and statistics
Program 49: Dice Rolling Simulator with Statistics
import random
import statistics
rolls = [
random.randint(1, 6)
for _ in range(20)
]
print("Rolls:", rolls)
print(
"Mean:",
statistics.mean(rolls)
)
print(
"Median:",
statistics.median(rolls)
)
print(
"Mode:",
statistics.mode(rolls)
)
random.randint(), list comprehension and
statistical functions such as mean, median and mode.
Program 50: Circle and Sphere Geometry Calculator
import math
r = float(input("Enter radius: "))
area = math.pi * r ** 2
circumference = 2 * math.pi * r
volume = (4 / 3) * math.pi * r ** 3
print(
f"Area: {area:.2f}"
)
print(
f"Circumference: "
f"{circumference:.2f}"
)
print(
f"Sphere Volume: "
f"{volume:.2f}"
)
print(
f"Ceil of radius: "
f"{math.ceil(r)}, "
f"Floor: {math.floor(r)}"
)
math.pi, math.ceil(),
math.floor() and formula-based calculations.
Quick Revision: 50 Programs at a Glance
| Programs | Topic | Major Concepts |
|---|---|---|
| 1–10 | Flow of Control | if-else, loops, break, continue, for-else, while, nested loops |
| 11–20 | Strings | String methods, slicing, traversal, split(), join(), character processing |
| 21–30 | Lists | Nested lists, slicing, searching, sorting, matrices, list processing |
| 31–36 | Tuples | Indexing, unpacking, immutability, tuple processing |
| 37–44 | Dictionaries | Key-value pairs, get(), pop(), nested dictionaries, frequency counting |
| 45–48 | Operators & Expressions | Arithmetic, logical, membership, conditional expressions |
| 49–50 | Modules | math, random and statistics |
Board Examination & Practical Tips
- Type programs yourself: Do not depend only on copy-paste. Writing programs improves coding accuracy and syntax recall.
- Predict the output: Before executing a program, manually trace the values of variables and predict the output.
- Practise Strings: Pay special attention to slicing, traversal and string methods.
- Practise Lists: Nested lists, matrices, searching and sorting are important programming patterns.
-
Practise Dictionaries:
Focus on
get(),items(),values(),pop()and frequency counting. - Dry run loops: For every loop, identify the initial value, condition, update and number of iterations.
- Indentation matters: Python uses indentation to define blocks of code.
-
Write meaningful variable names:
Names such as
marks,total,balanceandstudent_namemake programs easier to understand.
Final Takeaway
Programming is not simply about remembering syntax. The objective is to analyse a problem, break it into smaller steps, select appropriate Python constructs and develop a logical solution.
These 50 programs provide a progressive practice set in which individual Python concepts are combined to solve real-world computational problems.
First understand the problem → identify the data required → select the appropriate data structure → design the logic → write the Python program → dry run it → test different inputs.