Python Notes Complete
Python Notes Complete
Class 11
Abstract
Overview of textbook chapters – Class notes
Srividhya C
Srividhya.c@[Link]
Heartfulness International School, Omega Branch 2025-2026
Contents
Chapter 3 Introduction to Problem Solving ............................................................................................ 3
Chapter 4 Python Data Handling .......................................................................................................... 10
Additional notes: ............................................................................................................................... 26
Chapter 5 ............................................................................................................................................... 27
Statements ......................................................................................................................................... 27
Another type of classification ........................................................................................................... 27
Conditional Statements ..................................................................................................................... 28
Programs: .................................................................................................................................... 28
Coding Questions: ......................................................................................................................... 30
Menu Driven programs: ................................................................................................................ 32
Looping Statements ........................................................................................................................ 33
Jump statements .................................................................................................................................. 3
Chapter 6 – Strings.................................................................................................................................. 5
Types ................................................................................................................................................... 5
Accessing Characters/Indexing ........................................................................................................... 5
Traversing a string: ............................................................................................................................. 5
String Operations: ............................................................................................................................... 7
String Slicing: ..................................................................................................................................... 7
String methods and built-in functions: .............................................................................................. 10
Chapter 7 – Lists ................................................................................................................................... 24
Types ................................................................................................................................................. 24
Initializing a list ................................................................................................................................ 24
Accessing list elements ..................................................................................................................... 24
Traversing a list................................................................................................................................. 25
List Operations:................................................................................................................................. 26
Concatenation ................................................................................................................................... 26
Repetition .......................................................................................................................................... 27
Membership ...................................................................................................................................... 27
Comparison ....................................................................................................................................... 27
Indexing ............................................................................................................................................ 27
List Slicing: ....................................................................................................................................... 27
Modifying ......................................................................................................................................... 27
List Comprehension .......................................................................................................................... 29
Heartfulness International School, Omega Branch 2025-2026
Algorithms
Decomposition
Flowcharts:
Sample flowchart:
Number Palindrome-
Heartfulness International School, Omega Branch 2025-2026
4. Draw a flowchart
a. To calculate the sales commission
i. 0% for sales<=10000
ii. 5% for sales<=50000
iii. 10% for sales <=100000
iv. 15% for sales>100000
b. To display the square of a number
c. To find the largest of three numbers
5. Pseudocode:
a. To check whether a number is even or odd
b. To check whether a person can vote or not
About Python
Heartfulness International School, Omega Branch 2025-2026
• Developed by Guido Van Rossum in 1991 at the National Research Institute for
Mathematics and Computer Science, the Netherlands
• He was the BDFL, until he stepped down from the position in 2018
• Currently Python is owned by Python Software Foundation (PSF)
• It is based on ABC teaching language, which was developed to replace BASIC
• The name was inspired by the famous BBC comedy show Monty Python’s Flying
Circus
• Present day applications –
Features of Python
Heartfulness International School, Omega Branch 2025-2026
Open Portable
Easy
source
Large
Higly repository
Interactive
efficient of libraries
Better Dynamic
Interpreted Garbage typing
collection
Object-
Oriented
Programmi Compatible Extendable
ng
Advantages of Python:
Limitations of Python:
1. Speed
2. Mobile development
3. Runtime Errors
Installing Python
o ‘print’ method
1. Attributes ‘sep’ and ‘end’
➢ Python editor window / Script mode
Additional Notes:
Language Translators:
Recap
1. What is Python?
2. What is Dynamic typing?
3. How is Python a high-level programming language?
4. Compare Interpreted and Compiled Programming languages.
5. Explain about Python’s Garbage Collection?
Heartfulness International School, Omega Branch 2025-2026
+ - * / // % ** \ [] ()
{} = != < > <= >= . , ‘‘
““ ; : ! # ? $ & ^ @
_
o Whitespaces: blank space, tab space (‘\t’), carriage return (CR), newline (line
feed – LF), form feed (FF) – control characters
o Other characters – All other 256 ASCII and Unicode characters
➢ Tokens
Identifiers
Keywords
Literals
Operators
Delimiters
or
>>>import keyword
>>>[Link]
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
A=1
B=2
C=A%B
Escape Sequences:
➢ Variables
o value
o memory location - id()
1. The id() function returns the memory address (unique identifier) of an
object.
o datatype - type()
Heartfulness International School, Omega Branch 2025-2026
Numbers
• Integers
• Boolean - sub-type of integers
• Float
• Complex - r+ij
Sequences
• Strings
• Lists
• Tuples
Mappings
• Dictionary
None
➢ Data Types
o Numbers
1. Integers
• Boolean
2. Floats
>>>0.1+0.1+0.1==0.3
False #this is because of floating point approximation
3. Complex Numbers
• Attributes of a complex number are real and imag
o <identifier>.real
o <identifier>.imag
4. Types of Numbers Systems in Python
• Decimal (Base-10)
o The standard number system we use in everyday life.
Python treats numbers like 10, 200, and -5 as decimal
numbers by default.
o num = 123
• Binary (Base-2)
Heartfulness International School, Omega Branch 2025-2026
Positive Indices 0 1 2 3 4 5 6 7 8 9 10
String H E L L O W O R L D
Negative Indices -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
o Mappings
• Dictionary Syntax – {key1:value1,key2:value2…}
• dict() construct
• Dictionaries are unordered collections of key-value pairs.
• They are mutable and indexed by keys. (i.e. There is no indexing
in dictionary, instead we use the keys to access the values).
• Types of Dictionaries:
o Simple Dictionary
▪ Basic key-value pair mapping.
▪ student = {"name": "Asha", "age": 16}
o Nested Dictionary
▪ A dictionary within another dictionary.
▪ school = {"class11": {"Asha": 90, "John": 95}}
Heartfulness International School, Omega Branch 2025-2026
o Empty Dictionary
▪ Contains no key-value pairs.
▪ empty = {}
o None
➢ Operators
o Arithmetic / Mathematical ((), **, -, * / // %, + -) -> PE(U)MDAS
1. Used on Numeric Data types
• Floor division
o For integer operands:
▪ If both operands are integers, the result will be an
integer (no matter if the result is a whole number
or not).
o For floating-point operands:
▪ If either operand is a float, the result will be a
float.
2. Used on Sequences
• Concatenation using ‘+’
• Repetition using ‘*’
o Identity operator:
1. Identity operators are used to compare object references — i.e.,
whether two variables point to the same object in memory.
Operator Description Example
is True if both refer to same object a is b
is not True if they refer to different objects a is not b
Practice:
Operation Result Reason Operation Result Reason
0 or 0 0 and 0
0 or 8 0 and 8
5 or 0.0 5 and 0.0
‘’ or ‘d’ ‘’ and ‘d’
‘’ or ‘’ ‘’ and ‘’
‘a’ or ‘j’ ‘a’ and ‘j’
o Assignment Operator (=, +=, -=, *=, /=, //=, %=, **=):
Assignment operators are used to assign values to variables. The basic format
is:
<variable/identifier> = value
Evaluate this:
Note:
The or operator will test the second operand only if the first operand is false, otherwise ignore
it; even if the second operand is logically wrong.
Note:
The and operator will test the second operand only if the first operand is true, otherwise ignore
it; even if the second operand is logically wrong.
Additional concepts:
o Syntax:
o end Parameter
1. Controls what is printed at the end of the output.
2. Default is a newline (\n)
o
➢ The input() function
o Single-line multiple inputs
o Using split()
o Using map()
➢ The eval() function
Heartfulness International School, Omega Branch 2025-2026
o
o Try eval() with different datatype inputs
➢ Program examples
o Average of two numbers
o Perform all arithmetic operations on two user given numbers
➢ Data type conversions
o Implicit - Coercion
o Explicit – Type Casting – int(input(“Enter a number:”))
➢ Datatypes
o Mutable – in place change of value
o Immutable
➢ Additional Functions
o ord() – returns ordinal number
o chr() – returns the character
➢ Comments
o Single line - #
o Multiline –‘’’ ‘’’ / “”” “””
➢ Rules of writing code
o Statement termination
o Clarity and Simplification of expression
o Simplicity of instructions
o Maximum line length – 79 characters
o Lines and Indentation
o Avoid multiple statements on one line
Heartfulness International School, Omega Branch 2025-2026
o Example:
Write a user defined function to get a student’s name from the user and display
the concatenated string of student’s name and class/section. Write the same
function in all 4 types.
➢ Indentation
o What is Indentation?
1. Indentation refers to the leading whitespace (spaces or tabs) before a line
of code.
2. It is used to define the structure and flow of a Python program.
Heartfulness International School, Omega Branch 2025-2026
o Runtime error
1. Runtime errors are exceptions that occur while the program is running.
2. These errors do not stop the code from being written or compiled, but
they crash during execution if not handled.
3. Types:
• NameError - Occurs when you use a variable that hasn't been
defined.
o >>>print(x) Erroneous code
o Logical error
1. A logical error occurs when the program runs without any syntax or
runtime errors, but the output is incorrect because the logic used in the
code is flawed.
2. The program is syntactically correct but semantically wrong.
3. Characteristics:
• No error message is shown.
• The program runs normally.
• Output is unexpected or incorrect.
• Often caused by mistakes in formulas, conditions, or loops.
• Harder to detect — must be found through testing and
debugging.
4. Example:
Heartfulness International School, Omega Branch 2025-2026
20.0
>>>(10+20)/2 Corrected code
15.0
Programs revision:
Additional notes:
1. How to get multiple string inputs in a single line?
a. X,y=input(“Enter first word:”), input(“Enter second word:”)
b. X,y=input(“Enter two words separated by space:”).split()
c. X,y=input(“Enter two words separated by ‘:’ –“).split(‘:’)
2. How to get lists, tuples and dictionaries as user inputs?
a. X=eval(input(“Enter a list:”))
b. X=eval(input(“Enter a tuple:”))
c. X=eval(input(“Enter a dictionary:”))
3. How to get multiple integer inputs from user in a single line?
a. X,y=map(int, input(“Enter two numbers separated by space:”).split())
4. How to get multiple different data types as user input in a single line?
a. X,y=map(eval, input(“Enter the values separated by space:”).split())
Recall:
1. Get a 2-digit number from user and print the reverse of the 2-digit number.
2. Write a user-defined function to get the student’s name, and return the name to main
function to be displayed.
Heartfulness International School, Omega Branch 2025-2026
Chapter 5
Statements
➢ Empty statement – ‘pass’
➢ Simple statements
➢ Compound statements
Simple Statement
Compound Statement
Statements
Based on the flow of control
Based on the
The codes are Based on a
outcome of an
executed one after condition/event a
event/condition the
the other in an block of code is
flow of control
orderly manner repeated
changes
Conditional Statements
➢ Changes the flow of control based on the outcome of the conditions
if block -
Syntax:
if <condition>:
<statement(s)>
if else block -
Syntax:
if <condition>:
<statement(s)>
else:
<statement(s)>
if elif else block –
➢ If the first condition is false, then the next condition is checked, and so on. If one of
the conditions is true, then the corresponding indented block executes, and the if
statement terminates.
Syntax:
if <condition>:
<statement(s)>
elif <condition>:
<statement(s)>
else:
<statement(s)>
Nested if block –
Syntax
if <condition1>: #outer if block
if <condition2>: #inner if block
<statement(s)>
<statement(s)>
>40 E
If the student has failed to score more than 40 even in one subject then display the
result as “fail, you have not been promoted”.
6. Check whether a user given number is negative, zero or positive integer.
Sample Program Code Output
#With separate if statements
10. Check whether a user given number is divisible by 5 or not. If divisible, also check
whether the number is divisible by 10.
11. A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap
years unless they are also divisible by 400. Write a program that asks the user for a year
and prints out whether it is a leap year or not.
Coding Questions:
1. Rewrite the following code fragment that saves on the number of comparisons:
if (a==0):
print(“Zero”)
elif (a==1):
print(“One”)
elif (a==2):
print(“Two”)
elif (a==3):
print(“Three”)
print('D')
4. What is the error in the following code? Also correct the code:
weather='raining'
if weather=='sunny':
print('wear sunblock')
elif weather=='snow':
print('going skiing')
else:
print(weather)
if x:
print('hi')
else:
print('bye')
8. Predict the output:
marks = 72
if marks >= 60:
if not marks < 80:
print("Grade A", end='\n')
else:
print("Grade B", end='\n')
else:
print("Fail", end='\n')
print(marks)
9. Predict the output:
a=True
b=False
c=False
if not a or b:
print(1)
elif not a or not b and c:
print(2)
elif not a or b or not b and a:
print(3)
else:
print(4)
10. Predict the output:
def calcresult():
i=9
while i>1:
if i%2==0:
x=i%2
i-=1
else:
i=i-2
x=i
print(x**2)
calcresult()
Recall:
1. Write a python program that will take an integer as input and provide the corresponding
day of the week as the output; i.e. if the input is 1, the output should be Sunday.
Looping Statements
Loops allow us to repeat a block of code multiple times — either for a specific number of
times or until a condition is met.
Python provides two main types of loops:
➢ For loop – Used when you know how many times you want to repeat something.
➢ While loop – Used when you want to repeat until a condition becomes false.
print(<counter>, end=’ ‘)
Example:
for i in s:
print(i, end=’ ‘)
#The same way, try for other types of sequences like lists, tuples and dictionaries.
Range function:
The range() function is used to generate a sequence of numbers. It is commonly used in loops
(especially for loops) when you want to repeat a task a certain number of times or over a
numerical range. It is immutable.
Returns a range object, which is an immutable, lazy iterable (doesn’t generate all values at
once).
Syntax:
range(start,stop,step)
step Optional An integer that increments (or decrements) the count. Default is 1.
Can be negative.
Example:
for i in range(10):
print(i)
print(i)
s = "PYTHON"
for i in range(len(s)):
Heartfulness International School, Omega Branch 2025-2026
Programs:
1. Write a python program to display the negative integers from -1 till -n, where n is user
input.
2. Write a python program to display the elements of a list in reverse order using a loop.
l=[1,2,3,4,5]
op=> 5 4 3 2 1
3. Find the factorial of a given number.
4. Calculate and display the square of all numbers from 1 to a given number.
5. Find the sum of the series up to n terms.
s='abc'
l=[1,2]
t=9,8
r=range(2)
s=s+s t=t+s
s=s+l t=t+l
s=s+t t=t+t
s=s+r t=t+r
s+=s t+=s
s+=l t+=l
s+=t t+=t
s+=r t+=r
l=l+s r=r+s
l=l+l r=r+l
l=l+t r=r+t
l=l+r r=r+r
l+=s r+=s
l+=l r+=l
l+=t r+=l
l+=r r+=r
s+=i
print("The sum of the first 10 natural
numbers is", s)
l=[]
for i in range(1, 21, 2):
if i%4==0:
l+=[i]
print(l)
s='Computer'
for i in s:
print(i, end='*')
print()
for i in range(len(s)):
print(s[i], end='@')
print()
for i in range(len(s)-1, -1, -1):
print(s[i], end='$')
print()
print(range(5)[-1])
Programs:
1. Write a python program to print every second character in the given string, while
reading it from both left to right and right to left.
2. Write a python program to calculate the sum of multiples of 3 from 3 till n.
3. Write a python program to calculate the factorial of a number.
4. Write a python program to display the Fibonacci series till n.
While Loop:
Syntax:
while <condition>:
# code block
Comparison of for and while loops:
Programs:
1. Write a program to display the first n whole numbers, where n is user input using ‘for’
loop.
2. Write a program to get a list from the user and
a. display the list elements one below the other
b. display the elements in odd positions
c. display the elements in the even positions
3. Write a python program to input a string from the user and display the reversed string.
4. Convert the above code to use ‘while’ loop.
5. Print the multiplication table for n.
6. Get n numbers from the user
and count the even and odd numbers
separately.
- After the successful completion of all the iterations of the for loop the else block will
be executed.
Example:
Code Output
for i in range(5): 0
print(i) 1
else: 2
print("End of loop") 3
4
End of loop
- After the successful completion of all the iterations of the while loop the else block will
be executed.
Example:
Code Output
i=1 1
while i<=5: 2
print(i) 3
Heartfulness International School, Omega Branch 2025-2026
i+=1 4
else: 5
print("End of loop") End of loop
Jump statements
1. Break
2. Continue
3. Pass
4. Return
Question 1:
for i in range(10,20):
if not i%2:
print(i)
else:
print("End of loop")
Question 2:
for i in range(10,20):
if not i%2:
continue
print(i)
else:
print("End of loop")
Question 3:
for i in range(10,20):
if not i%2:
break
print(i)
else:
print("End of loop")
Question 4:
for i in range(5):
if i == 3:
pass
print(i)
else:
print("End of loop")
Question 5:
for i in range(5):
if i == 3:
Heartfulness International School, Omega Branch 2025-2026
continue
print(i)
else:
print("End of loop")
Question 6:
for i in range(5):
if i == 3:
break
print(i)
else:
print("End of loop")
Programs
1. Write a python program to input a string from the user and display the reversed string.
2. Write a python program to print the Fibonacci series.
3. Write a python program to display the factors of a user given number.
4. Write a python program to check whether a user given number is a perfect number or
not.
5. Write a python program to check whether the given number is a prime number or not.
6. Change the above program to repeat until the user chooses to exit.
7. Menu-Driven Programs to be looped till user wishes to exit
Chapter 6 – Strings
- Consecutive sequence of characters enclosed within single quotes or double quotes
- immutable
Types
➢ Empty
o ‘’,””,str()
➢ Single line
➢ Multiline
Notice:
No newline characters (\n) are included. So, the length of s2 is smaller compared to s1.
Making use of \, \n and \t
Accessing Characters/Indexing
Traversing a string:
➢ Using for loop
Heartfulness International School, Omega Branch 2025-2026
String Operations:
Concatenation
• string1+string2 Eg: "CS"+" "+"IS"+" "+"FUN" => "CS IS FUN"
Repetition
• string1*n Eg: "PYTHON"*3 => "PYTHONPYTHONPYTHON"
Membership
• in / not in - substring in string1 Eg: "S" in "CS" => True
Comparison
• >,<,>=,<=,==,!= - string1>string2 Eg: "CS"!="PYTHON" => True
Slicing
• string[start:stop:step] Eg: "HELLO WORLD"[:5] => "HELLO"
String Slicing:
- used to retrieve a substring called as slice
<string_name>[start:stop:step]
0 1 2 3 4 5 6 7 8 9 10
H E L L O W O R L D
Heartfulness International School, Omega Branch 2025-2026
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
S No Question Code
1 Extract 'HELLO' from the string s[0:5]
2 Extract 'WORLD' from the string
3 Extract 'ELLO WOR' from the string
4 Extract 'LO WO' from the string using negative indices
5 Extract every second character from the string starting from the
first character
6 Extract every second character from the string starting from the
second character
7 Extract 'OLLEH' from the string using slicing to reverse the first
part
8 Extract 'DLROW' from the string using slicing to reverse the
second part
9 Extract 'HLOD' from the string using slicing with step s[::3]
10 Extract 'LROW OLLEH' by reversing the entire string and then S[-2:-12:-1]
taking a slice S[-11::-1]
S[-1:-10:-1]
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
W E L C O M E T O M Y H O M E
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[3:18]) =>’COME TO MY HOME’
print(s[2:14:2]) =>’LOET Y’
print(s[:7]) =>’WELCOME’
print(s[8:-16:-1]) =>’’
print(s[-9:15]) =>’’
print(s[0:9:3]) =>’WCE’
print(s[9:29:2]) =>’OM OE’
print(s[-6:-9:-3]) =>’Y’
print(s[-9:-9:-1]) =>’’
print(s[8:25:3]) =>’TMHE’
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
E V E R Y T H I N G I S A W E S O M E
Answers:
print(s[5:13]) =>’ THING IS’
print(s[-7:]) =>’AWESOME’
Heartfulness International School, Omega Branch 2025-2026
print(s[1:-16]) =>’VERY ‘
print(s[::-3]) =>’ESAINTE’
print(s[12:5:1]) =>’’
print(s[5:-6]) =>’ THING IS A’
print(s[-1:-8:-1]) =>’EMOSEWA’
print(s[2:8][::-1]+s[-10:-14:-1]+s[-7:-8:-1]) =>print(‘ERY TH’[::-1]+’I GN’+’A’)
=>print(‘HT YRE’+’I GN’+’A’)=>’IHTYREI GNA’
print(s[25::-1]) =>’EMOSEWA SI GNIHTYREVE’
print(s[-4:3:-1]) =>’SEWA SI GNIHTY’
Quirks:
Will string s=’Hello world’ be the same as s[:]?
1. <string>.swapcase()
➢ Explanation: Converts uppercase letters to lowercase and lowercase to uppercase.
➢ Example:
s = "PyThOn"
print([Link]()) # pYtHoN
➢ Use Case:
✓ Useful in text transformation tasks
✓ Can be used when you want to toggle case without knowing original casing.
2. <string>.capitalize()
Heartfulness International School, Omega Branch 2025-2026
➢ Explanation: Makes the first character (if it’s an alphabet) uppercase, rest lowercase.
➢ Example:
s = "python programming"
print([Link]()) # Python programming
➢ Use Case: Formatting sentences before displaying.
6. <string>.isalnum()
➢ Explanation: Returns True if all characters are letters or digits.
➢ Example:
print("Python3".isalnum()) # True
print("Python 3".isalnum()) # False (space not allowed)
➢ Use Case: Validate usernames, IDs.
7. <string>.isalpha()
➢ Explanation: Returns True if all characters are alphabets only.
➢ Example:
print("Hello".isalpha()) # True
print("Hello123".isalpha()) # False
➢ Use Case: Checking if input is only text (e.g., name).
8. <string>.isdigit()
➢ Explanation: Returns True if all characters are digits.
➢ Example:
print("12345".isdigit()) # True
print("12a45".isdigit()) # False
➢ Use Case: Validating numeric-only input (phone number, roll number).
Heartfulness International School, Omega Branch 2025-2026
9. <string>.islower()
➢ Explanation: Returns True if all letters are lowercase.
➢ Example:
print("python".islower()) # True
print("Python".islower()) # False
➢ Use Case: Password case sensitivity checks.
10. <string>.isspace()
➢ Explanation: Returns True if string has only whitespace.
➢ Example:
print(" ".isspace()) # True
print(" a ".isspace()) # False
➢ Use Case: Input validation (skip blank lines).
11. <string>.isupper()
➢ Explanation: Returns True if all letters are uppercase.
➢ Example:
print("HELLO".isupper()) # True
print("Hello".isupper()) # False
➢ Use Case: Formatting checks for headings, codes.
12. <string>.lower()
➢ Explanation: Converts string to lowercase.
➢ Example:
print("PyThOn".lower()) # python
➢ Use Case: Case-insensitive comparison.
13. <string>.upper()
➢ Explanation: Converts string to uppercase.
➢ Example:
print("PyThOn".upper()) # PYTHON
➢ Use Case: Making text uniform for processing.
print("Python".endswith("on")) # True
➢ Use Case: File extension check (.endswith(".txt")).
16. <string>.title()
➢ Explanation: Capitalizes each word in a string separated by non-alphanumeric
characters
➢ Example:
print("hello world".title()) # Hello World
➢ Use Case: Proper formatting of names, titles.
➢ Exception:
'asdasd asdasd 34rt34rt2113df#$er'.title()
17. <string>.istitle()
➢ Explanation: Checks if string follows title case.
➢ Example:
print("Hello World".istitle()) # True
print("hello world".istitle()) # False
➢ Use Case: Checking formatted names.
19. "<sep>".join(iterable)
➢ Explanation: Joins items of list into string with separator.
➢ Example:
words = ["Python", "is", "fun"]
print(" ".join(words)) # Python is fun
➢ Use Case: Making sentences, CSV export.
20. <string>.split(sep)
➢ Explanation: Splits string into list of words.
➢ Example:
s = "Python is fun"
print([Link]()) # ['Python', 'is', 'fun']
print([Link]("i")) # ['Pyth', 'n ', 's fun']
➢ Use Case: Tokenizing text into words.
21. <string>.partition(sep)
➢ Explanation: Creates a tuple by splitting the string into 3 parts:
(before sep, sep itself, after sep)
➢ Example:
s = "name:John"
print([Link](":")) # ('name', ':', 'John')
➢ Use Case: Extracting key-value pairs from text.
List of Whitespaces:
Whitespace are the actual characters in memory. A whitespace character is just like the letter
"A" or digit "5", except it’s invisible. Escape Sequences are Notations for hard-to-type
characters. Hence \t is not 2 characters, but a single tab character in memory. You can type "
" (space) directly, but how do you type a newline into a one-line string? You can’t — you
need \n.
Therefore:
Heartfulness International School, Omega Branch 2025-2026
• Escape sequence = the code you write in your source file to tell Python to insert that
thing.
Del statement
• Once deleted, that name or element cannot be accessed again unless redefined.
• Example 1:
o x = 100
o del x
• Example 2:
o x = "Python is fun"
o del x
• Example 3:
o x = "Python is fun"
o del x[:3] # TypeError, 'str' object does not support item deletion
Max()
Min()
Sum()
Example:
s = "HelloWorld"
print(min(s)) #H
print(max(s)) #r
Packing means placing multiple values into a single variable (usually into a sequence like a
tuple, list, or even string).
Example:
Example 1:
s = "CAT"
print(a, b, c)
Heartfulness International School, Omega Branch 2025-2026
Example 2:
s = "PYTHON"
a, *b, c = s
Practice Questions:
Coding Questions:
1. Given:
s='''this
is a multiline
string'''
Predict the output of: print([Link]()==[Link]('\n'))
(a) True (b) False (c) None (d) Error
i += 1
else:
print("Outer while loop completed successfully")
str1+=str(d1[i])+' '
str2=str1[:-1]
print(str2[::-1])
Program questions:
1. Write a function in python which accepts a string as argument and display total number of
digits, and the sum of the digits.
2. Write a function in python which accepts a string and displays the entire string with first
and last letter in upper case. The rest of the characters should be in lower case.
3. Write a python program to read a string and display the last 3 characters of the string in
reverse.
4. Write a Python program to check whether a substring is present in a string or not. If present
display the index position else display ‘not present’. The string and the substring are user
input. Your code should work irrespective of the case of the string and substring.
5. Write a python program to read a string and display the string in title case without using
title() function. Two cases:
Heartfulness International School, Omega Branch 2025-2026
> Assume that it’s a proper English sentence with space-separated words.
6. Write a python program to read a string and replace every vowel with ‘#’.
7. Menu driven program to find the area of square, circle and triangle.
8. Write a python program to print the below pattern. (Refer Practical exam question bank)
10. Write a Python program to accept a string and display each word and it’s length.
Section - A
1. State True or False: The Python interpreter handles logical errors during code
execution.
2. Identify the output of the following code snippet:
text = "PYTHONPROGRAM"
text=[Link]('PY','#')
print(text)
country='International'
print([Link]("n"))
Heartfulness International School, Omega Branch 2025-2026
(A) ('I', 'ter', 'atio', 'al') (B) ['I', 'ter', 'atio', 'al']
(C) ['I', 'n', 'ter', 'n', 'atio', 'n', 'al'] (D) Error
print(message[-2::-2])
Section – B
6. How is a mutable object different from an immutable object in Python? Identify one
mutable object and one immutable object from the following: (1,2), [1,2], {1:1,2:2},
‘123’
Chapter 7 – Lists
- An ordered sequence of elements
- Mutable
- Could be homogeneous or heterogeneous
- Lists are mutable, but member objects may be immutable/mutable
Types
o Empty – []
o Long – [1,2,3,’a’,’b’,’c’,’d’,’e’,1.2,’asd123’,8,2,4,1,’asdfgf’,’;lkjhgh’]
o Nested – [‘a’,’hello’,’world’,[1,2,3,[4,’python’,5,6],[7,8,9],67],4.567]
Initializing a list
To create an L=[] #using the delimeters
Empty list L=list() #using the constructor
To create a list l=list('python3.8') ['p', 'y', 't', 'h', 'o', 'n', '3', '.', '8']
from another
sequences l=list([1,2.3,'hello']) [1, 2.3, 'hello']
l=list((1,'a',3.14)) [1, 'a', 3.14]
l=list({1:'11',2:'22'}) [1, 2]
l=list(123)
To create a list
from user input
Aliasing L1=[1,2,3,4,5]
L2=L1
L3=L1[3:]
Say list1=[1,2,3,'hello',3.14],
Heartfulness International School, Omega Branch 2025-2026
Traversing a list
o ‘in’ operator
o range() function
Say, L=[1,2,3,’a’,’b’,’c’,’d’,’e’,1.2,[‘CS’,’IP’]]
Notes Code Output
Left to right Traversal, for i in L: 1 2 3 a b c d e 1.2 ['CS',
using loop and print(i, end=' ') 'IP']
membership operator #no equivalent code in while loop
Left to right traversal, for i in range(len(L)): 1 2 3 a b c d e 1.2 ['CS',
using loop and range, print(L[i], end=' ') 'IP']
positive indexing
Left to right traversal, for i in range(-len(L), 0): 1 2 3 a b c d e 1.2 ['CS',
using loop and range, print(L[i], end=' ') 'IP']
negative indexing
Right to left traversal, for i in range(len(L)-1, -1, -1): ['CS', 'IP'] 1.2 e d c b a 3 2
using loop and range, print(L[i], end=' ') 1
positive indexing
Right to left traversal, for i in range(-1, -len(L)-1, -1): ['CS', 'IP'] 1.2 e d c b a 3 2
using loop and range, print(L[i], end=' ') 1
negative indexing
i=i+1
Right to left traversal, using i=len(L)-1 ['CS', 'IP'] 1.2 e d c b a 3 2
loop and range, positive while i>-1: 1
indexing print(L[i], end=' ')
i=i-1
Right to left traversal, using i=-1 ['CS', 'IP'] 1.2 e d c b a 3 2
loop and range, negative while i>= -len(L): 1
indexing print(L[i], end=' ')
i-=1
List Operations:
Concatenation
•List1+List2 Eg: [1,2,3] + ["a","b","c"] => [1,2,3,"a","b","c"]
Repetition
•List1*n Eg: [1,2,3] * 3 => [1,2,3,1,2,3,1,2,3]
Membership
•in / not in - element in List1 Eg: 3 in [1,2,3] => True
Comparison
•>,<,>=,<=,==,!= - List1 > List2 Eg: ['a','b']>['a','B'] => True
Slicing
•List1[start:stop:step] Eg: [1,2,3,"a","b","c"] [:4] => [1, 2, 3, 'a']
Modifying
<list_name>[index]=<new value>
Concatenation
l1=[1,2,['v','b']]
l2=['r','t',[1,2,[3,4.5]]]
Heartfulness International School, Omega Branch 2025-2026
l1+l2
Repetition
l1=[1,2,['v','b']]
l1*3
Membership
In and not in operators
Comparison
Using all the comparison operators.
Indexing
<list_name>[index] will return the value stored in that index position.
List Slicing:
- used to retrieve a sublist called as slice
<list_name>[start:stop:step]
0 1 2 3 4 5 6 7 8 9 10
1 2 3 4 [1,2] P Y T H O N
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Modifying
<list_name>[index]=<new value>
Practice Questions:
Set 2:
1. Predict the output. Why does the inner list [3, 4] appear multiple times?
l1 = [1, 2, [3, 4]]
l2 = l1 * 2
l3 = l1 + l2
print(l3)
2. Explain why one of them returns False and the other True.
l = [1, 2, [3, 4], 5]
print(3 in l)
print([3, 4] in l)
4. Why does one of these raise an error while the others work?
l = ['p', 'y', 't', 'h', 'o', 'n']
print(l[-6], l[-1], l[-7])
5. Slicing:
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:5:2])
print(nums[-5:-1:2])
print(nums[::-2])
l = [0, 1, 2, 3, 4, 5, 6]
l[1:6:2] = [11, 22, 33]
print(l)
Why must the replacement list [11, 22, 33] match the number of elements selected? What if you
tried [11, 22] instead?
7. Why does equality (==) return True but identity (is) return False?
l1 = [1, 2, 3]
l2 = l1[:]
print(l1 == l2, l1 is l2)
10. Write Python code (using slicing only, no loops) to reverse the middle part of this list:
List Comprehension
Syntax:
Example:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ld
[3, 9]
s='omega'
Heartfulness International School, Omega Branch 2025-2026
l1=list(s)
l2=[x for x in s]
l1
l2
l3
Questions:
8. words = ["one", "two", "three"], create a new list with the string elements reversed
using list comprehension
Copying a List
- Using the built-in method called copy()
lcopy1=l[:]
id(l);id(lcopy);id(lcopy1)
2380584570240 Read the output and understand that id(l) and id(lcopy) are same whereas id(lcopy1)
is different – hence we can understand that assignment with slice results in a true copy
2380584570240 similar to using the list() constructor (as shown by id(lcopy2)) and copy() function (as
shown by id(lcopy3)) in the subsequent lines.
2380584702656
lcopy2=list(l)
id(lcopy2)
2380540169472
lcopy3=[Link]()
lcopy3
[3, 9]
id(lcopy3)
2380584702016
Questions:
1. Given below are statements for creating a list. Find errors, if any, and rewrite the
correct statement:
a. L1=1,5,’t’,’n’
b. L=[[1,2,3,4],[‘my’,’class’]]
c. L=([1,2,3,4,5])
d. L=(10)
e. L=[Xylo, Xuv, Thar, Taigun]
Heartfulness International School, Omega Branch 2025-2026
Built-in methods
Practice Questions:
[Link] Question Output
1 l=[1,2,3,4,5]
[Link]([6,7])
[Link]([8,9])
2 my_list = [10, 20, 30]
my_list.insert(1, 15)
Heartfulness International School, Omega Branch 2025-2026
print(my_list)
3 my_list = ['a', 'b', 'c', 'b']
my_list.remove('b')
print(my_list)
4 names1 = ['Amir', 'Bala', 'Charlie']
names2 = [[Link]() for name in
names1]
print(names2[2][0])
5 my_list = [1, 2, 3, 4, 5]
print(my_list[::-1])
6 my_list = ['a', 'b', 'c', 'd']
joined_string = '-'.join(my_list)
print(joined_string,type(joined_string))
7 my_list = [1, 2, 3, 4]
del my_list[2]
print(my_list)
8 my_list = [1, 2, 3]
total_sum = sum(my_list)
print(total_sum)
9 my_list = ['apple', 'banana', 'cherry']
copied_list = my_list.copy()
copied_list.append('date')
print(my_list, copied_list)
10 my_list = [10, 5, 15, 20]
my_list.reverse()
print(my_list)
11 my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list)
12 my_list = [2, 4, 2, 6, 2, 8]
count_of_2 = my_list.count(2)
Heartfulness International School, Omega Branch 2025-2026
print(count_of_2)
13 my_list = [1, 2, 3, 4, 5]
index_of_3 = my_list.index(3)
print(index_of_3)
14 my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)
15 my_list = [1, 2, 3, 4, 5]
removed_element = my_list.pop(2)
print(my_list, removed_element)
16 numbers = [1, 2, 3, 4]
[Link]([5,6,7,8])
print(len(numbers))
17 l=[1,2,3,4]
l1='l + math'
l2=[Link](l1)
print(l2)
18 l=['q',0]*9
print(l)
19 l=[None]*10
print(len(l))
20 a='hello'
b=list(([Link](),len(x)) for x in a)
print(b)
21 a=[[]]*3 Reason:
a[1].append(7) id(a[0]);id(a[1]);id(a[2])
print(a) 2194004276608
2194004276608
2194004276608
id(a)
2194004276288
Hence, all the nested elements will
have the same memory location, so
Heartfulness International School, Omega Branch 2025-2026
print(l[::-1])
print(sorted(l)[::-1])
30 A=list(“Python is easy”)
for i in range(len(A)-1,0,-5):
Print(A[i], end=’&’)
31 A=[‘a’,’b’,’c’]
B=A
A[0]=’A’
print(A,B,sep=’$’)
32 L=[1,2,3,4]
L[1:1]='a'
L[1:3]='computer'
L[1:]='python'
33 lis=[2,1,3,5,4,3,8]
del lis[2:5]
print('List elements after deleting are : ')
for i in range(len(lis)):
print(lis[i])
lis[i]=lis[i]+2
[Link](2)
[Link](1,11)
[Link](6,12)
print('List elements after manipulation are :')
for i in range(len(lis)):
print(lis[i])
34 L=[1,2,3,4]
for x in L:
[Link](x)
print(L)
35 List1[4:44]= 'hello world'
Program Questions:
Heartfulness International School, Omega Branch 2025-2026
1. Write a python program to move all zeros in a user given list, to the starting of the list
and display the same.
2. Write a python program to count the number of even numbers in the user given list.
3. Write a python program to create a new list with all the common elements in two user
given lists.
4. Write a program that reads N number of integer values in a list Marks and performs
the following operations on this list and print accordingly (Assume maximum marks
is 100):
(i) Print the average marks achieved by the students
(ii) Number of students who have go more than 90
(iii) Maximum marks achieved by the student(s)
(iv) Number of students who have failed (marks achieved less than 33)
5. WAP to display unique and duplicate items of a given list into two different lists.
Input: L1 = [2,7,1,4,9,5,1,4,3,1]
Output: [2,7,1,4,9,5,3]
[1,4]
6. Write a python program to check whether the list contains 2 consecutive common
numbers.
7. WAP that reverses a list of integers (in place).
8. WAP to calculate the sum of integers of the user given heterogeneous list.
9. WAP a program to generate a list of elements of Fibonacci Series.
10. Write a python user defined function to double the elements in an integer list.
11. Write a program to read a list of elements. Modify this list so that it does not contain
any duplicate elements i.e. all elements occurring multiple times in the list should be
deleted and only their first occurrence should be displayed.
12. Write a python program to input a number and count the occurrences of that number
in a user given list (using built-in function and without using built-in function)
13. Write a python program to
a. get roll number, name, and list of marks for n number of students and store
these in a list
b. calculate the total marks for each student and append this into the nested lists
c. display the data as a table
Heartfulness International School, Omega Branch 2025-2026
L1= [500,800,600,200,900]
start =1
Sum =0
for i in range(start,4):
Sum=Sum +L1[i]
print(i, ':', Sum)
mes1=["SKy"]
mes2=["ThE"]
mes3=["LiMIT"]
l1=len(mes1)
l2=len(mes2)
l3=len(mes3)
n=l1+l2+l3
for C in range(1,n):
if(C%4==0):
print(mes2)
l2=l2-1
else:
if (C%3==0):
print(mes1)
l1=l1-1
else:
print(mes3)
Heartfulness International School, Omega Branch 2025-2026
l3=l3-1
x=[[1,2,3],[4,5,6],[7,8,9]]
result=[]
for items in x:
if item % 2==0:
[Link](item)
print(result)
value=[5,4,3,2,1,4]
print(value[0])
print(value[value[0]])
print(value[value[-2]])
print(value[value[value[value[2]+1]]])
t1=['CS','IP','IT']
lst1=t1
new_lst=[]
for i in lst1:
if [Link](i)%2!=0:
new_lst.append([Link]())
elif [Link](i)//2==0:
new_lst.append([Link](len(t1)-1, [Link]()))
l1=[100,900,300,400,500]
start=1
s=0
for c in range(start,4):
s+=l1[c]
print(f'{c}:s')
s+=l1[0]*10
print(s)
txt=['20','50','30','40']
cnt=3
total=0
for c in [7,5,4,6]:
t=txt[cnt]
total=float(t)+c
print(total)
cnt-=1
l=[]
l1=[]
l2=[]
for i in range(6,10):
[Link](i)
Heartfulness International School, Omega Branch 2025-2026
for i in range(10,4,-2):
[Link](i)
for i in range(len(l1)):
[Link](l[i]+l1[i])
[Link](len(l)-len(l1))
print(l2)
def hello():
a=['MDU','MS','CGL','TBM']
k=-1
for i in ['MDU','MS','CGL','TBM'][:-2]:
if i in ['A','E','i','o','u']:
a[k]=['MDU','MS','CGL','TBM'][k]
k+=1
else:
a[k]=['MDU','MS','CGL','TBM'][k]
k-=1
print(a)
hello()
Heartfulness International School, Omega Branch 2025-2026
Heartfulness International School, Omega Branch 2025-2026
Heartfulness International School, Omega Branch 2025-2026
11. Which switching technique breaks data into smaller packets for transmission,
allowing multiple packets to share the same network resources.
Section – B
(II) A) Write a statement to insert all the elements of L2 at the end of L1.
OR
Section – C (3 marks)
print()
Section – D (4 marks)
the issues/problems mentioned in points (I) to (V), keeping in mind the distances
between various blocks/buildings and other given parameters.
I. Suggest the most appropriate location of the server inside the MUMBAI campus.
Justify your choice.
II. Which hardware device will you suggest to connect all the computers within each
building?
III. Draw the cable layout to efficiently connect various buildings within the MUMBAI
campus. Which cable would you suggest for the most efficient data transfer over the
network?
IV. Is there a requirement of a repeater in the given cable layout? Why/ Why not?
Heartfulness International School, Omega Branch 2025-2026
B) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in the MUMBAI campus?
Heartfulness International School, Omega Branch 2025-2026
Chapter 8 - Tuple
- Immutable
- Sequence of elements, separated by comma and enclosed within parenthesis
➢ Syntax check - Which of the following are correctly declared tuples?
a. T=('a', 'b', 'c', 'd')
b. T='a', 'b', 'c', 'd'
c. T=(['a', 'b', 'c', 'd'])
d. T=(['a', 'b', 'c', 'd'],)
e. T=['a', 'b', 'c', 'd']
➢ tuple() - correct
➢ () - correct
➢ T=’t’,
➢ T=5,
➢ Sum((1,2,3,4))
➢ T=tuple((5,))
➢ T=tuple(5)
For example:
Say t=1,2,3
Tuple Operations:
➢ Indexing
➢ Slicing
➢ Concatenation
➢ Repetition
➢ Membership operation (in/not in)
Tuple functions:
➢ len()
➢ count()
➢ index()
Heartfulness International School, Omega Branch 2025-2026
➢ any()
➢ min()/max()
➢ sum()
➢ sorted()
t=(1,2,3)
t1=[Link](t)
t1
(1, 2, 3)
t2=[Link](t)
t=[1,2],'hello'
t1=[Link](t)
t2=[Link](t)
Program:
8. Write a program to arrange all the sub tuples in a tuple in increasing order and store
them in another tuple. Note: All elements are integers.
9. Write a program to accept a number from the user and create a tuple containing all the
factors of the number.
10. Write a program to check whether the 3 user given coordinates (points) form a
triangle or not.
11. Write a program to get 5 subject marks of a student and store it in a tuple. Print the
total and average.
12. Write a program to get 5 subject marks for 5 students and store it in a nested tuple.
Determine the topper from these 5 students.
13. Given a tuple pair ((2,5),(4,2),(9,8),(12,8)), write a function that accepts this tuple as
argument and displays the number of pairs of (a,b) where a and b are even.
tuple = (1, 2, 3, 4)
[Link]( (5, 6, 7) )
print(len(tuple))
(1,2,3) < (1,3,2)
tuple = (1, 2, 3)
print(2 * tuple)
tuple=("Check")*3
print(tuple,type(tuple))
T1 = (1)
T2 = (3, 4)
T1 += 5
print(T1)
print(T1 + T2)
T = (1, 2, 3, 4, 5, 6, 7, 8)
print(T[[Link](5)], end = " ")
print(T[T[T[6]-3]-6])
T='python'
a,b,c,d,e,f=T
Heartfulness International School, Omega Branch 2025-2026
b=d=f='*'
T=(a,b,c,d,e,f)
print(T)
temp=‘’.join(T)
print(temp)
T = (2e-04, True, False, 8, 1.001, True)
val = 0
for x in T:
val += int(x)
print(val)
L = [3, 1, 2, 4]
T = ('A', 'b', 'c', 'd')
[Link]()
counter = 0
for x in T:
L[counter] += int(x)
counter += 1
break
print(L)
A tuple named subject stores the names of Subject=(‘Eng’,’CS’,’Phy’,’Chem’,’Maths’)
different subjects. Write the Python Ls=list(Subject)
commands to convert the given tuple to a [Link]()
list and thereafter delete the last element of print(Ls)
the list. (Board question)
Write the output of the following:
S=1,(2,3,4,5),51,(61,71)
print(len(S))
print(S[2:3])
print(S[-1][0])
print(type(S))
Match
Functions Description
Heartfulness International School, Omega Branch 2025-2026
tuple1=(11,22,33,44,55,66)
lst1=list(tuple1)
new_lst=[]
for i in lst1:
if i%2==0:
new_lst.append(i)
new_tuple=tuple(new_lst)
print(new_tuple)
L=[[1,2],[3,4],[5,6],[7,8]]
for a,b in L:
print(a)
T=1,2
T+=3,4 #what will be in T
T=T+5,6 #what will be in T
Heartfulness International School, Omega Branch 2025-2026
Dictionary
- Mutable
- Unordered collection of key-value pairs
- Each key maps to a value
- Keys are unique and immutable
- Concept of indexing does not exist
- Values are accessed using keys
Syntax:
{key1:value1, key2:value2….}
D={1:’one’,2:’two’} #literal
Dictionary Operations:
➢ Indexing/accessing with keys
➢ Comparison -> equal to and not equal to alone can be checked
➢ Membership operation (in/not in)
• len({'a':1,'b':2}) → 2
• Examples:
• Errors: TypeError if keys are of different, non-comparable types (e.g., mixing str and
int).
sum(<dictionary object>)
• Example:
sorted(<dictionary object>)
• Example:
o sorted({'b':2,'a':1}) → ['a','b']
any(<dictionary object>)
➢ Example:
• any(d) # True
• Returns d[key] if present; otherwise returns default (defaults to None). Does not
change d.
• Example:
o d = {'x': 1}
o print([Link]('x')) # 1
o print([Link]('y')) # None
o print([Link]('y', 0)) # 0
Heartfulness International School, Omega Branch 2025-2026
Tip: Use get when you want to avoid KeyError, and the dictionary to be unchanged.
[Link](key, default=None)
• If key exists, returns its value. If not, inserts key with value default and returns
default. Modifies the dictionary object d.
• Example:
o d = {}
o v = [Link]('a', 100)
o print(v) # 100
o print(d) # {'a': 100}
• setdefault adds keys — use only when you want to ensure the key exists.
• Common use: grouping/aggregation ([Link](k, []).append(x)).
Adding / changing
d[key] = value —> insert or update
• Example:
o d['c'] = 30
Deleting:
del d[key]
• Returns None.
• Example:
[Link](key[, default])
• Removes key and returns its value. If key not present and default provided, returns
default. If not present and no default → KeyError.
• Examples:
o d = {'a':1}
o [Link]('a') # returns 1, d becomes {}
o [Link]('x', 'no') # returns 'no', d unchanged
o [Link]('x') # KeyError
[Link]()
Heartfulness International School, Omega Branch 2025-2026
• Example:
o d = {'a':1, 'b':2}
o [Link]() # ('b',2)
o [Link]() # ('a',1)
o [Link]() # KeyError: 'popitem(): dictionary is empty'
[Link]()
• Example:
o [Link]() # d == {}
Recall:
• Returns a shallow copy of d — top-level mapping copied; nested mutable values are
shared (same objects).
• Example 1:
o d1 = {'x':12}
o d2 = [Link]()
o print(d2) # {'x': 12} -> shallow and true copy
• Example 2:
o d1 = {'x':[1,2]}
o d2 = [Link]()
o d2['x'].append(3)
o print(d1) # {'x': [1,2,3]} -> changed because list was
shared; shallow but not a true copy
• The same function can be also be called as [Link](d)
• For nested structures use [Link]() from copy module.
[Link](other)
• What: Update d with key-value pairs from other (mapping or iterable of pairs). If
key exists, value replaced; otherwise added.
• Examples:
o d = {'a':1}
o [Link]({'b':2}) # {'a':1,'b':2}
o [Link]([('c',3), ('a',100)]) # {'a':100, 'b':2, 'c':3}
• If given an iterable of items that are not 2-length iterables, ValueError may be raised.
[Link](seq, value=None)
• Create a new dict with keys from seq, all mapped to value.
• Example:
o [Link](['a','b'], 0) # {'a':0, 'b':0}
• If value is a mutable object (like a list), the same object is used for every key.
o d = [Link](['x','y'], [])
o d['x'].append(1)
o print(d) # {'x': [1], 'y': [1]} <- surprising to students
object
(values)
dict_obj.items( None Dictionary No Returns key–value pairs as
)
view tuples.
object {'a':1,'b':2}.items() →
(key-value dict_items([('a',1),('b
pairs) ',2)])
dict_obj.pop(ke key Value Yes Removes specified key and
y, default) (required), associated returns its value.
default d={'a':10,'b':20}[Link](
with key
(optional) 'a')→10, d={'b':20}
dict_obj.popite None (key, Yes Removes and returns the last
m() value)
inserted key–value pair.
tuple Raises KeyError if empty.
d={'a':1,'b':2} →
('b',2)
dict_obj.clear( None None Yes Deletes all key–value pairs.
)
d={'a':1,'b':2} → after
[Link]() → {}
dict_obj.get(ke key Value or No Returns the value for a given
y, (required),
default=None)
default key. If the key doesn’t exist,
default
returns default (or None).
(optional) [Link]('a',0)
dict_obj.setdef key Value of Yes (if key Returns the value if key
ault(key, (required),
default=None)
key not found) exists; else adds key with
default
default value.
(optional) d={'x':10}[Link](
'y',20) → adds 'y':20
dict([(key,valu Iterable Dictionary No Creates a dictionary from a
e),…])
(list/tuple) sequence of pairs.
of pairs dict([('a',1),('b',2)])
→ {'a':1,'b':2}
[Link](s Iterable Dictionary No Creates a dictionary from a
eq[,value])
(list/tuple) sequence
dict_obj.update Iterable None Yes Extends a dictionary by
(other_dict)
(list/tuple) inserting key value pairs.
dict() -> takes one argument – (a list of tuples with key and value as elements) – 2 levels of
sequences
Example:
dict([(1,11),(2,22)])
dict(((1,11),(2,22)))
Heartfulness International School, Omega Branch 2025-2026
dict(([1,11],[2,22]))
dict(('aA','bB'))
➔ Keyword arguments
Example:
dict(name='Arjun',cl=11,sec='A')
– with zip() -> to be used when you have 2 separate iterables/sequences, one as keys
and the other as values
Example:
dict(zip('ask','get'))
dict(zip([1,2,3],[11,22,33]))
[Link]() -> takes 2 arguments, the first is the sequence of keys, the second is the
default value for all keys
Example:
d={1:11}
[Link]({2:22})
[Link]([[3,33]])
Heartfulness International School, Omega Branch 2025-2026
Import copy
Recall:
• You only need the • You want a key to exist before using it
value
• You do not want to
modify the dictionary
• Example: counting how
many times a key
appears
Practical Example:
students = {}
[Link]('Grade 11', []).append('Asha')
[Link]('Grade 11', []).append('Rohan')
[Link]('Grade 12', []).append('Meera')
print(students)
In one line:
• KeyError
Heartfulness International School, Omega Branch 2025-2026
• TypeError
• ValueError
o [Link]() with malformed iterable (e.g., elements not of length 2) may raise a
ValueError during unpacking.
• Mutable-default pitfalls
Merging dictionaries
d1 = {'a':1}
d2 = {'b':2}
• Update: [Link](other)
Final tips:
• Encourage trying small experiments in REPL to see keys()/items() views update live.
Recall:
Questions:
1. Consider the dictionary course_info = {'course': 'Computer Science', 'duration': '1 year'}.
Write code to:
course_info[‘instructor’]=’Rossum’
course_info.setdefault(‘instructor’,’Rossum’)
course_info.update({'instructor': 'Rossum’})
2. Given the dictionary product = {'name': 'Laptop', 'brand': 'Dell', 'price': 100000}, use the
get() method to:
Heartfulness International School, Omega Branch 2025-2026
b) Try to retrieve a key called 'discount', which is not present in the dictionary, and return a
default value of 0.
5. Given the dictionary school = {'name': ‘Heartfulness’, 'students': 500}, use setdefault() to:
a) Add a new key 'location' with value 'Chennai’ if it does not already exist.
b) Try to add the key 'name' with value 'Riverdale High' and observe the result.
6. Write the code to create the dictionary {'name': 'Alice', 'age': 25, 'city': 'New York'}, using
dict() constructor.
marks_shallow_copy = [Link]()
marks['Science'].append(100)
print("Original:", marks)
print(list([Link]())[0].startswith(‘a’))
A={}
A[1]=1
A[‘1’]=2
A[1]=A[1]+1
Count=0
for I in A:
Count+=A[I]
print(A,Count)
10. Write a Python program to manage employee details and calculate net salary. Prompt the
user to enter the Employee ID, Employee Name, and Basic Salary. Calculate Salary
Components like HRA (House Rent Allowance): 20% of the basic salary and DA (Dearness
Allowance): 10% of the basic salary. Then calculate the Net Salary which is Basic Salary +
HRA + DA. Store the details in a Dictionary and display the same in a proper format.
11. Write a program that accepts a number from 1 to 12; then displays the corresponding
month in words along with the number of days in the month. (Assume the year is a non-leap
year)
D1={‘Rahul’:56,’Sourav’:98,’Virat’:99}
D2=D1
D2[‘Virat’]=100
print(D1,D2)
a,i=('Mindset','is','Everything'),{1:11}
for i in a:
print(i)
Revision:
3. Fill in the blank, then predict and explain the output for the given code snippet:
l1,l2=['A','B','C'],[]
d=dict.________(l1,l2)
d['A'].append(100)
print(d)
dnew=[Link](‘abc’,500)
id(d[‘a’]);id(d[‘b’]);id(d[‘c’])
4. Predict the output:
text='abracadabraaabbccrr'
counts={}
ct=0
lst=[]
for word in text:
if word not in lst:
[Link](word)
Heartfulness International School, Omega Branch 2025-2026
counts[word]=0
ct+=1
counts[word]+=1
print(counts, lst)
Homework Questions:
1.
2.
3.
Output: {'vowels':['o','i','e'],'consonants':['C','n','s','t','y','h','k']}
4.
student dictionary:
student={1:{'name':'Aishvarya','Total':555},11:{'name':'Aryan','Total':555},
20:{'name':'Yuvan','Total':555}}
Menu Options:
5. Exit
Heartfulness International School, Omega Branch 2025-2026
Chapter 9 - Modules
1. Introduction to Modules
[Link]
[Link]
[Link]
1. Function definitions
2. Class definitions
3. Variables / constants
4. Executable statements
6. Import statements
Hierarchy Summary
In-built modules Already provided by Python math, random, time, datetime, sys
5. Advantages of Modules
4. Improves readability
Every Python file has a built-in variable named __name__. It holds the name of the current
module. Its primary purpose is to allow a code file (a module) to be used both as a reusable
module (imported by other scripts) and as a standalone program (executed directly)
o __name__ == "__main__"
• When you import the module, __name__ takes the module’s name as value instead
of __main__.
Imported Module The actual module name The script is being loaded as a library
(e.g., 'my_module') into another program.
Example:
# [Link]
print(__name__)
Running directly:
python [Link]
Output: __main__
import mymod
Output: mymod
7. Docstring in Modules
A docstring is a multi-line comment that describes the module or function. It is written at the
top of the file.
Example:
"""
Author: ABC
"""
Access using:
import mymod
print(mymod.__doc__)
8. PYTHONPATH
PYTHONPATH is an environment variable in the OS that tells Python where to search for
modules.
1. Current directory
To check:
import sys
print([Link])
Example: [Link]
def add(a,b):
return a+b
import mycalc
Heartfulness International School, Omega Branch 2025-2026
print([Link](2,3))
Folder structure:
mypack/
__init__.py
[Link]
[Link]
print([Link](2,5))
1. import module
✔ Explanation:
✔ Advantages:
Example:
import math
Heartfulness International School, Omega Branch 2025-2026
print([Link](9))
✔ Explanation:
✔ Advantages:
• Cleaner code.
✔ Disadvantages:
• If your program also has a function named sqrt, it will cause naming conflicts.
Example:
print(sqrt(9))
✔ Explanation:
✔ Advantages:
• Cleaner code.
✔ Disadvantages:
• If your program also has a function named sqrt, it will cause naming conflicts.
Example:
print(sqrt(9))
✔ Explanation:
✔ Advantages:
• Easy to type
Example:
import math as m
print([Link](9))
importing a specific function (selective import) and giving that function a nickname (alias).
Example:
print(ms(16)) # [Link]()
Comparison:
Recall:
Heartfulness International School, Omega Branch 2025-2026
Import specific from math sqrt(9) Short, clean Risk of name conflict
name import sqrt
import random
print([Link](1,10))
print(randint(1,10))
Case:
def sqrt(x):
• The local version is called, because Python searches names in this order:
2. Global
3. Module
4. Built-in
So output is:
my sqrt
hi = greet # alias
hi() # calls greet()
Purpose:
✔ Makes long names shorter
✔ Resolves naming conflicts
✔ Improves readability
In-Built Modules
RANDOM MODULE
[Link]()
• Example:
o import random
o print([Link]()) # e.g. 0.37444887175646646
[Link](start=0, stop, step=1)
[Link](a, b)
• Return a random integer N such that a <= N <= b — both ends inclusive.
• Example:
STATISTICS MODULE
These functions expect non-empty numeric iterables (lists, tuples, etc.). They raise
StatisticsError on empty input.
[Link](data)
• Example:
o import statistics
• Errors:
[Link](data)
• Example:
o [Link]([3, 1, 4]) #3
[Link](data)
• Example:
o [Link]([1,2,2,3]) # 2
o [Link]([1,2,3]) #1
Mean The arithmetic average of the data set. Requires summation and
division.
Median The middle value in a data set that has been Requires the data set to be
ordered from least to greatest. sortable.
Mode The value that appears most frequently in a Requires comparability for
data set. counting frequencies.
MATH MODULE
Import with import math. Functions generally operate on real numbers and raise ValueError
for imaginary numbers (e.g., sqrt of negative).
[Link](x)
Heartfulness International School, Omega Branch 2025-2026
[Link](x, y)
• Return x**y as a float (even if both arguments are integers).
• Notes:
o [Link] always returns float.
o The operator ** may return int for integer powers (e.g., 2**3 → 8 as int).
• Example:
o [Link](2, 3) # 8.0
o 2 ** 3 # 8 (int)
[Link](x)
• Float absolute value (always returns a float).
• Example:
o [Link](-3.5) # 3.5
o abs(-3.5) # 3.5 (can return int or float depending on input)
round(x[, ndigits])
• Round x to ndigits decimal places. If ndigits omitted, rounds to nearest integer.
• Tie-breaking: Python uses round-half-to-even (also called “banker’s rounding”).
Heartfulness International School, Omega Branch 2025-2026
o round(2.5) → 2 (2 is even)
o round(3.5) → 4
• Example:
o round(3.14159, 3) # 3.142
o round(2.5) #2
math.log10(x)
• Base-10 logarithm of x.
• Errors: ValueError if x <= 0 (math domain error).
• Example:
o math.log10(100) # 2.0
o math.log10(0) # ValueError: math domain error