Important CS Programs
Master your practical exams with our curated list of essential Python programs for Class 11 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.
PYTHON BASICS, INPUT/OUTPUT & OPERATORS 11 programs
-
input() reads text typed by the user; print() shows it.
message = input("Enter a welcome message: ") print("Your message is:", message) # Sample run (the values after each prompt are typed by the user): # Enter a welcome message: Welcome to CSIP12! # Your message is: Welcome to CSIP12! -
input() always gives text, so int() converts it to a number before adding.
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print("Sum =", a + b) # Sample run (the values after each prompt are typed by the user): # Enter first number: 25 # Enter second number: 17 # Sum = 42 -
SI = P x R x T / 100. float() allows decimal values.
p = float(input("Principal: ")) r = float(input("Rate of interest: ")) t = float(input("Time in years: ")) si = p * r * t / 100 print("Simple Interest =", si) print("Total amount =", p + si) # Sample run (the values after each prompt are typed by the user): # Principal: 5000 # Rate of interest: 6.5 # Time in years: 2 # Simple Interest = 650.0 # Total amount = 5650.0 -
Use arithmetic operators to calculate area and perimeter.
length = float(input("Length: ")) breadth = float(input("Breadth: ")) print("Area =", length * breadth) print("Perimeter =", 2 * (length + breadth)) # Sample run (the values after each prompt are typed by the user): # Length: 12 # Breadth: 7.5 # Area = 90.0 # Perimeter = 39.0 -
Two ways: with a third variable, and Python's a, b = b, a.
a = 10 b = 20 temp = a # way 1: using a third variable a = b b = temp print("After swap 1: a =", a, "b =", b) a, b = b, a # way 2: tuple assignment print("After swap 2: a =", a, "b =", b) # Output: # After swap 1: a = 20 b = 10 # After swap 2: a = 10 b = 20 -
/ gives a decimal, // the whole-number quotient, % the remainder and ** the power.
a = 17 b = 5 print("a + b =", a + b) print("a - b =", a - b) print("a * b =", a * b) print("a / b =", a / b) # division print("a // b =", a // b) # floor division print("a % b =", a % b) # remainder print("a ** 2 =", a ** 2) # power # Output: # a + b = 22 # a - b = 12 # a * b = 85 # a / b = 3.4 # a // b = 3 # a % b = 2 # a ** 2 = 289 -
Python converts int to float by itself (implicit); int(), float() and str() convert on request (explicit).
x = 10 # int y = 2.5 # float z = x + y # implicit: the result becomes float print(z, type(z)) s = "45" n = int(s) + 5 # explicit: str -> int print(n) print(str(100) + "%") # explicit: int -> str print(float("3.75") * 2) # explicit: str -> float # Output: # 12.5 <class 'float'> # 50 # 100% # 7.5 -
x += 5 means x = x + 5. is checks if two names point to the same object; in checks membership.
x = 10 x += 5 # augmented assignment x *= 2 print("x =", x) a = [1, 2] b = a c = [1, 2] print(a is b) # True: same object print(a is c) # False: different objects with equal values print(a == c) # True: equal values print(3 in [1, 2, 3]) print("z" not in "python") # Output: # x = 30 # True # False # True # True # True -
not is done first, then and, then or.
print(19 < 11 and 29 > 19 or not 75 > 30) print(True or False and False) print(not (5 > 3)) age = 17 print(age >= 13 and age <= 19) # is a teenager? # Output: # False # True # False # True -
Expressions from CBSE papers. ** is done first (right to left), then * / // %, then + -.
print(14 % 3 ** 2 * 4) # 3**2=9, 14%9=5, 5*4=20 print(16 * 5 / 4 * 2 / 5 - 8) print(3 - 2 ** 2 ** 3 + 99 / 11) # 2**3=8 first, then 2**8=256 print(10 - 3 ** 2 ** 2 + 144 / 12) print(25 + 100 ** 1 ** 3 / 5) # Output: # 20 # 0.0 # -244.0 # -59.0 # 45.0 -
A syntax error stops the program before it runs; a runtime error stops it while running; a logical error gives a wrong answer.
# Syntax error (the program will not start): # print("Hello" <- missing ) # Runtime error (stops while running): # print("15" + 3) <- TypeError: cannot add str and int print("15" + str(3)) # fixed: joins text -> 153 print(int("15") + 3) # fixed: adds numbers -> 18 # Logical error (runs, but the answer is wrong): a, b = 10, 20 average = a + b / 2 # wrong: only b is divided print("Wrong average:", average) average = (a + b) / 2 # right print("Right average:", average) # Output: # 153 # 18 # Wrong average: 20.0 # Right average: 15.0
CONDITIONAL STATEMENTS (IF, ELIF, ELSE) 11 programs
-
A number is even if the remainder after dividing by 2 is 0.
n = int(input("Enter a number: ")) if n % 2 == 0: print(n, "is even") else: print(n, "is odd") # Sample run (the values after each prompt are typed by the user): # Enter a number: 37 # 37 is odd -
Input two numbers and display the larger and the smaller number.
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) if a > b: print("Larger:", a, " Smaller:", b) elif b > a: print("Larger:", b, " Smaller:", a) else: print("Both numbers are equal") # Sample run (the values after each prompt are typed by the user): # Enter first number: 48 # Enter second number: 73 # Larger: 73 Smaller: 48 -
The absolute value is the number without its minus sign.
n = float(input("Enter a number: ")) if n < 0: n = -n print("Absolute value:", n) # Sample run (the values after each prompt are typed by the user): # Enter a number: -12.5 # Absolute value: 12.5 -
Check if one number divides another exactly (remainder 0).
n = int(input("Enter a number: ")) d = int(input("Check divisibility by: ")) if n % d == 0: print(n, "is divisible by", d) else: print(n, "is not divisible by", d, "- remainder", n % d) # Sample run (the values after each prompt are typed by the user): # Enter a number: 84 # Check divisibility by: 7 # 84 is divisible by 7 -
Input three numbers and display the largest and the smallest.
a = int(input("First number: ")) b = int(input("Second number: ")) c = int(input("Third number: ")) if a >= b and a >= c: largest = a elif b >= a and b >= c: largest = b else: largest = c if a <= b and a <= c: smallest = a elif b <= a and b <= c: smallest = b else: smallest = c print("Largest:", largest) print("Smallest:", smallest) # Sample run (the values after each prompt are typed by the user): # First number: 45 # Second number: 92 # Third number: 17 # Largest: 92 # Smallest: 17 -
Arrange three numbers in ascending order using only if statements.
a = int(input("First number: ")) b = int(input("Second number: ")) c = int(input("Third number: ")) if a > b: a, b = b, a # now a <= b if b > c: b, c = c, b # now c is the largest if a > b: a, b = b, a # fix the first two again print("Ascending order:", a, b, c) # Sample run (the values after each prompt are typed by the user): # First number: 30 # Second number: 10 # Third number: 20 # Ascending order: 10 20 30 -
An if-elif-else ladder: only the first true condition runs.
per = float(input("Enter percentage: ")) if per >= 90: grade = "A1" elif per >= 80: grade = "A2" elif per >= 70: grade = "B1" elif per >= 60: grade = "B2" elif per >= 33: grade = "C" else: grade = "Fail" print("Grade:", grade) # Sample run (the values after each prompt are typed by the user): # Enter percentage: 76.5 # Grade: B1 -
Divisible by 4 but not by 100, or divisible by 400.
year = int(input("Enter a year: ")) if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print(year, "is a leap year") else: print(year, "is not a leap year") # Sample run (the values after each prompt are typed by the user): # Enter a year: 1900 # 1900 is not a leap year -
Choose the operation with if-elif and handle division by zero.
a = float(input("First number: ")) op = input("Operator (+ - * /): ") b = float(input("Second number: ")) if op == "+": print("Result:", a + b) elif op == "-": print("Result:", a - b) elif op == "*": print("Result:", a * b) elif op == "/": if b == 0: print("Cannot divide by zero") else: print("Result:", a / b) else: print("Invalid operator") # Sample run (the values after each prompt are typed by the user): # First number: 15 # Operator (+ - * /): / # Second number: 4 # Result: 3.75 -
Check whether a character is an uppercase letter, lowercase letter, digit or special character.
ch = input("Enter one character: ") if ch.isupper(): print(ch, "is an uppercase letter") elif ch.islower(): print(ch, "is a lowercase letter") elif ch.isdigit(): print(ch, "is a digit") else: print(ch, "is a special character") # Sample run (the values after each prompt are typed by the user): # Enter one character: @ # @ is a special character -
Each side must be smaller than the sum of the other two.
a = float(input("Side 1: ")) b = float(input("Side 2: ")) c = float(input("Side 3: ")) if a + b > c and b + c > a and a + c > b: if a == b == c: print("Equilateral triangle") elif a == b or b == c or a == c: print("Isosceles triangle") else: print("Scalene triangle") else: print("These sides cannot make a triangle") # Sample run (the values after each prompt are typed by the user): # Side 1: 5 # Side 2: 5 # Side 3: 8 # Isosceles triangle
LOOPS (FOR, WHILE, NESTED) 21 programs
-
range(start, stop, step): stop is not included.
for k in range(7, 40, 6): print(k, end='-') print() for i in range(10, 0, -2): # counting down print(i, end=' ') # Output: # 7-13-19-25-31-37- # 10 8 6 4 2 -
Print the table of a number from 1 to 10.
n = int(input("Table of: ")) for i in range(1, 11): print(n, "x", i, "=", n * i) # Sample run (the values after each prompt are typed by the user): # Table of: 7 # 7 x 1 = 7 # 7 x 2 = 14 # 7 x 3 = 21 # 7 x 4 = 28 # 7 x 5 = 35 # 7 x 6 = 42 # 7 x 7 = 49 # 7 x 8 = 56 # 7 x 9 = 63 # 7 x 10 = 70 -
Add 1 + 2 + ... + N with a loop.
n = int(input("Enter N: ")) total = 0 for i in range(1, n + 1): total += i print("Sum of 1 to", n, "=", total) # Sample run (the values after each prompt are typed by the user): # Enter N: 10 # Sum of 1 to 10 = 55 -
n! = 1 x 2 x ... x n, and 0! = 1.
n = int(input("Enter a positive number: ")) fact = 1 for i in range(1, n + 1): fact *= i print(n, "! =", fact) # Sample run (the values after each prompt are typed by the user): # Enter a positive number: 6 # 6 ! = 720 -
Error-finding question (the paper puts this loop inside a function EvenOdd()). Fixes: closing bracket, % instead of /, and indentation of the else part.
for i in range(5): num = int(input("Enter a number: ")) if num % 2 == 0: # % (remainder), not / (division) print("Even") else: print("Odd") # indented inside else # Sample run (the values after each prompt are typed by the user): # Enter a number: 4 # Even # Enter a number: 7 # Odd # Enter a number: 10 # Even # Enter a number: 13 # Odd # Enter a number: 22 # Even -
Each term is the sum of the two terms before it: 0 1 1 2 3 5 ...
n = int(input("How many terms? ")) a, b = 0, 1 for i in range(n): print(a, end=" ") a, b = b, a + b # Sample run (the values after each prompt are typed by the user): # How many terms? 10 # 0 1 1 2 3 5 8 13 21 34 -
A prime has exactly two factors: 1 and itself. 1 is neither prime nor composite.
n = int(input("Enter a number: ")) if n <= 1: print(n, "is neither prime nor composite") else: is_prime = True for i in range(2, n): if n % i == 0: is_prime = False break if is_prime: print(n, "is a prime number") else: print(n, "is a composite number") # Sample run (the values after each prompt are typed by the user): # Enter a number: 91 # 91 is a composite number -
Error-finding question. Fixes: closing bracket, range starts at 1 (no division by zero), == instead of =, and indentation.
n = int(input("Enter a positive integer: ")) c = 0 for i in range(1, n + 1): if n % i == 0: c += 1 print(c) # Sample run (the values after each prompt are typed by the user): # Enter a positive integer: 12 # 6 -
% 10 gives the last digit and // 10 removes it.
n = int(input("Enter a number: ")) rev = 0 total = 0 while n > 0: digit = n % 10 rev = rev * 10 + digit total += digit n = n // 10 print("Reverse:", rev) print("Sum of digits:", total) # Sample run (the values after each prompt are typed by the user): # Enter a number: 4721 # Reverse: 1274 # Sum of digits: 14 -
Palindrome: same when reversed. Armstrong: sum of digits^count = number. Perfect: sum of factors (except itself) = number.
n = int(input("Enter a number: ")) # Palindrome temp, rev = n, 0 while temp > 0: rev = rev * 10 + temp % 10 temp //= 10 print("Palindrome:", rev == n) # Armstrong digits = len(str(n)) temp, total = n, 0 while temp > 0: total += (temp % 10) ** digits temp //= 10 print("Armstrong:", total == n) # Perfect factor_sum = 0 for i in range(1, n): if n % i == 0: factor_sum += i print("Perfect:", factor_sum == n) # Sample run (the values after each prompt are typed by the user): # Enter a number: 153 # Palindrome: False # Armstrong: True # Perfect: False -
GCD by repeated remainders (Euclid); LCM = a x b / GCD.
a = int(input("First number: ")) b = int(input("Second number: ")) x, y = a, b while y != 0: x, y = y, x % y gcd = x lcm = a * b // gcd print("GCD =", gcd) print("LCM =", lcm) # Sample run (the values after each prompt are typed by the user): # First number: 24 # Second number: 36 # GCD = 12 # LCM = 72 -
break leaves the loop; continue skips to the next round.
for i in range(1, 11): if i == 8: break # stop at 8 if i % 3 == 0: continue # skip 3 and 6 print(i, end=" ") # Output: # 1 2 4 5 7 -
Nested loops: the outer loop is the row, the inner loop prints the stars.
n = 5 for i in range(1, n + 1): for j in range(i): print("*", end="") print() # Output: # * # ** # *** # **** # ***** -
Each row prints 1 up to a number that gets smaller.
n = 5 for i in range(n, 0, -1): for j in range(1, i + 1): print(j, end="") print() # Output: # 12345 # 1234 # 123 # 12 # 1 -
chr(65) is "A"; add j to get the next letters.
n = 5 for i in range(1, n + 1): for j in range(i): print(chr(65 + j), end="") print() # Output: # A # AB # ABC # ABCD # ABCDE -
Input x and n and add the powers of x.
x = int(input("Enter x: ")) n = int(input("Enter n: ")) total = 0 for i in range(n + 1): total += x ** i print("Sum =", total) # Sample run (the values after each prompt are typed by the user): # Enter x: 2 # Enter n: 5 # Sum = 63 -
The sign changes every term: (-1)^i gives + - + - ...
x = int(input("Enter x: ")) n = int(input("Enter n: ")) total = 0 for i in range(n + 1): total += (-1) ** i * x ** i print("Sum =", total) # Sample run (the values after each prompt are typed by the user): # Enter x: 2 # Enter n: 5 # Sum = -21 -
Each term is x to the power i, divided by i.
x = float(input("Enter x: ")) n = int(input("Enter n: ")) total = 0 for i in range(1, n + 1): total += x ** i / i print("Sum =", round(total, 4)) # Sample run (the values after each prompt are typed by the user): # Enter x: 2 # Enter n: 4 # Sum = 10.6667 -
Keep a running factorial so each term is x^i / i!.
x = float(input("Enter x: ")) n = int(input("Enter n: ")) total = 0 fact = 1 for i in range(1, n + 1): fact *= i # i! total += x ** i / fact print("Sum =", round(total, 4)) # Sample run (the values after each prompt are typed by the user): # Enter x: 2 # Enter n: 4 # Sum = 6.0 -
Trace the loop step by step: new % 2 is 0 (False) when new is even. (In the paper this loop is inside a function.)
given = 123456 new = 0 while given: # runs while given is not 0 if new % 2: # new is odd new += given % 10 else: # new is even new += given % 5 print(new, end='-') given //= 10 # Output: # 1-6-10-13-15-16- -
random.randint picks a secret number; a while loop gives hints until it is guessed.
import random secret = random.randint(1, 20) tries = 0 while True: guess = int(input("Guess (1-20): ")) tries += 1 if guess < secret: print("Too small") elif guess > secret: print("Too big") else: print("Correct! You took", tries, "tries") break # One possible output (yours may differ): # Guess (1-20): 10 # Too small # Guess (1-20): 15 # Too big # Guess (1-20): 12 # Too big # Guess (1-20): 13 # Too big # Guess (1-20): 14 # Too big # Guess (1-20): 11 # Correct! You took 6 tries
STRINGS 14 programs
-
Positions start at 0; negative positions count from the end.
s = "PYTHON" print(s[0], s[3], s[-1]) for ch in s: print(ch, end=" ") print() for i in range(len(s)): print(i, s[i]) # Output: # P H N # P Y T H O N # 0 P # 1 Y # 2 T # 3 H # 4 O # 5 N -
Concatenation, repetition, membership and slicing [start:stop:step].
a = "Computer" b = "Science" print(a + " " + b) # concatenation print("Hi! " * 3) # repetition print("put" in a) # membership print(a[0:4]) # slicing: positions 0 to 3 print(a[::-1]) # reverse # Output: # Computer Science # Hi! Hi! Hi! # True # Comp # retupmoC -
These methods return a new string; the original is not changed.
s = "the Truth" print(s.upper()) print(s.lower()) print(s.capitalize()) # only the first letter capital print(s.title()) # each word capital # Output: # THE TRUTH # the truth # The truth # The Truth -
They return True or False.
print("Python".isalpha()) print("2024".isdigit()) print("Class12".isalnum()) print(" ".isspace()) print("Hello".isupper(), "hello".islower()) username = "admin_ravi" print(username.startswith("admin")) print("notes.txt".endswith(".txt")) # Output: # True # True # True # True # False True # True # True -
find() gives -1 if not found; index() gives an error instead.
game = 'Olympic2024' print(game.index('c')) s = "an apple. a toy." print(s.find('a', 2)) # search from position 2 text = "Python Programming" print(text.find("z")) # -1: not found print(text.replace("o", "0")) print("This is his book".count("is")) print("PYTHONPROGRAM".replace('PY', '#')) # Output: # 6 # 3 # -1 # Pyth0n Pr0gramming # 3 # #THONPROGRAM -
split() breaks a string into a list; join() joins a list into a string.
print("Paralympic Games".split("m")) print("programming is amazing".split("m")) print('War and Peace by Leo Tolstoy'.partition("by")) l = "Python is fun".split() print("-".join([l[0].upper(), l[1], l[2].capitalize()])) print(" hello ".strip(), "|", " hello".lstrip(), "|", "hello ".rstrip()) # Output: # ['Paraly', 'pic Ga', 'es'] # ['progra', '', 'ing is a', 'azing'] # ('War and Peace ', 'by', ' Leo Tolstoy') # PYTHON-is-Fun # hello | hello | hello -
With a negative step the slice moves right to left, starting at the first number.
myStr = "MISSISSIPPI" print(myStr[:4] + "#" + myStr[-5:]) print("PythonProgram"[-1:2:-2]) pride = "#G20 Presidency" print(pride[-2:2:-2]) s = "Soft Skills" print(s[-3::-3]) text = "Drone Expo" print(text[-2::-4]) # Output: # MISS#SIPPI # mroPo # ceieP0 # lSf # peD -
Count and display the vowels, consonants, uppercase and lowercase characters in a string.
s = input("Enter a string: ") vowels = consonants = upper = lower = 0 for ch in s: 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) # Sample run (the values after each prompt are typed by the user): # Enter a string: Hello World from CSIP12 # Vowels: 5 # Consonants: 13 # Uppercase: 6 # Lowercase: 12 -
Check if a string is a palindrome, then change uppercase to lowercase and lowercase to uppercase.
s = input("Enter a string: ") if s.lower() == s.lower()[::-1]: print(s, "is a palindrome") else: print(s, "is not a palindrome") result = "" for ch in s: if ch.isupper(): result += ch.lower() elif ch.islower(): result += ch.upper() else: result += ch print("Case converted:", result) # Sample run (the values after each prompt are typed by the user): # Enter a string: Madam # Madam is a palindrome # Case converted: mADAM -
split() gives the words; len() of the list counts them.
s = input("Enter a sentence: ") words = s.split() print("Number of words:", len(words)) longest = "" for w in words: if len(w) > len(longest): longest = w print("Longest word:", longest) # Sample run (the values after each prompt are typed by the user): # Enter a sentence: Practice makes a programmer perfect # Number of words: 5 # Longest word: programmer -
Palindrome words print their letters with *, others with #.
S = "Racecar Car Radar" L = S.split() for W in L: x = W.upper() if x == x[::-1]: for I in x: print(I, end="*") else: for I in W: print(I, end="#") print() # Output: # R*A*C*E*C*A*R* # C#a#r# # R*A*D*A*R* -
Digits become digit+1, a capital letter is replaced by the next character, anything else becomes *.
Text1 = "IND-23" Text2 = "" I = 0 while I < len(Text1): if Text1[I] >= "0" and Text1[I] <= "9": Val = int(Text1[I]) Val = Val + 1 Text2 = Text2 + str(Val) elif Text1[I] >= "A" and Text1[I] <= "Z": Text2 = Text2 + (Text1[I + 1]) else: Text2 = Text2 + "*" I += 1 print(Text2) # Output: # ND-*34 -
Uppercase letters become lowercase, digits are doubled, the rest become #.
code = "gLaD5" result = [] i = 0 while i < len(code): if code[i].isupper(): result.append(code[i].lower()) elif code[i].isdigit(): result.append(int(code[i]) * 2) else: result.append("#") i += 1 print(result) # Output: # ['#', 'l', '#', 'd', 10] -
Build a new string with only the characters that are not vowels.
s = input("Enter a string: ") result = "" for ch in s: if ch.lower() not in "aeiou": result += ch print("Without vowels:", result) # Sample run (the values after each prompt are typed by the user): # Enter a string: Education is important # Without vowels: dctn s mprtnt
LISTS 15 programs
-
A list keeps items in order; it can be changed (mutable).
marks = [78, 92, 85, 64, 90] print(marks) print("First:", marks[0], " Last:", marks[-1]) marks[1] = 95 # lists can be changed for m in marks: print(m, end=" ") print() print("Length:", len(marks)) # Output: # [78, 92, 85, 64, 90] # First: 78 Last: 90 # 78 95 85 64 90 # Length: 5 -
Concatenation, repetition, membership and slicing work like strings.
a = [1, 2, 3] b = [4, 5] print(a + b) print(a * 2) print(3 in a, 7 in a) L = [10, 20, 30, 40, 50, 60] print(L[1:4], L[::2], L[::-1]) # Output: # [1, 2, 3, 4, 5] # [1, 2, 3, 1, 2, 3] # True False # [20, 30, 40] [10, 30, 50] [60, 50, 40, 30, 20, 10] -
Methods that add and remove items.
L1 = [10, 20, 25, 30] L1.insert(1, 15) # at position 1 print(L1) L1.append(40) # at the end L1.extend([50, 60]) # many at the end print(L1) L1.remove(25) # by value print(L1.pop()) # removes and returns the last item print(L1.pop(0)) # removes position 0 print(L1) # Output: # [10, 15, 20, 25, 30] # [10, 15, 20, 25, 30, 40, 50, 60] # 60 # 10 # [15, 20, 30, 40, 50] -
Find the largest, smallest and average of the numbers in a list.
nums = [45, 12, 78, 34, 89, 23] print("Maximum:", max(nums)) print("Minimum:", min(nums)) print("Mean:", sum(nums) / len(nums)) # Output: # Maximum: 89 # Minimum: 12 # Mean: 46.833333333333336 -
sort() changes the list; sorted() returns a new list and keeps the original.
L = [40, 10, 30, 20] L1 = sorted(L) # new list, L unchanged print(L, L1) L.sort(reverse=True) # descending, changes L print(L) L.reverse() print(L) # Output: # [40, 10, 30, 20] [10, 20, 30, 40] # [40, 30, 20, 10] # [10, 20, 30, 40] -
Trace each statement in order.
P = [3, 5, 7, 4] P.insert(2, 3) P.extend([10, 6]) print(P) print(P.index(7)) print(P[::2]) # Output: # [3, 5, 3, 7, 4, 10, 6] # 3 # [3, 3, 4, 6] -
Input a list and search for a given element.
L = eval(input("Enter a list, e.g. [4, 8, 2]: ")) x = int(input("Element to search: ")) found = False for i in range(len(L)): if L[i] == x: print(x, "found at position", i) found = True break if not found: print(x, "is not in the list") # Sample run (the values after each prompt are typed by the user): # Enter a list, e.g. [4, 8, 2]: [12, 45, 7, 33, 90] # Element to search: 33 # 33 found at position 3 -
count() tells how many times a value appears.
L = [2, 7, 9, 9, 2, 5, 9] done = [] for x in L: if x not in done: print(x, "appears", L.count(x), "times") done.append(x) print("The largest appears", L.count(max(L)), "times") # Output: # 2 appears 2 times # 7 appears 1 times # 9 appears 3 times # 5 appears 1 times # The largest appears 3 times -
Swap L[0] with L[1], L[2] with L[3], and so on.
L = eval(input("Enter a list: ")) for i in range(0, len(L) - 1, 2): L[i], L[i + 1] = L[i + 1], L[i] print("After swapping:", L) # Sample run (the values after each prompt are typed by the user): # Enter a list: [1, 2, 3, 4, 5, 6, 7] # After swapping: [2, 1, 4, 3, 6, 5, 7] -
Error-finding question. Fixes: matching quotes, range(L-1, -1, -1), the colon, and print in lowercase.
words = ["Class Test", "Term Exams", "Pre-board Exam", "Board Exam"] L = len(words) for i in range(L - 1, -1, -1): print(words[i], end=" ") # Output: # Board Exam Pre-board Exam Term Exams Class Test -
A list inside a list: L[i][j] is row i, column j.
students = [["Riya", 88], ["Aman", 75], ["Sara", 93]] print(students[1]) # ['Aman', 75] print(students[2][0]) # Sara for s in students: print(s[0], "scored", s[1]) # Output: # ['Aman', 75] # Sara # Riya scored 88 # Aman scored 75 # Sara scored 93 -
Split a string into a list, then slice it.
event = "G20 Presidency@2023" L = event.split(' ') print(L[::-2]) p = list("Session 2024-25") print(p[10:20:]) L = ["India", "Incredible", "Bharat"] print(L[1][0] + L[2][-1]) # Output: # ['Presidency@2023'] # ['2', '4', '-', '2', '5'] # It -
Uppercase letters reverse the list, new characters are added, repeated ones remove the last item. (In the paper this loop is inside a function.)
given = "Gold-24Medals" new = [] for ch in given[1:-1]: # leave out the first and last character if ch.isupper(): new.reverse() elif ch not in new: new.append(ch) elif ch in new: new.pop() print(new) # Output: # ['4', '2', '-', 'd', 'l', 'o'] -
Find the second largest without sorting.
L = [45, 78, 12, 90, 67, 90] first = second = None for x in L: if first is None or x > first: second = first first = x elif x != first and (second is None or x > second): second = x print("Largest:", first, " Second largest:", second) # Output: # Largest: 90 Second largest: 78 -
Keep only the first copy of each value, in the same order.
L = [3, 5, 3, 7, 5, 9, 3] unique = [] for x in L: if x not in unique: unique.append(x) print(unique) # Output: # [3, 5, 7, 9]
TUPLES 8 programs
-
A tuple is like a list but cannot be changed (immutable). A one-item tuple needs a comma.
t = (10, 20, 30, 40) print(t[0], t[-1], t[1:3]) single = (5,) # comma makes it a tuple print(type(single), type((5))) t2 = tuple("tuple") # from a string print(t2) # Output: # 10 40 (20, 30) # <class 'tuple'> <class 'int'> # ('t', 'u', 'p', 'l', 'e') -
Changing an item gives TypeError, but you can build a new tuple.
t = (10, 20, 30) # t[0] = 5 -> TypeError: 'tuple' object does not support item assignment t = (5,) + t[1:] # make a new tuple instead print(t) # t + [4, 5] -> TypeError: a tuple cannot be joined with a list print(t + (4, 5)) # tuple + tuple is fine # Output: # (5, 20, 30) # (5, 20, 30, 4, 5) -
Built-in functions and methods that work on tuples.
t = (4, 9, 2, 9, 7, 9) print(len(t), t.count(9), t.index(2)) print(min(t), max(t), sum(t)) print(sorted(t)) # gives a list # Output: # 6 3 2 # 2 9 40 # [2, 4, 7, 9, 9, 9] -
Unpack a tuple into variables in one line.
student = ("Riya", 17, ("Maths", "CS")) name, age, subjects = student # tuple assignment print(name, age) print(subjects[1]) print(student[2][0]) # nested tuple # Output: # Riya 17 # CS # Maths -
t += ... makes a NEW tuple; other names still point to the old one.
t = tuple('tuple') t2 = t[2], t += t2 print(t) tuple1 = (1, 2, 3) tuple2 = tuple1 tuple1 += (4,) print(tuple1 == tuple2) # Output: # ('t', 'u', 'p', 'l', 'e', 'p') # False -
Find the largest and smallest number in a tuple, and the mean.
t = (56, 23, 89, 12, 45) print("Largest:", max(t)) print("Smallest:", min(t)) print("Mean:", sum(t) / len(t)) # Output: # Largest: 89 # Smallest: 12 # Mean: 45.0 -
Linear search for an element and count its frequency.
t = (5, 8, 3, 8, 1, 8) x = int(input("Element to search: ")) if x in t: print(x, "is at position", t.index(x), "and appears", t.count(x), "times") else: print(x, "not found") # Sample run (the values after each prompt are typed by the user): # Element to search: 8 # 8 is at position 1 and appears 3 times -
Change a tuple by turning it into a list, editing, then back into a tuple.
subject = ("English", "Maths", "Physics", "CS") subject_list = list(subject) subject_list.pop() # delete the last element print(subject_list) subject = tuple(subject_list) print(subject) # Output: # ['English', 'Maths', 'Physics'] # ('English', 'Maths', 'Physics')
DICTIONARIES 12 programs
-
A dictionary stores key: value pairs. Use the key to get or change a value.
student = {"name": "Riya", "class": 11, "marks": 88} print(student["name"]) student["marks"] = 92 # change student["city"] = "Delhi" # add print(student) print(len(student)) # Output: # Riya # {'name': 'Riya', 'class': 11, 'marks': 92, 'city': 'Delhi'} # 4 -
A for loop over a dictionary gives its keys.
D = {'S01': 95, 'S02': 96, 'S03': 88} for I in D: print(I, end='#') print() print(list(D.keys())) print(list(D.values())) for k, v in D.items(): print(k, "->", v) # Output: # S01#S02#S03# # ['S01', 'S02', 'S03'] # [95, 96, 88] # S01 -> 95 # S02 -> 96 # S03 -> 88 -
in checks keys only; get() returns a default instead of an error.
my_dict = {"name": "Alicia", "age": 27, "city": "DELHI"} print(my_dict.get("profession", "Not Specified")) print(my_dict.get("age")) Dl = {"Pen": 12, "Pencil": 6, "Scale": 5, "InkPen": 20} print(12 in Dl) # False: 12 is a value, not a key print("Pen" in Dl) print(12 in Dl.values()) # Output: # Not Specified # 27 # False # True # True -
pop(key) returns the value; del removes; popitem() removes the last pair; clear() empties.
Students = {"ANITA": 90, "NISHA": 76, "ASHA": 92, "RAJ": 81} Students.pop("NISHA") print(Students) del Students["ASHA"] print(Students) print(Students.popitem()) Students.clear() print(Students) # Output: # {'ANITA': 90, 'ASHA': 92, 'RAJ': 81} # {'ANITA': 90, 'RAJ': 81} # ('RAJ', 81) # {} -
More dictionary methods from the syllabus.
D1 = {"a": 1, "b": 2} D2 = {"b": 20, "c": 30} D1.update(D2) # add/replace from D2 print(D1) print(D1.setdefault("RNo", 12)) # adds RNo: 12 only if it is missing print(D1.setdefault("a", 99)) # key exists: returns its value print(D1) marks = dict.fromkeys(["Riya", "Aman"], 0) print(marks) backup = D1.copy() print(backup == D1, backup is D1) print(tuple(D2.keys())) # Output: # {'a': 1, 'b': 20, 'c': 30} # 12 # 1 # {'a': 1, 'b': 20, 'c': 30, 'RNo': 12} # {'Riya': 0, 'Aman': 0} # True False # ('b', 'c') -
Count how many times each character appears in a string.
s = input("Enter a string: ") freq = {} for ch in s: if ch in freq: freq[ch] += 1 else: freq[ch] = 1 for ch in freq: print(repr(ch), ":", freq[ch]) # Sample run (the values after each prompt are typed by the user): # Enter a string: banana bread # 'b' : 2 # 'a' : 4 # 'n' : 2 # ' ' : 1 # 'r' : 1 # 'e' : 1 # 'd' : 1 -
Create a dictionary of employees and their salaries and access them.
emp = {} n = int(input("Number of employees: ")) for i in range(n): name = input("Name: ") salary = int(input("Salary: ")) emp[name] = salary print(emp) name = input("Whose salary? ") print(name, "earns", emp.get(name, "- not found")) # Sample run (the values after each prompt are typed by the user): # Number of employees: 3 # Name: Kiran # Salary: 45000 # Name: Dev # Salary: 52000 # Name: Meera # Salary: 61000 # {'Kiran': 45000, 'Dev': 52000, 'Meera': 61000} # Whose salary? Dev # Dev earns 52000 -
A dictionary with roll number, name and marks of n students; display the names of those scoring above 75.
n = int(input("Number of students: ")) result = {} for i in range(n): roll = int(input("Roll number: ")) name = input("Name: ") marks = int(input("Marks: ")) result[roll] = [name, marks] print("Students with marks above 75:") for roll in result: if result[roll][1] > 75: print(result[roll][0]) # Sample run (the values after each prompt are typed by the user): # Number of students: 3 # Roll number: 1 # Name: Riya # Marks: 88 # Roll number: 2 # Name: Aman # Marks: 72 # Roll number: 3 # Name: Sara # Marks: 91 # Students with marks above 75: # Riya # Sara -
Store only the words whose length is a multiple of 4.
LS = ["HIMALAYA", "NILGIRI", "ALASKA", "ALPS"] D = {} for S in LS: if len(S) % 4 == 0: D[S] = len(S) for K in D: print(K, D[K], sep="#") # Output: # HIMALAYA#8 # ALPS#4 -
L.pop() removes from the end of the list each time.
S = "LOST" L = [10, 21, 33, 4] D = {} for I in range(len(S)): if I % 2 == 0: D[L.pop()] = S[I] else: D[L.pop()] = I + 3 for K, V in D.items(): print(K, V, sep="*") # Output: # 4*L # 33*4 # 21*S # 10*6 -
Each value is a tuple of two salaries; keep names whose average is above 80000.
emp = {"Arv": (85000, 90000), "Ria": (78000, 88000), "Jay": (72000, 80000), "Tia": (80000, 70000)} selected = [] for name in emp: salary = emp[name] average = (salary[0] + salary[1]) / 2 if average > 80000: selected.append(name) print(selected) # Output: # ['Arv', 'Ria'] -
max(D, key=D.get) gives the key with the largest value; sorted() sorts the keys.
marks = {"Riya": 88, "Aman": 75, "Sara": 93, "Kabir": 67} topper = max(marks, key=marks.get) print("Topper:", topper, marks[topper]) print("Names in order:", sorted(marks)) print("Lowest marks:", min(marks.values())) # Output: # Topper: Sara 93 # Names in order: ['Aman', 'Kabir', 'Riya', 'Sara'] # Lowest marks: 67
PYTHON MODULES (MATH, RANDOM, STATISTICS) 8 programs
-
import math, then use math.name.
import math print(math.pi, math.e) print(math.sqrt(81)) print(math.pow(2, 5)) print(math.ceil(4.2), math.floor(4.8)) print(math.fabs(-7.5)) r = 7 print("Area of circle:", round(math.pi * r * r, 2)) # Output: # 3.141592653589793 2.718281828459045 # 9.0 # 32.0 # 5 4 # 7.5 # Area of circle: 153.94 -
from math import sqrt lets you write sqrt() without math.
from math import sqrt, pi from statistics import mean print(sqrt(144)) print(round(2 * pi * 5, 2)) print(mean([10, 20, 30])) # Output: # 12.0 # 31.42 # 20 -
The angle must be in radians: math.radians() converts degrees.
import math angle = math.radians(30) print(round(math.sin(angle), 2)) print(round(math.cos(math.radians(60)), 2)) print(round(math.tan(math.radians(45)), 2)) # Output: # 0.5 # 0.5 # 1.0 -
mode gives the most common value.
import statistics studentAge = [15, 16, 16, 17, 16, 15, 18] print(statistics.mean(studentAge)) print(statistics.median(studentAge)) print(statistics.mode(studentAge)) # Output: # 16.142857142857142 # 16 # 16 -
random() gives 0 to <1; randint(a, b) includes b; randrange(a, b) does not include b.
import random print(random.random()) print(random.randint(1, 6)) # 1 to 6 print(random.randrange(1, 6)) # 1 to 5 print(random.randrange(0, 20, 5)) # 0, 5, 10 or 15 # One possible output (yours may differ): # 0.32383276483316237 # 2 # 4 # 0 -
randrange(K) gives 0 to K-1. Work out which values each round can give.
import random Signal = ['RED', 'YELLOW', 'GREEN'] for K in range(2, 0, -1): R = random.randrange(K) # K=2: 0 or 1, then K=1: only 0 print(Signal[R], end='#') print() a = [1, 2, 3, 4, 5, 6] for i in range(4): j = random.randrange(i, 5) # i to 4 print(a[j], end='-') # One possible output (yours may differ): # YELLOW#RED# # 4-2-3-4- -
randint(a, b) includes both a and b.
import random L = [10, 30, 50, 70] Lower = random.randint(2, 2) # always 2 Upper = random.randint(2, 3) # 2 or 3 for K in range(Lower, Upper + 1): print(L[K], end="@") print() games = {0: "Chess", 1: "Scrabble", 2: "Sudoku", 3: "Tic-Tac-Toe", 4: "Puzzle"} start_key = random.randint(1, 2) end_key = random.randrange(3, 4) # always 3 for k in range(start_key, end_key + 1): print(games[k], end="@@") # One possible output (yours may differ): # 50@ # Sudoku@@Tic-Tac-Toe@@ -
Make a 6-digit one-time password from random digits.
import random otp = "" for i in range(6): otp += str(random.randint(0, 9)) print("Your OTP is", otp) # One possible output (yours may differ): # Your OTP is 526018