Important IP Programs
Master your practical exams with our curated list of essential Python programs for Class 11 Informatics Practices. 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 11 programs
-
print() shows text on the screen. Text goes inside quotes.
print("Hello, World!") print("Welcome to Class 11 Informatics Practices") # Output: # Hello, World! # Welcome to Class 11 Informatics Practices -
A variable stores a value. type() tells the kind of value.
name = "Riya" # str (text) age = 16 # int (whole number) height = 5.4 # float (decimal number) passed = True # bool (True / False) print(name, age, height, passed) print(type(name), type(age), type(height), type(passed)) # Output: # Riya 16 5.4 True # <class 'str'> <class 'int'> <class 'float'> <class 'bool'> -
input() always gives text. Use int() or float() to get a number.
name = input("What is your name? ") age = int(input("How old are you? ")) print("Hello", name) print("Next year you will be", age + 1) # Sample run (the values after each prompt are typed by the user): # What is your name? Aman # How old are you? 16 # Hello Aman # Next year you will be 17 -
+ - * / // % ** with two numbers.
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 (decimal answer) print("a // b =", a // b) # floor division (whole number) print("a % b =", a % b) # remainder print("a ** b =", a ** b) # power: 17 to the power 5 # Output: # a + b = 22 # a - b = 12 # a * b = 85 # a / b = 3.4 # a // b = 3 # a % b = 2 # a ** b = 1419857 -
sep= changes what goes between values; end= changes what comes at the end.
print("2026", "10", "14", sep="-") print("Loading", end="...") print("done") print("A", "B", "C") # default sep is a space # Output: # 2026-10-14 # Loading...done # A B C -
Change a value from one type to another with int(), float() and str().
a = "25" b = "4.5" print(int(a) + 10) # text -> whole number print(float(b) * 2) # text -> decimal number print(str(100) + " marks")# number -> text x = 5 + 2.5 # Python changes 5 to 5.0 by itself print(x, type(x)) # Output: # 35 # 9.0 # 100 marks # 7.5 <class 'float'> -
Relational operators compare values; and / or / not join conditions.
a = 10 b = 20 print(a > b, a < b, a == b, a != b) age = 17 print(age >= 13 and age <= 19) # teenager? print(age < 18 or age > 60) print(not age > 18) # Output: # False True False True # True # True # True -
x += 5 is the short form of x = x + 5.
x = 10 x += 5 # x = x + 5 print(x) x -= 3 # x = x - 3 print(x) x *= 2 # x = x * 2 print(x) x //= 4 # x = x // 4 print(x) # Output: # 15 # 12 # 24 # 6 -
Python does ** first, then * / // %, then + -. Brackets change the order.
print(2 + 3 * 4) # 3*4 first print((2 + 3) * 4) # brackets first print(2 ** 3 ** 2) # right to left: 3**2 = 9, then 2**9 print(20 - 10 / 5 * 2) print(17 % 5 + 2 ** 2) # Output: # 14 # 20 # 512 # 16.0 # 6 -
A list can be changed in place (mutable); a string cannot (immutable).
marks = [70, 80, 90] marks[0] = 75 # allowed: lists are mutable print(marks) name = "riya" # name[0] = "R" # not allowed: TypeError, strings are immutable name = "R" + name[1:] # make a new string instead print(name) # Output: # [75, 80, 90] # Riya -
Syntax error: wrong grammar. Runtime error: crashes while running. Logical error: wrong answer.
# Syntax error (will not run): print("Hi" <- missing ) # Runtime error (crashes): print(10 / 0) <- ZeroDivisionError # Logical error (runs, but the answer is wrong): a = 40 b = 60 avg = a + b / 2 # wrong: only b is divided by 2 print("Wrong average:", avg) avg = (a + b) / 2 # correct print("Correct average:", avg) # Output: # Wrong average: 70.0 # Correct average: 50.0
EVERYDAY CALCULATIONS 10 programs
-
Find the average of marks in 5 subjects and the grade for it.
m1 = float(input("Marks in English: ")) m2 = float(input("Marks in Maths: ")) m3 = float(input("Marks in IP: ")) m4 = float(input("Marks in Economics: ")) m5 = float(input("Marks in Accountancy: ")) average = (m1 + m2 + m3 + m4 + m5) / 5 print("Average:", average) if average >= 90: print("Grade: A") elif average >= 75: print("Grade: B") elif average >= 60: print("Grade: C") elif average >= 33: print("Grade: D") else: print("Grade: E (needs improvement)") # Sample run (the values after each prompt are typed by the user): # Marks in English: 78 # Marks in Maths: 85 # Marks in IP: 92 # Marks in Economics: 70 # Marks in Accountancy: 88 # Average: 82.6 # Grade: B -
Find the sale price of an item from its cost and discount %.
cost = float(input("Cost of the item: ")) discount = float(input("Discount %: ")) discount_amount = cost * discount / 100 sale_price = cost - discount_amount print("Discount amount:", discount_amount) print("Sale price:", sale_price) # Sample run (the values after each prompt are typed by the user): # Cost of the item: 1200 # Discount %: 15 # Discount amount: 180.0 # Sale price: 1020.0 -
Rectangle: area = l x b, perimeter = 2(l + b). Square: area = s x s, perimeter = 4s.
l = float(input("Length of rectangle: ")) b = float(input("Breadth of rectangle: ")) print("Rectangle area:", l * b, " perimeter:", 2 * (l + b)) s = float(input("Side of square: ")) print("Square area:", s * s, " perimeter:", 4 * s) # Sample run (the values after each prompt are typed by the user): # Length of rectangle: 8 # Breadth of rectangle: 5 # Rectangle area: 40.0 perimeter: 26.0 # Side of square: 6 # Square area: 36.0 perimeter: 24.0 -
Circumference = 2 x pi x r, area = pi x r x r.
r = float(input("Radius of circle: ")) pi = 3.14 print("Circumference:", round(2 * pi * r, 2)) print("Area:", round(pi * r * r, 2)) # Sample run (the values after each prompt are typed by the user): # Radius of circle: 7 # Circumference: 43.96 # Area: 153.86 -
Perimeter = a + b + c. Area by Heron's formula: s = half the perimeter, area = square root of s(s-a)(s-b)(s-c).
a = float(input("Side a: ")) b = float(input("Side b: ")) c = float(input("Side c: ")) perimeter = a + b + c s = perimeter / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 # ** 0.5 is square root print("Perimeter:", perimeter) print("Area:", round(area, 2)) # Sample run (the values after each prompt are typed by the user): # Side a: 3 # Side b: 4 # Side c: 5 # Perimeter: 12.0 # Area: 6.0 -
SI = P x R x T / 100. Amount with CI = P x (1 + R/100) ** T, and CI = Amount - P.
p = float(input("Principal: ")) r = float(input("Rate % per year: ")) t = float(input("Time in years: ")) si = p * r * t / 100 amount = p * (1 + r / 100) ** t ci = amount - p print("Simple Interest:", round(si, 2)) print("Compound Interest:", round(ci, 2)) # Sample run (the values after each prompt are typed by the user): # Principal: 10000 # Rate % per year: 8 # Time in years: 3 # Simple Interest: 2400.0 # Compound Interest: 2597.12 -
If selling price is more than cost price it is a profit, if less it is a loss.
cp = float(input("Cost price: ")) sp = float(input("Selling price: ")) if sp > cp: profit = sp - cp print("Profit:", profit, " Profit %:", round(profit / cp * 100, 2)) elif cp > sp: loss = cp - sp print("Loss:", loss, " Loss %:", round(loss / cp * 100, 2)) else: print("No profit, no loss") # Sample run (the values after each prompt are typed by the user): # Cost price: 500 # Selling price: 575 # Profit: 75.0 Profit %: 15.0 -
EMI = P x R x (1+R)^N / ((1+R)^N - 1), where R is the monthly rate and N the number of months.
p = float(input("Loan amount: ")) annual_rate = float(input("Interest rate % per year: ")) years = int(input("Period in years: ")) r = annual_rate / 12 / 100 # monthly rate n = years * 12 # number of months emi = p * r * (1 + r) ** n / ((1 + r) ** n - 1) print("Monthly EMI:", round(emi, 2)) print("Total payment:", round(emi * n, 2)) # Sample run (the values after each prompt are typed by the user): # Loan amount: 500000 # Interest rate % per year: 9 # Period in years: 5 # Monthly EMI: 10379.18 # Total payment: 622750.66 -
GST is added to the price. With CGST and SGST, each is half of the GST rate.
price = float(input("Price of the item: ")) gst_rate = float(input("GST rate % (5, 12, 18 or 28): ")) gst = price * gst_rate / 100 print("CGST:", gst / 2) print("SGST:", gst / 2) print("Total GST:", gst) print("Bill amount:", price + gst) # Sample run (the values after each prompt are typed by the user): # Price of the item: 2000 # GST rate % (5, 12, 18 or 28): 18 # CGST: 180.0 # SGST: 180.0 # Total GST: 360.0 # Bill amount: 2360.0 -
Different rates for different units: an if-elif ladder works out each slab.
units = int(input("Units used: ")) if units <= 100: bill = units * 3 elif units <= 200: bill = 100 * 3 + (units - 100) * 5 else: bill = 100 * 3 + 100 * 5 + (units - 200) * 7 print("Bill amount:", bill) # Sample run (the values after each prompt are typed by the user): # Units used: 260 # Bill amount: 1220
CONDITIONAL STATEMENTS (IF, ELIF, ELSE) 6 programs
-
If the remainder after dividing by 2 is 0, the number is even.
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: 27 # 27 is odd -
Three choices need if, elif and else.
n = float(input("Enter a number: ")) if n > 0: print("Positive") elif n < 0: print("Negative") else: print("Zero") # Sample run (the values after each prompt are typed by the user): # Enter a number: -8 # Negative -
A person can vote at 18 years or more.
age = int(input("Enter your age: ")) if age >= 18: print("You can vote") else: print("You can vote after", 18 - age, "year(s)") # Sample run (the values after each prompt are typed by the user): # Enter your age: 15 # You can vote after 3 year(s) -
Compare with and: the largest is bigger than or equal to both others.
a = int(input("First number: ")) b = int(input("Second number: ")) c = int(input("Third number: ")) if a >= b and a >= c: print("Largest:", a) elif b >= a and b >= c: print("Largest:", b) else: print("Largest:", c) # Sample run (the values after each prompt are typed by the user): # First number: 34 # Second number: 81 # Third number: 57 # Largest: 81 -
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: 2028 # 2028 is a leap year -
Pick the operation with if-elif.
a = float(input("First number: ")) op = input("Operation (+ - * /): ") b = float(input("Second number: ")) if op == "+": print(a + b) elif op == "-": print(a - b) elif op == "*": print(a * b) elif op == "/": if b != 0: print(a / b) else: print("Cannot divide by zero") else: print("Unknown operation") # Sample run (the values after each prompt are typed by the user): # First number: 45 # Operation (+ - * /): * # Second number: 3 # 135.0
LOOPS (FOR AND WHILE) 11 programs
-
range(5) gives 0 to 4; range(1, 6) gives 1 to 5; range(2, 11, 2) jumps by 2.
for i in range(5): print(i, end=" ") print() for i in range(1, 6): print(i, end=" ") print() for i in range(2, 11, 2): print(i, end=" ") # Output: # 0 1 2 3 4 # 1 2 3 4 5 # 2 4 6 8 10 -
A while loop repeats as long as its condition is True.
count = 5 while count > 0: print(count, end=" ") count -= 1 # without this the loop never ends print("Go!") # Output: # 5 4 3 2 1 Go! -
Print the first n multiples of a given number.
num = int(input("Number: ")) n = int(input("How many multiples? ")) for i in range(1, n + 1): print(num * i, end=" ") # Sample run (the values after each prompt are typed by the user): # Number: 7 # How many multiples? 10 # 7 14 21 28 35 42 49 56 63 70 -
Print the table of a number.
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: 9 # 9 x 1 = 9 # 9 x 2 = 18 # 9 x 3 = 27 # 9 x 4 = 36 # 9 x 5 = 45 # 9 x 6 = 54 # 9 x 7 = 63 # 9 x 8 = 72 # 9 x 9 = 81 # 9 x 10 = 90 -
Keep adding each number to a total.
n = int(input("Enter n: ")) total = 0 for i in range(1, n + 1): total = total + i print("Sum:", total) # Sample run (the values after each prompt are typed by the user): # Enter n: 20 # Sum: 210 -
Add 1x1 + 2x2 + ... + 100x100.
total = 0 for i in range(1, 101): total += i * i print("Sum of squares of 1 to 100:", total) # Output: # Sum of squares of 1 to 100: 338350 -
5! = 1 x 2 x 3 x 4 x 5.
n = int(input("Enter a number: ")) fact = 1 for i in range(1, n + 1): fact = fact * i print("Factorial of", n, "is", fact) # Sample run (the values after each prompt are typed by the user): # Enter a number: 5 # Factorial of 5 is 120 -
break stops the loop; continue skips just this round.
for i in range(1, 11): if i == 7: break # stop when i is 7 if i % 2 == 0: continue # skip even numbers print(i, end=" ") # Output: # 1 3 5 -
Read n marks one by one and add them up.
n = int(input("How many subjects? ")) total = 0 for i in range(n): m = float(input("Marks: ")) total += m print("Total:", total) print("Average:", total / n) # Sample run (the values after each prompt are typed by the user): # How many subjects? 4 # Marks: 80 # Marks: 65 # Marks: 90 # Marks: 75 # Total: 310.0 # Average: 77.5 -
The outer loop makes rows; the inner loop prints the stars of one row.
for i in range(1, 6): for j in range(i): print("*", end=" ") print() # Output: # * # * * # * * * # * * * * # * * * * * -
% 10 gives the last digit and // 10 removes it.
n = int(input("Enter a number: ")) total = 0 while n > 0: total += n % 10 n = n // 10 print("Sum of digits:", total) # Sample run (the values after each prompt are typed by the user): # Enter a number: 5729 # Sum of digits: 23
STRINGS 5 programs
-
Strings can be joined with +, repeated with *, and checked with in.
first = "Informatics" second = "Practices" print(first + " " + second) print("Ha" * 3) print(len(first)) print("form" in first) print(first[0], first[-1], first[0:4]) # Output: # Informatics Practices # HaHaHa # 11 # True # I s Info -
Count the vowels in a string entered by the user.
s = input("Enter a string: ") count = 0 for ch in s: if ch in "aeiouAEIOU": count += 1 print("Number of vowels:", count) # Sample run (the values after each prompt are typed by the user): # Enter a string: Informatics Practices # Number of vowels: 7 -
Print the words of a string that start with a given letter.
s = input("Enter a sentence: ") letter = input("Starting letter: ") for word in s.split(): if word[0].lower() == letter.lower(): print(word) # Sample run (the values after each prompt are typed by the user): # Enter a sentence: Python programs make practice perfect # Starting letter: p # Python # programs # practice # perfect -
For a few strings, print how many times a given letter appears in each.
n = int(input("How many strings? ")) letter = input("Letter to count: ") for i in range(n): s = input("String: ") print(s, "->", s.count(letter)) # Sample run (the values after each prompt are typed by the user): # How many strings? 3 # Letter to count: a # String: banana # banana -> 3 # String: apple # apple -> 1 # String: grape # grape -> 1 -
Slicing with [::-1] reverses a string.
s = input("Enter a word: ") rev = s[::-1] print("Reversed:", rev) if s.lower() == rev.lower(): print("It is a palindrome") else: print("It is not a palindrome") # Sample run (the values after each prompt are typed by the user): # Enter a word: Level # Reversed: leveL # It is a palindrome
LISTS 15 programs
-
Positions start at 0. Negative positions count from the end.
fruits = ["apple", "mango", "banana", "grapes"] print(fruits) print(fruits[0]) # first print(fruits[-1]) # last print(len(fruits)) # number of items # Output: # ['apple', 'mango', 'banana', 'grapes'] # apple # grapes # 4 -
Visit each item one by one.
marks = [72, 85, 90, 66] for m in marks: print(m) for i in range(len(marks)): print("Position", i, "->", marks[i]) # Output: # 72 # 85 # 90 # 66 # Position 0 -> 72 # Position 1 -> 85 # Position 2 -> 90 # Position 3 -> 66 -
L[start:stop] gives items from start up to stop - 1.
L = [10, 20, 30, 40, 50, 60] print(L[1:4]) # positions 1, 2, 3 print(L[:3]) # first three print(L[3:]) # from position 3 to the end print(L[::-1]) # reversed # Output: # [20, 30, 40] # [10, 20, 30] # [40, 50, 60] # [60, 50, 40, 30, 20, 10] -
+ joins two lists, * repeats a list, in checks if an item is present.
a = [1, 2, 3] b = [4, 5] print(a + b) print(a * 2) print(2 in a, 9 in a) # Output: # [1, 2, 3, 4, 5] # [1, 2, 3, 1, 2, 3] # True False -
append() adds at the end; insert(pos, item) adds at a position.
L = [10, 20, 30] L.append(40) print(L) L.insert(1, 15) # put 15 at position 1 print(L) # Output: # [10, 20, 30, 40] # [10, 15, 20, 30, 40] -
remove(value) deletes by value; pop() deletes the last item (or a given position) and returns it.
L = [10, 15, 20, 30, 40] L.remove(15) print(L) x = L.pop() # removes the last item print("Removed:", x, "List:", L) y = L.pop(0) # removes position 0 print("Removed:", y, "List:", L) # Output: # [10, 20, 30, 40] # Removed: 40 List: [10, 20, 30] # Removed: 10 List: [20, 30] -
Built-in functions on a list of numbers.
marks = [72, 85, 90, 66, 78] print("Highest:", max(marks)) print("Lowest:", min(marks)) print("Total:", sum(marks)) print("Average:", sum(marks) / len(marks)) # Output: # Highest: 90 # Lowest: 66 # Total: 391 # Average: 78.2 -
count(x) says how many times x appears; index(x) gives the position of the first x.
L = [3, 7, 3, 9, 3, 5] print(L.count(3)) print(L.index(9)) print(L.index(3)) # first 3 only # Output: # 3 # 3 # 0 -
sort() arranges the list; reverse() turns it back to front.
L = [40, 10, 30, 20] L.sort() print(L) L.sort(reverse=True) print(L) L.reverse() print(L) # Output: # [10, 20, 30, 40] # [40, 30, 20, 10] # [10, 20, 30, 40] -
Items of a list can be changed. list() makes a list from a string or range.
L = [1, 2, 3] L[1] = 200 print(L) print(list("hello")) print(list(range(1, 6))) # Output: # [1, 200, 3] # ['h', 'e', 'l', 'l', 'o'] # [1, 2, 3, 4, 5] -
Find the largest and smallest numbers in a list without max() and min().
L = [45, 12, 78, 34, 89, 23] largest = L[0] smallest = L[0] for x in L: if x > largest: largest = x if x < smallest: smallest = x print("Largest:", largest) print("Smallest:", smallest) # Output: # Largest: 89 # Smallest: 12 -
split() breaks the typed line into parts; int() turns each part into a number.
data = input("Enter numbers separated by spaces: ") L = [] for part in data.split(): L.append(int(part)) print("List:", L) print("Sum:", sum(L)) # Sample run (the values after each prompt are typed by the user): # Enter numbers separated by spaces: 5 12 8 20 3 # List: [5, 12, 8, 20, 3] # Sum: 48 -
Sort a copy of the list: the third item from each end is the answer.
L = [45, 12, 78, 34, 89, 23, 56] S = sorted(L) # new sorted list, L is unchanged print("Sorted:", S) print("Third smallest:", S[2]) print("Third largest:", S[-3]) # Output: # Sorted: [12, 23, 34, 45, 56, 78, 89] # Third smallest: 34 # Third largest: 56 -
Check each number and add to the right counter.
L = [12, 7, 9, 20, 33, 18, 5] even = 0 odd = 0 for x in L: if x % 2 == 0: even += 1 else: odd += 1 print("Even numbers:", even) print("Odd numbers:", odd) # Output: # Even numbers: 3 # Odd numbers: 4 -
Go through the list until the item is found.
L = [14, 27, 8, 33, 50] x = int(input("Number to search: ")) found = False for i in range(len(L)): if L[i] == x: print("Found at position", i) found = True if not found: print("Not found") # Sample run (the values after each prompt are typed by the user): # Number to search: 33 # Found at position 3
DICTIONARIES 10 programs
-
A dictionary stores key: value pairs. Use the key in [ ] to get its value.
student = {"name": "Riya", "class": 11, "marks": 88} print(student) print(student["name"]) print(student["marks"]) print(len(student)) # Output: # {'name': 'Riya', 'class': 11, 'marks': 88} # Riya # 88 # 3 -
Assign to a new key to add, to an old key to change; del removes.
student = {"name": "Riya", "marks": 88} student["city"] = "Delhi" # add student["marks"] = 91 # change print(student) del student["city"] # delete print(student) # Output: # {'name': 'Riya', 'marks': 91, 'city': 'Delhi'} # {'name': 'Riya', 'marks': 91} -
keys() gives all keys, values() all values, items() the pairs.
price = {"pen": 10, "pencil": 5, "eraser": 3} print(price.keys()) print(price.values()) print(price.items()) # Output: # dict_keys(['pen', 'pencil', 'eraser']) # dict_values([10, 5, 3]) # dict_items([('pen', 10), ('pencil', 5), ('eraser', 3)]) -
A for loop over a dictionary gives the keys; use them to get the values.
price = {"pen": 10, "pencil": 5, "eraser": 3} for item in price: print(item, "costs", price[item]) for item, cost in price.items(): print(item, "->", cost) # Output: # pen costs 10 # pencil costs 5 # eraser costs 3 # pen -> 10 # pencil -> 5 # eraser -> 3 -
update() adds/changes many items; clear() empties; dict() makes a dictionary.
d = dict(a=1, b=2) print(d) d.update({"b": 20, "c": 30}) print(d) d.clear() print(d) # Output: # {'a': 1, 'b': 2} # {'a': 1, 'b': 20, 'c': 30} # {} -
in checks the keys of a dictionary.
capital = {"Kerala": "Thiruvananthapuram", "Goa": "Panaji"} state = input("Enter a state: ") if state in capital: print("Capital:", capital[state]) else: print("Not in the dictionary") # Sample run (the values after each prompt are typed by the user): # Enter a state: Goa # Capital: Panaji -
Create a dictionary to store names of states and their capitals.
capitals = {} n = int(input("How many states? ")) for i in range(n): state = input("State: ") city = input("Capital: ") capitals[state] = city print(capitals) for state in capitals: print("The capital of", state, "is", capitals[state]) # Sample run (the values after each prompt are typed by the user): # How many states? 3 # State: Kerala # Capital: Thiruvananthapuram # State: Punjab # Capital: Chandigarh # State: Assam # Capital: Dispur # {'Kerala': 'Thiruvananthapuram', 'Punjab': 'Chandigarh', 'Assam': 'Dispur'} # The capital of Kerala is Thiruvananthapuram # The capital of Punjab is Chandigarh # The capital of Assam is Dispur -
Create a dictionary of students with their marks in 5 subjects, and show each total.
result = {} n = int(input("How many students? ")) for i in range(n): name = input("Name: ") marks = [] for j in range(5): marks.append(int(input(" Subject " + str(j + 1) + " marks: "))) result[name] = marks for name in result: print(name, result[name], "Total:", sum(result[name])) # Sample run (the values after each prompt are typed by the user): # How many students? 2 # Name: Riya # Subject 1 marks: 78 # Subject 2 marks: 85 # Subject 3 marks: 92 # Subject 4 marks: 70 # Subject 5 marks: 88 # Name: Aman # Subject 1 marks: 65 # Subject 2 marks: 72 # Subject 3 marks: 80 # Subject 4 marks: 91 # Subject 5 marks: 58 # Riya [78, 85, 92, 70, 88] Total: 413 # Aman [65, 72, 80, 91, 58] Total: 366 -
max() and min() on values() give the highest and lowest values; a loop finds whose they are.
marks = {"Riya": 88, "Aman": 75, "Sara": 93, "Kabir": 67} high = max(marks.values()) low = min(marks.values()) for name in marks: if marks[name] == high: print("Highest:", name, high) if marks[name] == low: print("Lowest:", name, low) # Output: # Highest: Sara 93 # Lowest: Kabir 67 -
Use each letter as a key and its count as the value.
word = input("Enter a word: ") count = {} for ch in word: if ch in count: count[ch] += 1 else: count[ch] = 1 print(count) # Sample run (the values after each prompt are typed by the user): # Enter a word: mississippi # {'m': 1, 'i': 4, 's': 4, 'p': 2}
INTRODUCTION TO NUMPY 6 programs
-
import numpy as np, then np.array(list). Arrays print without commas.
import numpy as np marks = [72, 85, 90, 66] arr = np.array(marks) print(arr) print(type(arr)) # Output: # [72 85 90 66] # <class 'numpy.ndarray'> -
Each inner list becomes one row.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr) print(arr[1][2]) # row 1, column 2 # Output: # [[1 2 3] # [4 5 6]] # 6 -
ndim: number of dimensions; shape: (rows, columns); size: number of items.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print("Dimensions:", arr.ndim) print("Shape:", arr.shape) print("Size:", arr.size) # Output: # Dimensions: 2 # Shape: (2, 3) # Size: 6 -
dtype= sets the type of every item; mixed types become one common type.
import numpy as np a = np.array([1, 2, 3], dtype=float) print(a, a.dtype) b = np.array([1, 2.5, 3]) # one float makes all floats print(b, b.dtype) c = np.array([1, "two", 3]) # one string makes all strings print(c) # Output: # [1. 2. 3.] float64 # [1. 2.5 3. ] float64 # ['1' 'two' '3'] -
An operation on an array is done on every item, without a loop.
import numpy as np price = np.array([100, 250, 80]) print(price + 10) print(price * 2) qty = np.array([2, 1, 5]) print(price * qty) # item by item print((price * qty).sum()) # total bill # Output: # [110 260 90] # [200 500 160] # [200 250 400] # 850 -
The same * 2 repeats a list but doubles every value in an array.
import numpy as np L = [1, 2, 3] A = np.array(L) print(L * 2) print(A * 2) print(L + L) print(A + A) # Output: # [1, 2, 3, 1, 2, 3] # [2 4 6] # [1, 2, 3, 1, 2, 3] # [2 4 6]