0% found this document useful (0 votes)
211 views121 pages

Python Notes Complete

The document outlines the curriculum for a Class 11 Python course, detailing chapters on problem solving, data handling, and various Python data structures such as strings, lists, and dictionaries. It includes key concepts, programming exercises, and the advantages and limitations of Python as a programming language. Additionally, it covers the installation of Python and introduces fundamental programming concepts like variables, data types, and control structures.

Uploaded by

chellakannan699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views121 pages

Python Notes Complete

The document outlines the curriculum for a Class 11 Python course, detailing chapters on problem solving, data handling, and various Python data structures such as strings, lists, and dictionaries. It includes key concepts, programming exercises, and the advantages and limitations of Python as a programming language. Additionally, it covers the installation of Python and introduces fundamental programming concepts like variables, data types, and control structures.

Uploaded by

chellakannan699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON

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

Copying a List ................................................................................................................................... 31


Built-in methods................................................................................................................................ 32
Practice Questions:............................................................................................................................ 32
Chapter 8 - Tuple .................................................................................................................................. 48
Dictionary ............................................................................................................................................. 55
Chapter 9 - Modules.............................................................................................................................. 72
Heartfulness International School, Omega Branch 2025-2026

Chapter 3 Introduction to Problem Solving


Key points:

Steps for problem solving

Algorithms

Decomposition

1. Explain the problem-solving cycle.


2. Determine the output of the following algorithms
a.
Step 1: Start
Step 2: Take length and breadth and store them as L and B
Heartfulness International School, Omega Branch 2025-2026

Step 3: Multiply L and B and store it in area


Step 4: Print area
Step 5: Stop
b.
Step 1: Start
Step 2: Take any number and store it in n
Step 3: Store 1 in I
Step 4: Check I value, if I<=n then go to step 5 else go to step 8
Step 5: Print I
Step 6: Increment I value by 1
Step 7: Go to step 4
Step 8: Stop

Flowcharts:

3. Match the following


Heartfulness International School, Omega Branch 2025-2026

Sample flowchart:

Simple Interest Calculation-

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

Getting Started with Python

About Python
Heartfulness International School, Omega Branch 2025-2026

Python is an open source, object-oriented, high-level, interpreted, general-purpose


dynamic programming language.

• 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 –

Difference between a Compiler and an Interpreter:

Features of Python
Heartfulness International School, Omega Branch 2025-2026

Open Portable
Easy
source

Large
Higly repository
Interactive
efficient of libraries

Expressive Supports Lesser time


GUI

Better Dynamic
Interpreted Garbage typing
collection

Object-
Oriented
Programmi Compatible Extendable
ng

Advantages of Python:

1. Platform independent 4. Lesser learning time


2. Readability 5. GUI Programming
3. Object-oriented programming 6. Availability of Libraries
language

Limitations of Python:

1. Speed
2. Mobile development
3. Runtime Errors

Installing Python

➢ Can be downloaded and installed from [Link]


➢ Python distribution comes with
o Python IDLE
o Python Interpreter
o PIP (Python Package Manager)

Interacting with Python

➢ Python Shell / Command Line Interaction / Interactive mode


Heartfulness International School, Omega Branch 2025-2026

o ‘print’ method
1. Attributes ‘sep’ and ‘end’
➢ Python editor window / Script mode

Additional Notes:

➢ Low-level Programming Language:


o Assembly language (Embedded systems, microcontrollers), Machine code
o Code directly interacts with the hardware
➢ Middle-level Programming Language:
o C, C++
o Procedural Programming Languages
➢ High-level Programming Language:
o Python, Java
o Can be read by humans and needs to be translated into machine code

Language Translators:

1. Compilers - .cc -> exe


2. Interpreters – line by line

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

Chapter 4 Python Data Handling


Key Points:

➢ Python Character Set


o What is character set? - set of characters that the language supports
o Letters: A-Z, a-z
o Digits: 0-9
o Special Symbols:

+ - * / // % ** \ [] ()
{} = != < > <= >= . , ‘‘
““ ; : ! # ? $ & ^ @
_
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

o Identifiers –> names


1. Rules:
• First character of the identifier should always start with a
character or underscore, but not with a digit
• No special characters are allowed except underscore
• Keywords cannot be used as an identifier
• Space is not allowed
Heartfulness International School, Omega Branch 2025-2026

• Upper- and lower-case characters are treated differently


o Keywords –> reserved words

True False None and or not as break pass


continue is if elif else except for while with
return raise assert async del from global await class
finally import lambda yield def try in

>>>from keyword import kwlist


>>>print(kwlist)
['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']

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']

o Literals –> constants


o Operators
o Delimiters
1. Whitespace
2. Punctuation (:;’,.
3. Special Characters&^%$
4. Escape Sequences \t \n \r
➢ Tokens, Expressions and Statements
➢ Exercise 1:
A=1
B=2
C=A+B
print(“The sum of A and B is”,C)
Heartfulness International School, Omega Branch 2025-2026

A=1
B=2
C=A%B

print(“The remainder is:”,c)

Identify the tokens in the above code.

Escape Sequences:

Escape Code Description Example / Output

\n Newline print("Hello\nWorld") → line break

\t Tab print("Hello\tWorld") → adds tab space

\r Carriage return Moves cursor to beginning of line

\b Backspace Removes one character behind

\f Form feed Advances to next page (rare use)

\v Vertical tab Rarely used

➢ 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

o Used mainly in low-level programming and digital


electronics. It starts with the prefix `0b` or `0B`.
o binary = 0b1010 # Represents 10 in decimal
• Octal (Base-8)
o Uses digits from 0 to 7. Prefix is `0o` or `0O`. Not
commonly used but useful in permissions (e.g., file
modes).
o octal = 0o71 # Equals 57 in decimal
• Hexadecimal (Base-16)
o Uses digits 0–9 and letters A–F. Often used in color
codes, memory addresses, etc.
o hex_num = 0xA4 # Equals 164 in decimal
5. Types of Floats
• Floating-point numbers are numbers with decimal points. Python
supports different formats of float values:
o Standard Float
▪ Normal decimal-based float values.
▪ price = 3.14
o Scientific Notation
▪ Used for very large or small numbers. `e` denotes
powers of 10.
▪ sci = 1.2e3 # 1200.0
o Sequences
1. Strings – An ordered sequence of characters enclosed within single
quotes or double quotes
• Types of Strings
o Single-line Strings
▪ Most basic string type using single or double
quotes.
▪ s1 = 'Hello'
▪ s2 = "World"
o Multi-line Strings
Heartfulness International School, Omega Branch 2025-2026

▪ Use triple quotes for strings that span multiple


lines.
• multi = '''Hello
World'''
▪ Use delimiter ‘\’ for strings that span multiple
lines.
• s='hello\
world'
o Raw Strings
▪ Ignore escape sequences like `\n`. Useful for file
paths.
▪ path = r"C:\\Users\\Admin"
• Str() - construct
2. Lists
• An ordered sequence of elements enclosed within []
• These are mutable – i.e. in place change
• Types of Lists
o Homogeneous List
▪ All elements of the same type.
▪ nums = [1, 2, 3, 4]
o Heterogeneous List
▪ Mix of different data types.
▪ mixed = [1, "text", 3.14, True]
o Nested List
▪ List containing other lists.
▪ nested = [[1, 2], [3, 4]]
o Empty List
▪ List with no elements.
▪ empty = []
• list() construct
3. Tuples
• An ordered sequence of elements enclosed within ()
• tuple() construct
Heartfulness International School, Omega Branch 2025-2026

• Tuples are immutable (unchangeable). Useful for fixed data.


• Types of Tuples:
o Homogeneous Tuple
▪ All elements are of the same type.
▪ t = (1, 2, 3)
• Heterogeneous Tuple
o Can contain a mix of data types.
o t = ("Alice", 25, True)
• Nested Tuple
o A tuple containing other tuples.
o nested = ((1, 2), (3, 4))
• Single-element Tuple
o Requires a comma to differentiate from a parenthesis.
o single = (5,)

The concept of indexing for all sequences:

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 Bitwise (~, &, |, ^, <<, >>) -> Not in syllabus


o Relational / Comparison (==, !=, >=, <=, >, <)
1. Can be used Numeric Data types
Operator Meaning Example
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
> Greater than 7 > 2 → True
< Less than 3 < 5 → True
>= Greater than or equal 6 >= 6 → True
<= Less than or equal 4 <= 5 → True

2. Can be used on Sequences


Heartfulness International School, Omega Branch 2025-2026

• Python compares character by character, using Unicode/ASCII


values.
Practice:

P Q P<Q P<=Q P==Q P>Q P>=Q P!=Q


3 3.0
6 4
‘A’ ‘A’
‘a’ ‘A’

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

2. Recall id() function


o Membership operator
1. Used to check if a value exists inside a sequence or mapping.

Operator Description Example


in True if value is present 'a' in 'apple'
not in True if value is not present 2 not in [1, 3, 4]

2. Logical / Boolean (not, and, or)


• Used to combine conditional expressions or evaluate truth
values.
• Python associates with every value, some truth value i.e.,
Python internally categorizes them as true or false.
Values with truth value as Values with truth value as true
false
None
False
0, 0.0, 0j All other values are considered
'', "", [],() true.
{}

3. Numeric Data types


Heartfulness International School, Omega Branch 2025-2026

• print(bool(5 and 3)) # True


• print(bool(0 or 1)) # True
• print(not 0) # True
4. Sequences
• print(bool("")) # False
• print(bool("Python")) # True
• print([] or [1]) # [1]
5. Mappings
• print(bool({})) # False
• print(bool({'a': 1})) # True

Operator Description Example


and True if both are true x > 0 and y < 10
or True if at least one is true x == 0 or y > 5
not Negates the truth value not True → False

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

Operator Meaning Example


= Assign value x=5
+= Add and assign x += 3 → x = x + 3
-= Subtract and assign x -= 2
*= Multiply and assign x *= 4
/= Divide and assign x /= 2
//= Floor divide and assign x //= 2
%= Modulo and assign x %= 3
**= Exponentiate and assign x **= 2

1. 5=x -> wrong usage of assignment operator, syntax error


2. Multiple variables, multiple values
• a, b, c = 1, 2, 3
3. Multiple variables, single value
• x = y = z = 100
Heartfulness International School, Omega Branch 2025-2026

All the operators from highest to lowest precedence:

Precedence Operator(s) Description Example Result


1 (Highest) () Parentheses (grouping, function (2 + 3) * 4 20
calls, tuple creation, etc.)
2 f[...], f(...), [Link] Indexing, slicing, function call, len("hello") 5
attribute reference
3 ** Exponentiation (right- 2 ** 3 ** 2 512
associative)
4 +x, -x Unary plus, Unary minus -5 + 2 -3
5 *, /, //, % Multiplication, Division, Floor 7 // 2 3
Division, Modulo
6 +, - Addition, Subtraction 10 - 4 + 2 8
7 <, <=, >, >= Comparison operators 5 >= 3 True
8 ==, != Equality operators 5 != 5 False
9 is, is not, in, not Identity & Membership "a" in "cat" True
in operators
10 not Logical NOT not (5 > 3) False
11 and Logical AND (5 > 3) and (2 False
< 1)
12 or Logical OR (5 > 3) or (2 < True
1)
13 =, +=, -=, *=, Assignment operators (right- x = 5; x += 2 7
(Lowest) /=, etc. associative)

Evaluate this:

1. 20 > 10 or ‘a’ + 1 >1

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.

2. 10>20 and ‘a’ + 10 < 5

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:

➢ The print() function:


o It is used to display output (text, variables, expressions) to the console.
Heartfulness International School, Omega Branch 2025-2026

o Syntax:

print(object1, object2, ..., sep=' ', end='\\n', file=[Link])

o sep Parameter (Separator):


1. Controls what goes between multiple values.
2. Default separator is space

o end Parameter
1. Controls what is printed at the end of the output.
2. Default is a newline (\n)

➢ The length function len():

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

➢ User defined functions

Function call: function name()


The above image shows the syntax for function definition
o To execute the a user defined function, it must be called i.e., <function_name>()
– this statement must be executed
o There are 4 types of user defined functions based on the arguments and return
value:
1. Type 1 – no arguments, no return
2. Type 2 – with arguments, no return
3. Type 3 – no arguments, with return
4. Type 4 – with arguments, with return

No Arguments, With Arguments, No Arguments, With Arguments,


No return No return With return With return

Input in User Input in User


Input in main Input in Main
defined defined
function function
function function

Output in Output in Output in Output -


User defined User defined Main Main
function function function function

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 Why is Indentation Important in Python?


1. Unlike many other languages, Python uses indentation to define blocks
of code (like inside if, for, while, functions, etc.).
2. Missing or inconsistent indentation will raise an IndentationError.
o Basic Rules:
1. Statements with the same level of indentation belong to the same block.
2. Indentation must be consistent within a block (all lines must use either
spaces or tabs, not both).
3. Python’s standard convention is to use 4 spaces per indentation level.
➢ Debugging
o Syntax error
1. A syntax error occurs when Python code violates the rules of the
language grammar.
2. Python can't even begin to execute such code — it throws an error before
the program runs.

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

• TypeError - Occurs when you apply an operation to an object of


incompatible type.
o >>>’abc’+4 Erroneous code

• ZeroDivisionError - Occurs when dividing a number by zero.


o >>>123/0 Erroneous code
Heartfulness International School, Omega Branch 2025-2026

• ValueError - Occurs when a function receives the right type but


wrong value.
o >>>int(‘abc’) Erroneous code

• IndexError - Occurs when trying to access an index that’s out of


range.
o >>>string_new='Fabulous day'
o >>>len(string_new)
o 12
o >>>string_new[12] Erroneous code

• KeyError - Occurs when a non-existent key is accessed in a


dictionary.
o >>>dictionary={1:'one',2:'two',3:'three'}
Erroneous code
o >>>dictionary[4]
• AttributeError - Occurs when you try to use a method that does
not exist for that data type.
o >>>tuple_old=(1,2,3)
o >>>tuple_old.append(4) Erroneous code
• FileNotFoundError - Occurs when trying to open a non-existent
file.
o File_handle=open(“[Link]”) 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

>>>10+20/2 Erroneous code

20.0
>>>(10+20)/2 Corrected code
15.0

Programs revision:

1. Swap two numbers


a. Using a third variable
b. Without using a third variable
2. Write a program to calculate in how many days a work will be completed by three
persons A, B, and C together, if A, B and C take x, y, and z days respectively to do the
job alone. The formula to calculate the number of days if they work together is
xyz/(xy+yz+xz). Note: x, y, and z are user inputs.

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

Empty Statement or Null (operation) statement

• A statement that does nothing. Eg - pass

Simple Statement

• Any single executable statement. Eg name=input("Enter name:")

Compound Statement

• A set of statements executed as a unit - a code block. Eg if block

Another type of classification


➢ Sequential statements
➢ Conditional statements / selection statements
➢ Iterative statements

Statements
Based on the flow of control

Sequential Conditional Iterative

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

For loop While loop


Heartfulness International School, Omega Branch 2025-2026

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)>

“else” block is optional in conditional statements.


Programs:
1. Check whether a user given number is odd or even
2. Check whether a user given character is a vowel or consonant.
3. Write a python program to input a digit and print it in words.
4. Write a program to determine whether the user given number is one-digit, two-digit,
three-digit or more than 3-digits.
5. Write a python program to determine the result and grade of a student. The program
should print “pass, you have been promoted to the next class”, if the student has
scored more than 40 in each of the subjects and the grade is displayed as per the below
table:
Total Grade
>90 A+
>80 A
>70 B
>60 C
>50 D
Heartfulness International School, Omega Branch 2025-2026

>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

#with If else block

COMPARISON OF MULTIPLE IF STATEMENTS AND SINGLE IF ELIF ELSE BLOCK

What goes wrong in the first scenario?


➢ All if statements are independent.
➢ So when x == 0, both if x == 0 and the else paired with if x > 0 get executed.
➢ In essence:
x == 0 → prints “neither...”
x>0→ skips
else → paired with x > 0 → executes because x > 0 is False
What works in the second scenario?
➢ This is a single decision tree:
o If x == 0 → do first block and skip others
o If not, check x > 0
o If not, go to else
➢ Only one of the blocks will run.
Multiple if Each one checks
blocks independently
if–elif–else Only one block
runs

7. Write a program to find the largest of 3 numbers.


8. Write a program to display 3 user given numbers in descending order.
9. Check whether a user given character is a number, upper case letter, lower case letter or
special character.
Heartfulness International School, Omega Branch 2025-2026

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”)

2. Under what conditions will this code fragment print “Water”?


if temp<32:
print(“Ice”)
elif temp<212:
print(“Water”)
else:
print(“Steam”)

3. Predict the output when x=4


if x>3:
if x>4:
print('A',end=' ')
else:
print('B', end=' ')
elif x<2:
if x!=0:
print('C',end=' ')
Heartfulness International School, Omega Branch 2025-2026

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)

5. What is the output of the following lines of code:


if int(zero)==0:
print('Zero')
elif str(0)=='zero':
print(0)
elif str(0)=='0':
print(str(0))
else:
print("None of the above")

6. Find the errors and correct the below code:


if n==0:
print('Zero')
elif n==1:
print('One')
elif n==2:
print('Two')
else n==3:
print('Three')

7. Predict the output:


x=0
Heartfulness International School, Omega Branch 2025-2026

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()

Menu Driven programs:


1. Display a menu for the user to select from, based on the selection proceed
a. Area of 2D shapes
b. Volume of 3D shapes
c. Basic arithmetic operations
Heartfulness International School, Omega Branch 2025-2026

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.

For Loop Syntax:

for <counter> in <sequence>:

print(<counter>, end=’ ‘)

Example:

s=’omega’# predict the output when s=[1,2,[‘a’,’s’]]

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)

Parameter Required Description


Heartfulness International School, Omega Branch 2025-2026

start Optional An integer number where the sequence starts. Default is 0.

stop Yes An integer number where the sequence ends (exclusive).

step Optional An integer that increments (or decrements) the count. Default is 1.
Can be negative.

Example:

1. To print 10 whole number:

for i in range(10):

print(i)

2. Predict the output

for i in range(2, 6):

print(i)

3. Predict the output:


for i in range(1, 10, 2):
print(i)

Common Usage Errors:

Mistake Explanation Example


Using float Raises TypeError range(0.5, 5)
Step = 0 Raises ValueError range(1, 5, 0)

Test your learning:

S. No. Code Output


1 for i in range(2,8,3):
print(i)
2 for i in range(9,0,1):
print('a')
3 for i in range(1,2):
print('a')

Predict the output:

s = "PYTHON"

for i in range(len(s)):
Heartfulness International School, Omega Branch 2025-2026

print("Index:", i, "Character:", s[i])

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.

Range object operations – augmented concatenation:

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

Predict the output, correct the errors, if any:

for i in range(1, 10, -1):


print('hello')
for i in range(-1,-10):
print(i, end=' ')
for i in range(1, 11):
s=0
Heartfulness International School, Omega Branch 2025-2026

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:

➢ Runs as long as the condition is true


➢ You must manually manage loop control (e.g., incrementing a counter) to prevent
infinite loops

Syntax:
while <condition>:
# code block
Comparison of for and while loops:

Feature for loop while loop


Best for Known iteration count or Unknown count, condition-based
iterable
Structure for var in iterable: while condition:
Loop control Implicit (via iterable) Explicit (you update the
condition)
Risk of infinite Low High (if condition isn’t updated)
loop
Use with iterables Yes No (unless manually indexed)
Heartfulness International School, Omega Branch 2025-2026

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.

For… else… blocks

- 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

While… else… blocks

- 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

Output based questions:

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

Predict the output:


n = int(input("Enter the number of rows: "))

for i in range(1, n + 1):


for j in range(1, i + 1):
print(j, end=" ")
print()
Heartfulness International School, Omega Branch 2025-2026

Chapter 6 – Strings
- Consecutive sequence of characters enclosed within single quotes or double quotes
- immutable

Types
➢ Empty
o ‘’,””,str()
➢ Single line
➢ Multiline

✓ Compare lengths of s1 and s2.


✓ The string s1 is stored as:
✓ "This\nis\nan\nexample\nof\nmultiline\nstring"
✓ Each line break adds 1 extra character (\n).
✓ Whereas in s2, the backslash (\) escapes the newline. Hence, the interpreter
continues the string on the same line. So, the actual string stored in memory is:
✓ "Thisisalsoanexampleofmultilinestring"

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

o By using membership operator


o By indexing – range()
Say, str1='CS is the best'
Notes Code Output
Left to right Traversal, for i in str1: CS is the best
using loop and print(i, end=' ')
membership operator #no equivalent code in while loop
Left to right traversal, for i in range(len(str1)): CS is the best
using loop and range, print(str1[i], end=' ')
positive indexing
Left to right traversal, for i in range(-len(str1),0): CS is the best
using loop and range, print(str1[i], end=' ')
negative indexing
Right to left traversal, for i in range(len(str1)-1, -1, -1): tseb eht si SC
using loop and range, print(str1[i], end=' ')
positive indexing
Right to left traversal, for i in range(-1, -len(str1)-1, -1): tseb eht si SC
using loop and range, print(str1[i], end=' ')
negative indexing

➢ Using while loop


o By indexing – range()
Say, str1='CS is the best'
Notes Code Output
Left to right traversal, using i=0 CS is the best
loop and range, positive while i<len(str1):
indexing print(str1[i], end=' ')
i=i+1
Left to right traversal, using i=-len(str1) CS is the best
loop and range, negative while i<0:
indexing print(str1[i], end=' ')
i=i+1
Heartfulness International School, Omega Branch 2025-2026

Right to left traversal, using i=len(str1)-1 tseb eht si SC


loop and range, positive while i>-1:
indexing print(str1[i], end=' ')
i=i-1
Right to left traversal, using i=-1 tseb eht si SC
loop and range, negative while i>= -len(str1):
indexing print(str1[i], end=' ')
i-=1

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"

For comparison purposes:

Characters Ordinal Values


‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

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

Assume, s=’HELLO WORLD’, answer the following:

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]

Predict the output:


s='welcome to my home'
print(s[3:18])
print(s[2:14:2])
print(s[:7])
print(s[8:-1:-1])
print(s[-9:-15])
print(s[0:9:3])
print(s[9:29:2])
print(s[-6:-9:-3])
print(s[-9:-9:-1])
print(s[8:25:3])
Answers:
Heartfulness International School, Omega Branch 2025-2026

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’

Predict the output:


s='everything is awesome'
print(s[5:13])
print(s[-7:])
print(s[1:-16])
print(s[::-3])
print(s[12:5:1])
print(s[5:-6])
print(s[-1:-8:-1])
print(s[2:8][::-1]+s[-10:-14:-1]+s[-7:-8:-1])
print(s[25::-1])
print(s[-4:3:-1])

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

-21 -20 -19 -18 -17 - - - - -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


16 15 14 13

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’

Test your knowledge:


Given string ‘OMEGA’, write a code to print the below pattern
O
OM
OME
OMEG
OMEGA
CODE:
s='OMEGA'
for i in range(len(s)):
print(s[:i+1])

Quirks:
Will string s=’Hello world’ be the same as s[:]?

String methods and built-in functions:


Syntax:
String_Name.function_name()

Function Syntax Arguments Return


isalpha() [Link]() None Boolean (True/False)
isalnum() [Link]() None Boolean (True/False)
isspace() [Link]() None Boolean (True/False)
isdigit() [Link]() None Boolean (True/False)
istitle() [Link]() None Boolean (True/False)
Heartfulness International School, Omega Branch 2025-2026

swapcase() [Link]() None New String


join () [Link] (iterable) Iterable – string, list, New String
tuple or dictionary
lstrip() [Link](substring) Optional - chars to Left Trimmed String
remove
Default - whitespaces
rstrip() [Link](substring) Optional - chars to Right Trimmed String
remove
Default - whitespaces
startswith() [Link](substring[, prefix, optional start Boolean (True/False)
start[, end]]) & end indices
endswith() [Link](substring[, suffix, optional start Boolean (True/False)
start[, end]]) & end indices
partition() [Link](separator) Separator String Tuple (Before,
Separator, After)
split() [Link](separator, Separator, Optional List of Strings
maxsplit) Maxsplit
replace() [Link](old, new, Old Substring, New Modified String
count) Substring, Optional
Count
upper() [Link]() None Uppercase String
lower() [Link]() None Lowercase String
isupper() [Link]() None Boolean
islower() [Link]() None Boolean
capitalize() [Link]() None Capitalized String
title() [Link]() None Title Case String
strip() [Link](chars) Optional Characters Trimmed String
index() [Link](substring, Substring, Optional Integer
start, end) Start, Optional End
find() [Link](sub[, start[, end]]) - sub: substring to Returns the lowest
search index where substring
- start (optional): is found, or -1 if not
index to start search found
- end (optional):
index to end search
count() [Link](substring, Substring, Optional Integer
start, end) Start, Optional End

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.

3. <string>.count(sub[, start, end])


➢ Explanation: Counts how many times sub occurs in string.
➢ Example:
s = "banana"
print([Link]("a")) #3
print([Link]("a", 2, 5)) # 2 (between index 2 and 5)
➢ Use Case: Counting occurrences (e.g., count vowels, words).

4. <string>.find(sub[, start, end])


➢ Explanation: Returns index of first occurrence of sub, or -1 if not found.
➢ Example:
s = "banana"
print([Link]("na")) # 2
print([Link]("x")) # -1
➢ Use Case: Searching inside text (e.g., search keyword).

5. <string>.index(sub[, start, end])


➢ Explanation: Like find(), but raises error if substring not found.
➢ Example:
s = "banana"
print([Link]("na")) # 2
# print([Link]("x")) # ValueError
➢ Use Case: When substring must exist (e.g., parsing data).

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.

14. <string>.lstrip(), .rstrip(), .strip()


➢ Explanation: Removes spaces →
lstrip() → left
rstrip() → right
strip() → both sides
➢ Example:
s = " hello "
print([Link]()) # "hello "
print([Link]()) # " hello"
print([Link]()) # "hello"
➢ Use Case: Cleaning user input.

15. <string>.startswith(sub[, start, end]) / .endswith(sub[, start, end])


➢ Explanation: Checks if string starts/ends with substring.
➢ Example:
print("Python".startswith("Py")) # True
Heartfulness International School, Omega Branch 2025-2026

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.

18. <string>.replace(old, new, count)


➢ Explanation: Replaces all occurrences of old with new.
➢ Example:
s = "I like Java"
print([Link]("Java", "Python")) # I like Python
➢ Use Case: Text correction, data cleaning.

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.

Key Differences between split() and partition() functions:


Heartfulness International School, Omega Branch 2025-2026

Criteria Split() Partition()


Return Type Returns a list of substrings. Returns a tuple of three elements
(substring before separator,
separator itself, substring after
separator).
Number of Splits Can perform multiple splits, Always performs exactly one
resulting in a list of multiple split, resulting in exactly three
elements. elements in the tuple.
Separator Handling The separator is removed from The separator is retained as the
the resulting substrings. second element in the resulting
tuple.
Default Separator Uses whitespace as the default Requires an explicit separator and
separator if none is provided. does not have a default.

List of Whitespaces:

Character Escape Meaning / Description Example


Sequence
Space "" Regular space "Hello World" (1 space
between words)
Tab "\t" Horizontal tab (moves to "Hello\tWorld" → Hello
next tab stop) World
Newline (Line "\n" Moves cursor to next line "Hello\nWorld" → Hello
Feed, LF) World
Carriage "\r" Returns cursor to start of "Hello\rWorld" → Worldo
Return (CR) line
Form Feed "\f" Advances to the next "Hello\fWorld" (usually looks
(FF) "page" (used in printers, like space or blank area)
very rare today)
Vertical Tab "\v" Moves cursor down to "Hello\vWorld"
(VT) next vertical tab stop
(rarely used)
Non-breaking "\u00A0" Looks like space but "Hello\u00A0World" (keeps
Space (NBSP) prevents line break words together)

Comparison of whitespace and escape sequences:

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

• Whitespace = the thing stored in memory (space, tab, newline, etc.).

• Escape sequence = the code you write in your source file to tell Python to insert that
thing.

Let’s learn about:

Del statement

• del is a Python statement used to delete a variable or even an entire object.

• It does not return anything.

• Once deleted, that name or element cannot be accessed again unless redefined.

• Example 1:

o x = 100

o del x

o # print(x) # NameError, because x no longer exists

• Example 2:

o x = "Python is fun"

o del x

o # print(x) # NameError, because x no longer exists

• Example 3:

o x = "Python is fun"

o del x[:3] # TypeError, 'str' object does not support item deletion

Max()

• Returns the largest element in an iterable.

• Works on numbers or strings (lexicographical order for strings).

Min()

• Returns the smallest element in an iterable.


Heartfulness International School, Omega Branch 2025-2026

• Works on numbers or strings (lexicographical order for strings).

Sum()

• Returns the sum of all numeric elements in an iterable.

• Works only on numbers, not strings.

How min() and max() work on strings

• They compare characters by their Unicode/ASCII values.


• The "smallest" character = lowest Unicode value.
• The "largest" character = highest Unicode value.
• For uppercase vs lowercase → uppercase letters (A–Z) have smaller Unicode values
than lowercase (a–z).

Example:

s = "HelloWorld"

print(min(s)) #H

print(max(s)) #r

PACKING AND UNPACKING OF SEQUENCES

Packing means placing multiple values into a single variable (usually into a sequence like a
tuple, list, or even string).

Example:

s = "HELLO" # Packing characters into a string

Unpacking means extracting individual elements of a sequence into separate variables.

Example 1:

s = "CAT"

a, b, c = s # Unpacking string into variables

print(a, b, c)
Heartfulness International School, Omega Branch 2025-2026

Example 2:

s = "PYTHON"

a, *b, c = s

print(a) # First character P

print(b) # Middle characters as a list ['Y', 'T', 'H', 'O']

print(c) # Last character N

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

2. Predict the output of the below code snippet:


str1='This is Title Case'
print([Link]().isalpha())
(a) True (b) False (c) None (d) Error

Output based questions:


1. ‘11a’.capitalize()
2. ‘11a’.title()
3. ‘Today is another awesome day’.split()
4. What is the value returned by find() function for an unsuccessful search?
5. Name one string function which returns a numeric value.

Predict the output:


1. Predict the output for the below code snippet:
s='omega'
for i in range(len(s)):
print(s[i:])

2. Predict the output for the below code snippet:


i=1
while i < 3:
for j in range(3):
if i * j == 2:
break
print(i, j)
else:
print(f"Inner loop completed for i = {i}")
Heartfulness International School, Omega Branch 2025-2026

i += 1
else:
print("Outer while loop completed successfully")

3. Convert to while loop


s = "hello"
count = 0
for ch in s:
if ch == 'l':
count += 1
print(count)

4. Predict the output


Test='abcdefghi'
Input=4
Input1=int(Input)
Count=0
Newstr=''
while Count<=Input1:
Newstr=Newstr+Test[0:Count]
Test=Test[2:]
Count+=1
print(Newstr, Test, Count, Input1, sep='\n')

5. Predict the output:


string='aabbcc'
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string, count)

6. Predict the output:


S='Python Programming'
L=[Link]()
S=','.join(L)
print(S)

7. Predict the output:


S='Good Morning Madam'
L=[Link]()
for W in L:
if [Link]()==W[::-1].lower():
print(W)
Heartfulness International School, Omega Branch 2025-2026

8. Predict the output:


def makenew(mystr):
newstr=''
count=0
for i in mystr:
if count%2!=0:
newstr+=str(count)
else:
if [Link]():
newstr+=[Link]()
else:
newstr+=i
count+=1
newstr=newstr+mystr[:1]
print("The new string is:", newstr)
makenew('sTUdeNT')

9. Predict the output:


s='welcome2cs'
m=''
n=len(s)
for i in range(0,n):
if s[i]>'a' and s[i]<'m':
m+=s[i].upper()
elif s[i]>='n' and s[i]<='z':
m+=s[i-1]
elif s[i].isupper():
m+=s[i].lower()
else:
m+='&'
print(m)

10. Predict the output:


str1='EXAM2025'
str2=''
i=0
while i<len(str1):
if str1[i]>='A' and str1[i]<='M':
str2+=str1[i+1]
elif str1[i]>='O' and str1[i]<='9':
str2+=str1[i-1]
else:
str2+='*'
i+=1
print([Link](), str2, sep='^^')

11. Predict the output:


d1={'a':10,'b':2,'c':3}
str1=''
for i in d1:
Heartfulness International School, Omega Branch 2025-2026

str1+=str(d1[i])+' '
str2=str1[:-1]
print(str2[::-1])

12. Predict the output:


Msg1='WeLcOME'
Msg2='GUeSTs'
Msg3=''
for I in range(len(Msg2)+1):
if Msg1[I]>='A' and Msg1[I]<='M':
Msg3+=Msg1[I]
elif Msg1[I]>='N' and Msg1[I]<='Z':
Msg3+=Msg2[I]
else:
Msg3+='*'
print(Msg3)

13. Predict the output:


s='Rs.10'
u=''
for i in s:
if [Link]() and [Link]():
u+=''
elif [Link]():
u+=i
else:
u=u
print('$'+u)

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.

> Need not be a proper 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)

9. Write a Python Program to Check if Two Strings are Anagrams.

10. Write a Python program to accept a string and display each word and it’s length.

Class 12 – Board example questions from sample paper – 2024-2025

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)

(A) #THONPROGRAM (B) ##THON#ROGRAM

(C) #THON#ROGRAM (D) #YTHON#ROGRAM

3. Which of the following expressions evaluates to False?

(A) not(True) and False (B) True or False

(C) not(False and True) (D) True and not(False)

4. What is the output of the expression?

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

5. What will be the output of the following code snippet?

message= "World Peace"

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’

7. Give two examples of each of the following:

(I) Arithmetic operators


(II) Relational operators
Heartfulness International School, Omega Branch 2025-2026

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:]

Accessing list elements


o Indexing
1. Positive indices – 0 to length-1 – left to right
2. Negative indices - -1 to -length – right to left

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

➢ Using while loop


o By indexing – range()
Say, L=[1,2,3,’a’,’b’,’c’,’d’,’e’,1.2,[‘CS’,’IP’]]
Notes Code Output
Left to right traversal, using i=0 1 2 3 a b c d e 1.2 ['CS',
loop and range, positive while i<len(L): 'IP']
indexing print(L[i], end=' ')
i=i+1
Left to right traversal, using i=-len(L) 1 2 3 a b c d e 1.2 ['CS',
loop and range, negative while i<0: 'IP']
indexing print(L[i], end=' ')
Heartfulness International School, Omega Branch 2025-2026

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>

For comparison purposes:

Characters Ordinal Values


‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

Concatenation
l1=[1,2,['v','b']]

l2=['r','t',[1,2,[3,4.5]]]
Heartfulness International School, Omega Branch 2025-2026

l1+l2

[1, 2, ['v', 'b'], 'r', 't', [1, 2, [3, 4.5]]]

Repetition
l1=[1,2,['v','b']]

l1*3

[1, 2, ['v', 'b'], 1, 2, ['v', 'b'], 1, 2, ['v', 'b']]

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>

<list_name>[start:stop:step]=<new value> #must be a sequence; can insert or overwrite


depending on the stop value

Practice Questions:

1. Given l1 = [1, 2, 3], l2 = [4, 5], Write the output of l1 + l2.


2. If a = ['x', 'y'] and b = [10, 20, 30], what will be the result of a + b?
3. Given l = [0, 1], Write the output of l * 4.
4. Predict the output:
l = [['a', 'b']]
print(l * 3)
Heartfulness International School, Omega Branch 2025-2026

[['a', 'b'], ['a', 'b'], ['a', 'b']]


5. For nums = [2, 4, 6, 8], check whether:
▪ 4 in nums
▪ 5 not in nums
6. Consider l = ['python', 'java', 'c++'], Write an expression to check if 'Python' (capital P) exists in the
list.
7. Predict the output: [1, 2, 3] < [1, 2, 4]
8. What will be the result of ['a', 'b'] > ['a', 'A']
9. Given l = [10, 20, 30, 40, 50],
▪ What is l[0]?
▪ What is l[-1]?
▪ What happens if you try l[5]?
10. For l = [1, 2, 3, 4, 5, 6, 7, 8],
▪ Write the output of l[2:6]
▪ Write the output of l[:4]
▪ Write the output of l[::-1]
11. Given l = [10, 20, 30, 40],
▪ replace 30 with 35
▪ l[2]=35
▪ replace [20, 35] with [25, 26, 27] using slicing
▪ l[1:3]= [25, 26, 27]#’252627’
12. If l = [1, 2, 3, 4, 5], what happens when you run l[1:4] = [9].

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)

3. Justify the results using lexicographic ordering of lists.


print([10, 20] < [10, 21])
print([10, 20, 30] < [10, 20])

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])

6. Modification with Step Slicing


Heartfulness International School, Omega Branch 2025-2026

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)

8. Why does changing one element in l2 also affect l?


l = [[1, 2], [3, 4]]
l2 = l * 2
l2[0][0] = 99
print(l2)
print(l)

9. Explain why both results are different forms of empty lists.


l = [1, 2, 3, 4, 5]
print(l[2:2])
print(l[3:1])

10. Write Python code (using slicing only, no loops) to reverse the middle part of this list:

l = [10, 20, 30, 40, 50, 60, 70]

Expected Output: [10, 20, 60, 50, 40, 30, 70]

List Comprehension
Syntax:

new_list = [expression for item in iterable if condition]

Example:

l=[‘a’ for x in range(1,11)]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

l=[x for x in range(1,11,2) if x%3==0]

ld

[3, 9]

s='omega'
Heartfulness International School, Omega Branch 2025-2026

l1=list(s)

l2=[x for x in s]

l1

['o', 'm', 'e', 'g', 'a']

l2

['o', 'm', 'e', 'g', 'a']

l3=[s[i] for i in range(0,len(s),2)]

l3

['o', 'e', 'a']

Predict the output:

[y for x in range(3) for y in range(5)]

[[y for y in range(5)] for x in range(3)]

Questions:

1. Create a list with all the multiples of 5 till 100


2. Create a list of vowels.
3. Create a list of even numbers till 50, which are also a multiple of 3.
4. Determine the output:
l=[x for y in ['omega','python'] for x in y]
5. Say, s=’python’, using list comprehension, create the list l, as ['p', 'p', 'y', 'y', 't', 't', 'h',
'h', 'o', 'o', 'n', 'n']
6. In the newly created list from the previous question, predict the output for the below
questions.
['o', 'm', 'e', 'g', 'a', 'p', 'y', 't', 'h', 'o', 'n']
[Link](len(l)*2%3*'Google')
[Link]([Link]([Link]()))
7. Say, words = ["apple", "banana", "cherry"], predict the output:
result = [word[0] for word in words]
print(result)
Heartfulness International School, Omega Branch 2025-2026

8. words = ["one", "two", "three"], create a new list with the string elements reversed
using list comprehension

l = [word[::-1] for word in words]

Copying a List
- Using the built-in method called copy()

lcopy=l #this is not a copy, this is alias

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

2. Suppose l=['abcdef',[1,2,3,4,5,6]], predict the output:


a. l[1][4:]
b. l[0][2:]
c. l[1][4:]+l[0][2:]
d. l[1][4]=1,2,3
e. l[0][1]='12'

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

when one element is changed, all


the other nested elements also
change.
22 l=[10,20,30,40,50,60]
temp=l[0]
for i in range(1,6):
l[i-1]=l[i]
for i in range(0,6):
print(l[i], end='$')
23 l=[6,12,18,24,30]
for i in l:
for j in range(1,i%5):
print(j,'$',end='')
print()
24 l=[1,2,'asd',[1,2,3,'a']]
print(l[1:3])
25 In the above list:
l[1:3]='123344'
print(l)
26 In the above list:
l[1:3]=123344
print(l)
27 lst1=[13,18,11,16,13,18,13]
print([Link](18))
print([Link](18))
[Link]([Link](13))
print(lst1)
28 l1=[1,3,5,7,9]
print(l1==[Link]())
print(l1)
29 l=[12,45,23,78,93,67]
print([Link]()[::-1])
[Link]()
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

Predict the output:

L1= [500,800,600,200,900]
start =1
Sum =0
for i in range(start,4):
Sum=Sum +L1[i]
print(i, ':', Sum)

for name in ['JAYES', 'RAMYA', 'TARUNA','SURAJ']:


print(name)
if name[0]=='T':
break
else:
print('Finshed!')
print('Got it !')

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:

for item in items:

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]()))

print(new_lst, lst1, t1, sep='#')


Heartfulness International School, Omega Branch 2025-2026

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

Class 12 – Board example questions from sample paper – 2024-2025

8. What does the [Link](x) method do in Python?


(A) Removes the element at index x from the list
(B) Removes the first occurrence of value x from the list
(C) Removes all occurrences of value x from the list
(D) Removes the last occurrence of value x from the list
9. Which protocol is used to transfer files over the Internet?
(A) HTTP (B) FTP (C) PPP (D) HTTPS
10. Which network device is used to connect two networks that use different protocols?
(A) Modem (B) Gateway (C) Switch (D) Repeater
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

12. If L1=[1,2,3,2,1,2,4,2, . . . ], and L2=[10,20,30, . . .], then (Answer using builtin


functions only)

(I) A) Write a statement to count the occurrences of 4 in L1.


OR
B) Write a statement to sort the elements of list L1 in ascending order.

(II) A) Write a statement to insert all the elements of L2 at the end of L1.

OR

B) Write a statement to reverse the elements of list L2.

13. A) List one advantage and one disadvantage of star topology.


OR
B) Expand the term SMTP. What is the use of SMTP?

Section – C (3 marks)

14. Predict the output of the following code:


line=[4,9,12,6,20]
for i in line:
for j in range(1,i%5):
print(j,’#’,end=””)

print()

Section – D (4 marks)

15. Event Horizon Enterprises is an event planning organization. It is planning to set up


its India campus in Mumbai with its head office in Delhi. The Mumbai campus will
have four blocks/buildings - ADMIN, FOOD, MEDIA, DECORATORS. You, as a
network expert, need to suggest the best network-related solutions for them to resolve
Heartfulness International School, Omega Branch 2025-2026

the issues/problems mentioned in points (I) to (V), keeping in mind the distances
between various blocks/buildings and other given parameters.

Distance of Delhi Head Office from Mumbai Campus = 1500 km

Number of computers in each of the blocks/Center is as follows:

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

V. A) What would be your recommendation for enabling live visual communication


between the Admin Office at the Mumbai campus and the DELHI Head Office from
the following options: a) Video Conferencing b) Email c) Telephony d) Instant
Messaging
(Or)

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']

Creation and Deletion of a tuple:

Creation of an empty tuple:

➢ tuple() - correct
➢ () - correct

Creation of a tuple with a single element:

➢ T=’t’,
➢ T=5,
➢ Sum((1,2,3,4))
➢ T=tuple((5,))
➢ T=tuple(5)

Creation of a tuple from other sequences – using tuple()

Tuple can be deleted using the del statement.

For example:

Say t=1,2,3

del t Correct usage


del(t) Incorrect usage, del is a statement and not a function, hence
parenthesis should not be used
del t[0] Incorrect usage, tuples are immutable, hence removing a
single element from a tuple will result in error
Heartfulness International School, Omega Branch 2025-2026

Tuple Traversal – similar to other sequences

Tuple Operations:

➢ Indexing
➢ Slicing
➢ Concatenation
➢ Repetition
➢ Membership operation (in/not in)

Tuple Packing and Unpacking:

tuple1=1,2,3,'hello','python' This is packing a tuple

a,b,c,d,e=tuple1 This is unpacking a tuple


print(a,b,c,d,e, sep='\n')
1
2
3
hello
python

Unpacking with asterisk:


t=1,2,3,4,5
a,b,*c=t
a;b;c
1
2
[3, 4, 5]
Adding elements to a tuple – because tuples are immutable, we cannot directly add an
element, however it can be done with concatenation

Tuple functions:

➢ len()
➢ count()
➢ index()
Heartfulness International School, Omega Branch 2025-2026

➢ any()
➢ min()/max()
➢ sum()
➢ sorted()

How does copy of a tuple work:

t=(1,2,3)

t1=[Link](t)

t1

(1, 2, 3)

t2=[Link](t)

id(t), id(t1), id(t2)

(2463713676544, 2463713676544, 2463713676544)

t=[1,2],'hello'

t1=[Link](t)

t2=[Link](t)

id(t), id(t1), id(t2)

(2463758351232, 2463758351232, 2463753150528)

Program:

1. Write a statement to create an empty tuple.


2. Write a program to input ‘n’ numbers one by one and store it in tuple t.
3. Write a statement to create a tuple with single element 50.
4. Write a program to display names starting with vowel from the given tuple:
T=(“India”,”USA”,”Netherlands”,”Switzerland”)
5. Write a program to display the longest sub tuple from the given tuple.
T=((1,2),(45,23),(98,34,67),(34,56,78,9),(“A”,”B”,”C”))
6. Write a program to find the common elements of 2 user given tuples.
7. Write a program to join two user given tuples; common elements to be added only
once.
Heartfulness International School, Omega Branch 2025-2026

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.

Output based questions:

What will be the output of the following programs?

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

Max() Returns the length


of the tuple
Min() Returns the index
value of an element
in the tuple
Count() Returns the largest
element in the tuple
Index() Returns the
smallest element in
the tuple
Len() Returns the
frequency of an
element in the tuple
Predict the output:
T=(10,20,30)
print((T,T,T))
print(T,T,T)
print((T+T+T))
print(T*3)
Predict the output:
T=(1,2,3,4)
print(T*3)
print(T*(3))
print((T)*3)
print(T+(3,))
T1=1,2
T2=3,4
T=(T1,)+(T2,)
print(T,T+T1+T2)
t1=('a')*3
t2=('a',)*3
t3=('a',)+ ('a',)+ ('a',)
print(t1,t2,type(t1),type(t2),len(t1),len(t2))
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….}

Creating and deleting a dictionary:


D={} #empty dictionary

D=dict() #empty dictionary

D={1:’one’,2:’two’} #literal

D={(1,2):’tuple’,[1,2]:’list’} #Incorrect declaration of a dictionary, list cannot be used as a


key

D={1:{2:2}} #correct declaration of key

Dictionary Operations:
➢ Indexing/accessing with keys
➢ Comparison -> equal to and not equal to alone can be checked
➢ Membership operation (in/not in)

Access & membership


d[key] — indexing by key (access)

• Returns the value for key.


• Example:
o d = {'a': 10, 'b': 20}
o print(d['a']) # 10
• KeyError if the key is not present.
• d['c'] # KeyError: 'c'

key in d / key not in d — membership test

• Checks if key exists (only checks keys).


• Example:
• 'a' in d # True
• 10 in d # False (checks keys, not values)
Heartfulness International School, Omega Branch 2025-2026

Built-in functions working on dictionaries (operate on keys by default)


len(<dictionary object>)

• Counts the number of key-value pairs.

• len({'a':1,'b':2}) → 2

min(<dictionary object>) / max(<dictionary object>)

• What: Minimum / maximum key (not value). Keys must be


comparable/homogeneous.

• Examples:

o min({1:'a', 3:'c', 2:'b'}) # 1

o max({'a':1, 'b':2}) # 'b'

• Errors: TypeError if keys are of different, non-comparable types (e.g., mixing str and
int).

sum(<dictionary object>)

• What: Sum of keys (numeric). sum([Link]()) to sum values.

• Example:

o sum({1:10, 2:20}) # 3 -> sum of keys

o sum({1:10, 2:20}.values()) # 30 -> sum of values

• Errors: TypeError if keys not numeric or not addable.

sorted(<dictionary object>)

• What: Returns a list of keys in sorted order.

• Example:

o sorted({'b':2,'a':1}) → ['a','b']

• Tip: sorted([Link](), key=lambda kv: kv[1]) sorts by values.

any(<dictionary object>)

➢ Operate over keys


➢ any(d) True if any key is truthy
Heartfulness International School, Omega Branch 2025-2026

➢ Example:

• d = {0: 'zero', 2:'two'}

• any(d) # True

Function Syntax Arguments Return Comments / Example


len() len(dict_obj) Dictionary Integer Returns the number of key–
value pairs in the dictionary.
len({'a':1,'b':2}) → 2
min() min(dict_obj) Dictionary Smallest Returns the minimum key.
(homogeneou key min({'x':1,'a':2}) →
'a'
s keys)
max() max(dict_obj) Dictionary Largest Returns the maximum key.
(homogeneou key max({'x':1,'a':2}) →
'x'
s keys)
sum() sum(dict_obj) Dictionary Numeri Returns the sum of all
(numeric c sum numeric keys.
keys) sum({1:'a',2:'b',3:'c'}
) → 6
sorted( sorted(dict_obj Dictionary List Returns a list of keys in
) )
(homogeneou ascending order.
s keys) sorted({'x':1,'a':2}) →
['a','x']

Views and iteration


[Link](), [Link](), [Link]()

• Return view objects (dict_keys, dict_values, dict_items) — these act like


sets/lists for iteration and reflect updates to the dictionary.
• Examples:
o d = {'a':1, 'b':2}
o k = [Link]() # dict_keys(['a','b'])
o v = [Link]() # dict_values([1,2])
o it = [Link]() # dict_items([('a',1),('b',2)])
• Can convert to list to index or view snapshot:
o list([Link]())[0]
• Views are dynamic. If you change d, k / v / it reflect change.

Safe access / defaults


[Link](key, default=None)

• 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

• Assigns a value to key. Creates new key if absent, updates if present.

• Example:

o d['c'] = 30

Deleting:
del d[key]

• Removes key from d.

• Returns None.

• KeyError if key not present.

• Example:

o del d['c'] # deletes key

[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

• Removes and returns the last inserted (key, value) pair.

• Raises KeyError if dict empty.

• Example:

o d = {'a':1, 'b':2}
o [Link]() # ('b',2)
o [Link]() # ('a',1)
o [Link]() # KeyError: 'popitem(): dictionary is empty'

[Link]()

• Removes all items — d becomes {}.

• Example:

o [Link]() # d == {}

Recall:

- Write a program to get a dictionary from the user using loop


- Given the dictionary d={1:”Sunday”,2:”Monday,3:”Tuesday”}, write the code to
append the key-value pair 4:’Wednesday’ to the dictionary d.
- Given the dictionary
d={1:”Sunday”,2:”Monday”,3:”Tuesday”,4:”Wednesday”,5:’Friday’}, write a
program to update the value of the key 5 from ‘Friday’ to ‘Thursday’

Copying & mutability


[Link]()

• 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.

Merging & updating


Heartfulness International School, Omega Branch 2025-2026

[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.

Creating / building dicts


dict() constructor

• Builds a dict from:


o No args → empty dict,
o Mapping/iterable of key-value pairs,
o keyword args.
• Examples:
o dict() # {}
o dict([('a',1), ('b',2)]) # {'a':1, 'b':2}
o dict(a=1, b=2) # {'a':1, 'b':2}, keyword argument
o dict({'a':1}) # {'a':1}
• TypeError if given non-iterable or wrong format of elements.

[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

Dictionary functions and methods:

Syntax Arguments Return Changes the Explanation / Example


Value Dictionary?
dict_obj.copy() None Shallow No (creates a Creates a shallow copy of
copy of new the dictionary.
dictionary dictionary) d1={'a':1,'b':2}d2=d1.c
opy() →
d2={'a':1,'b':2}
dict_obj.keys() None Dictionary No Returns a pseudo-list of
view keys.
object {'a':1,'b':2}.keys() →
(keys) dict_keys(['a','b'])
dict_obj.values None Dictionary No Returns a pseudo-list of
()
view values.
{'a':1,'b':2}.values()
→ dict_values([1,2])
Heartfulness International School, Omega Branch 2025-2026

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)])

{1: 11, 2: 22}

dict(((1,11),(2,22)))
Heartfulness International School, Omega Branch 2025-2026

{1: 11, 2: 22}

dict(([1,11],[2,22]))

{1: 11, 2: 22}

dict(('aA','bB'))

{'a': 'A', 'b': 'B'}

➔ Keyword arguments

Example:

dict(name='Arjun',cl=11,sec='A')

{'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'))

{'a': 'g', 's': 'e', 'k': 't'}

dict(zip([1,2,3],[11,22,33]))

{1: 11, 2: 22, 3: 33}

[Link]() -> takes 2 arguments, the first is the sequence of keys, the second is the
default value for all keys

<dict_obj1>.update(<dict_obj2>) -> add a dictionary or nested iterable to another


dictionary.

Example:

d={1:11}

[Link]({2:22})

d => {1: 11, 2: 22}

[Link]([[3,33]])
Heartfulness International School, Omega Branch 2025-2026

d => {1: 11, 2: 22, 3: 33}

To create a deep copy of a dictionary with mutable elements:

Import copy

New_dict_obj=[Link](<original dict object>)

Recall:

Function / Method Description Example Output /


Explanation
len(dict_obj) Returns the number of key– len({'a':1, 'b':2}) 2
value pairs in the dictionary.
min(dict_obj) Returns the minimum key (if min({10:'a', 5:'b', 5
15:'c'})
keys are homogeneous).
max(dict_obj) Returns the maximum key (if max({'a':1, 'c':3, 'c'
'b':2})
keys are homogeneous).
sum(dict_obj) Returns the sum of numeric sum({1:'a', 2:'b', 6
3:'c'})
keys (if keys are numbers).
sorted(dict_obj) Returns a sorted list of keys. sorted({'c':3, ['a', 'b',
'a':1, 'b':2}) 'c']
dict_obj.copy() Returns a shallow copy of the d1={'a':1}; d2 becomes a
d2=[Link]()
dictionary. copy of d1
dict_obj.keys() Returns a view (pseudo-list) of {'x':10, dict_keys([
'y':20}.keys() 'x','y'])
all keys.
dict_obj.values() Returns a view (pseudo-list) of {'x':10, dict_values
'y':20}.values() ([10,20])
all values.
dict_obj.items() Returns a view of key–value {'x':10, dict_items(
'y':20}.items() [('x',10),(
pairs as tuples. 'y',20)])
dict_obj.pop(key[ Removes and returns value for d={'a':1,'b':2}; Returns 1,
,default]) [Link]('a')
given key. If not found, returns dict becomes
default if provided. {'b':2}
dict_obj.popitem( Removes and returns last {'x':10,'y':20}.pop Returns
) item() ('y',20)
inserted (key, value) pair.
dict_obj.clear() Deletes all key–value pairs. d={'a':1}; d becomes {}
[Link]()
dict_obj.get(key[ Returns value for key if d={'x':1}; 0
,default]) [Link]('y',0)
present; else returns default
(default is None).
dict_obj.setdefau Returns value if key exists; d={}; Adds
lt(key[,default]) [Link]('a',10 'a':100
else adds key with default 0)
value.
[Link](seq Creates a new dictionary from [Link](['a', {'a':0,'b':
[,value]) 'b','c'],0) 0,'c':0}
a sequence of keys, assigning
a default value to each.
dict_obj.update(o Adds key–value pairs from d1={'a':1}; {'a':1,'b':
ther_dict) [Link]({'b':2}) 2}
another dictionary or iterable.
Heartfulness International School, Omega Branch 2025-2026

Comparison between get() and setdefault():

Feature get() setdefault()


Purpose Retrieve the value for a key Retrieve the value and set a default value if key is
missing
Modifies No, dictionary remains Yes, adds the key with default value if it doesn’t
dictionary? unchanged exist
Syntax [Link](key, [Link](key, default=None)
default=None)
Return Value of key, or default if key Value of key if exists, otherwise inserts default
value not found and returns it
When to When you only want to read When you want to ensure a key exists, if not add
use? values the key to the dictionary
Examples d = {'a': 1, 'b': 2} d = {'a': 1, 'b': 2}

print([Link]('a')) #1 print([Link]('a', 100)) # 1 (key exists →


print([Link]('c', 0)) #0 original value returned)
print(d) # {'a': 1, 'b': print([Link]('c', 100)) # 100 (key missing →
2} (unchanged) inserted)
print(d) #{'a': 1, 'b': 2, 'c': 100}
Use get() when: Use setdefault() when:

• 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:

get() → Only retrieves, does NOT change dictionary

setdefault() → Retrieves AND adds default key-value if key missing

Errors & common mistakes (summary)

• KeyError
Heartfulness International School, Omega Branch 2025-2026

o Caused by accessing d[key] when key not present, or pop(key) with no


default, or del d[key] with missing key or [Link]() on an empty dictionary.

• TypeError

o Passing non-iterable to dict(), or calling sum() on non-numeric keys, or


min()/max() with mixed incomparable key types.

o Example: tuple(9) → TypeError: 'int' object is not iterable.

• ValueError

o [Link]() with malformed iterable (e.g., elements not of length 2) may raise a
ValueError during unpacking.

• Mutable-default pitfalls

o [Link](..., default_mutable) creates shared mutable value for all keys


(unexpected shared state).

• Shallow copy surprise

o d2 = [Link]() shares nested mutable values between original and copy.

Merging dictionaries

d1 = {'a':1}

d2 = {'b':2}

[Link](d2) # d1 -> {'a':1,'b':2}

[Link]([['c',3],[ 'd',4]]) #d1 -> {'a':1,'b':2,'c':3,'d':4}

Quick reference (cheat-sheet)

• Access: d[key] → KeyError if missing

• Safe access: [Link](key, default) → returns default if missing

• Ensure key exists: [Link](key, default) → inserts if missing


Heartfulness International School, Omega Branch 2025-2026

• Remove: del d[key], [Link](key[,default]), [Link]()

• Inspect: [Link](), [Link](), [Link]() → view objects

• Copy: [Link]() → shallow copy

• Build: dict(), [Link](seq, default)

• Update: [Link](other)

• Builtins: len(d), min(d), max(d), sum(d), sorted(d)

Final tips:

• Always prefer get() when reading optional keys to avoid KeyError.

• Understand the difference between d2 = d1 (alias) and d2 = [Link]() (shallow copy).

• Demonstrate fromkeys with immutable vs mutable defaults to expose the shared-


reference pitfall.

• Encourage trying small experiments in REPL to see keys()/items() views update live.

Recall:

1. Methods to fetch value from the dictionary


2. Methods to update the value in a dictionary
3. Methods to write new key-value pair into a dictionary

Questions:

1. Consider the dictionary course_info = {'course': 'Computer Science', 'duration': '1 year'}.
Write code to:

a) Add a new key-value pair 'instructor': 'Rossum’.

course_info[‘instructor’]=’Rossum’

course_info.setdefault(‘instructor’,’Rossum’)

course_info.update({'instructor': 'Rossum’})

b) Remove the key 'duration' from the dictionary.

2. Given the dictionary product = {'name': 'Laptop', 'brand': 'Dell', 'price': 100000}, use the
get() method to:
Heartfulness International School, Omega Branch 2025-2026

a) Retrieve the price of the product.

b) Try to retrieve a key called 'discount', which is not present in the dictionary, and return a
default value of 0.

3. Consider the dictionary city_info = {'name': 'Delhi', 'country': 'India', 'population':


19000000}. Write code to:

a) Create a list of all keys in the dictionary.

b) Create a list of all values in the dictionary.

c) Create a list of all key-value pairs as tuples.

4. You are given two dictionaries:

dict1 = {'a': 1, 'b': 2}

dict2 = {'b': 3, 'c': 4}

Write code to merge dict2 into dict1.

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.

7. Observe the below code and predict the output:

marks = {'Math': 95, 'Science': [88, 92]}

marks_shallow_copy = [Link]()

marks['Science'].append(100)

print("Original:", marks)

print("Shallow Copy:", marks_shallow_copy)

print(list([Link]())[0].startswith(‘a’))

8. Create using dictionary comprehension:


Heartfulness International School, Omega Branch 2025-2026

> {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

9. Predict the output:

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)

For example: If input is 4, the output is April and 30.

12. Predict the output:

D1={‘Rahul’:56,’Sourav’:98,’Virat’:99}

D2=D1

D2[‘Virat’]=100

print(D1,D2)

13. Menu – driven dictionary program – student, employee, etc

14. What would be the output of the below code:


Heartfulness International School, Omega Branch 2025-2026

a,i=('Mindset','is','Everything'),{1:11}

for i in a:

print([Link](i), end=' ')

print(i)

Revision:

1. Predict the output. In case of error, give reason:


a) T1=('India', 'Switzerland') b) d1,d2,d3={'axe':'tree'},{'scissors':'cloth'},
T2=('Sri Lanka') {'knife':'fruit'}
print(T1+T2) print([Link](d2).update(d3))

2. Predict the output for the below code snippets:


a) t='python',3.11,'students b) dict1=dict([{'A':30,'B':30,'C':27}.popitem()])
database' print(dict1)
a,b,*c=t
print(a,b,c,sep='&')

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.

Input:[121, 134, 15651, 898, 456, 34, 9]

Output:{'Palindrome':[121, 15651, 898, 9], 'Not a Palindrome':[134, 456, 34]}

2.

Input: 'Consistency is the key'

Output: {'vowel words':1, 'consonant words':3}

3.

Input: 'Consistency is the key'

Output: {'vowels':['o','i','e'],'consonants':['C','n','s','t','y','h','k']}

4.

Menu Driven Program:

student dictionary:

student={1:{'name':'Aishvarya','Total':555},11:{'name':'Aryan','Total':555},
20:{'name':'Yuvan','Total':555}}

1. Total marks scored by Aryan – dictionary fn


➢ Student[11].get(‘Total’)
1. Add another record for roll number 17, name is Shakthi, marks in 555 –
dicyionary fn
[Link](17,{‘name’:’Shakthi’,’marks’:555})
[Link]({17: {‘name’:’Shakthi’,’marks’:555}})
2. Yuvan’s total to be changed from 555 to 580
Student[20][‘Total’]=580
3. [555,555,555,580] – list comprehension
Heartfulness International School, Omega Branch 2025-2026

[student[i][‘Total’] for I in student]


Student[17].popitem()[0]
>{‘name’:’Shakthi’,’marks’:555}.popitem()[0]
> (’marks’,555)[0]
> ‘marks’

Menu Options:

1. Add student record

2. Edit student record

3. Delete student record

4. Display student data as a table

5. Exit
Heartfulness International School, Omega Branch 2025-2026

Chapter 9 - Modules

1. Introduction to Modules

A module in Python is simply a file that contains Python code.


A module allows us to organize large programs, reuse code, and avoid rewriting the same
logic.

Example of a module file name:

[Link]

[Link]

[Link]

2. What Can be Included in a Module?

A module may contain:

1. Function definitions

2. Class definitions

3. Variables / constants

4. Executable statements

5. Docstrings (optional documentation)

6. Import statements

7. Loops, conditionals, exception handling

Example module content ([Link]):


Heartfulness International School, Omega Branch 2025-2026

3. Module vs Library vs Package

Feature Module Library Package

Meaning A single .py A collection of modules / A folder containing modules +


file packages __init__.py file

Example [Link] NumPy library email package

Size Small Larger Medium–Large

Use Group related Provide many features Organize modules


code

Analogy Component Description


Module A single Tool (e.g., a This is the fundamental unit. It's a single file
[Link]) or containing code (.py extension) that defines functions,
Blueprint (a single .py classes, and variables.
file).
Package A Toolbox (e.g., a This is a directory containing multiple related
"Plumbing" folder). Modules. It must contain an __init__.py file (often
empty) to be recognized as a package by Python.
Packages are used to organize modules hierarchically.
Heartfulness International School, Omega Branch 2025-2026

Library A Set of Toolboxes or This is a general term for a collection of related


a Complete Packages (or modules) that provide specific
Workshop. functionality. Examples: NumPy for numerical work,
or Pandas for data analysis.

Hierarchy Summary

• Collection of codes/functions -> Module (.py file)

• Collection of Module(s) -> Package (folder with __init__.py)

• Collection of Package(s) & Modules -> Library (High-level functional collection)

4. In-Built Module vs User-Defined Module

Type Meaning Examples

In-built modules Already provided by Python math, random, time, datetime, sys

User-defined modules Created by programmers [Link], [Link]

5. Advantages of Modules

1. Reusability – Use the same code in multiple programs.

2. Better organization – Divides big program into smaller parts.

3. Avoids repetition – Write once, use many times.

4. Improves readability

5. Encourages teamwork – Multiple programmers can work on separate modules.

6. Easy maintenance – Errors are easier to locate.

6. Special Variable: __name__

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)

• When you run a module directly, its value is


Heartfulness International School, Omega Branch 2025-2026

o __name__ == "__main__"

• When you import the module, __name__ takes the module’s name as value instead
of __main__.

Execution Context Value of __name__ Significance

Direct Execution '__main__' The script is being run as the primary


program.

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__

Importing in another file:

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:

"""

This module contains arithmetic functions.


Heartfulness International School, Omega Branch 2025-2026

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.

Python searches in:

1. Current directory

2. Standard library directory

3. Paths listed in PYTHONPATH

To check:

import sys

print([Link])

9. How to Create a Module

1. Open any text editor / IDE.

2. Write Python code.

3. Save it with a .py extension.

Example: [Link]

def add(a,b):

return a+b

Use it in another program:

import mycalc
Heartfulness International School, Omega Branch 2025-2026

print([Link](2,3))

10. How to Create a Package

A package is a folder containing modules + a special file:

Folder structure:

mypack/

__init__.py

[Link]

[Link]

__init__.py may be empty.


It tells Python: “This folder is a package.”

Importing from a package:

from mypack import mathops

print([Link](2,5))

11. Importing Modules

1. import module

✔ Explanation:

• The entire module is imported.

• To call functions, you must use module_name.function_name().

✔ Advantages:

• Prevents naming conflicts.

• Makes it clear which module a function comes from.

Example:

import math
Heartfulness International School, Omega Branch 2025-2026

print([Link](9))

2. from module import name

✔ Explanation:

• Only the specific name(s) you mention are imported.

• Function can be used directly, without module prefix.

✔ Advantages:

• Cleaner code.

• Loads only required functions—memory efficient.

✔ Disadvantages:

• If your program also has a function named sqrt, it will cause naming conflicts.

Example:

from math import sqrt

print(sqrt(9))

3. from module import *

✔ Explanation:

• Only the specific name(s) you mention are imported.

• Function can be used directly, without module prefix.

✔ Advantages:

• Cleaner code.

• Loads only required functions—memory efficient.

✔ Disadvantages:

• If your program also has a function named sqrt, it will cause naming conflicts.

Example:

from math import *


Heartfulness International School, Omega Branch 2025-2026

print(sqrt(9))

4. import module as alias

✔ Explanation:

• Gives the module a nickname (alias).

• Useful when module names are long.

✔ Advantages:

• Short, clean code

• Easy to type

• Still avoids naming conflicts

Example:

import math as m

print([Link](9))

5. from module import function as alias

importing a specific function (selective import) and giving that function a nickname (alias).

Example:

from math import sqrt as ms

print(ms(16)) # [Link]()

Comparison:

import module from module import name

Requires prefix: [Link]() Can call directly: func()

Entire module loaded Only specific components loaded

Less namespace pollution May cause name conflicts

Recall:
Heartfulness International School, Omega Branch 2025-2026

Import Type Syntax How to Call Pros Cons


Function

Import whole import math [Link](9) Safe, clear Longer to type


module

Import specific from math sqrt(9) Short, clean Risk of name conflict
name import sqrt

Import from math sqrt(9) Very short Not recommended;


everything import * confusion

Aliased import import math as [Link](9) Short + safe None (recommended)


m

12. Calling Functions from a Module

If imported using import:

import random

print([Link](1,10))

If imported using from:

from random import randint

print(randint(1,10))

13. What if Function Names Conflict?

Case:

from math import sqrt

def sqrt(x):

return "my sqrt"

• The local function overrides the imported function.


Heartfulness International School, Omega Branch 2025-2026

• The local version is called, because Python searches names in this order:

1. Local (current function or program)

2. Global

3. Module

4. Built-in

So output is:

my sqrt

14. Function Aliasing

Function aliasing means giving another name to the same function.


Aliasing during import
from math import sqrt as root
print(root(25))

Aliasing a function inside your program


def greet():
print("Hello")

hi = greet # alias
hi() # calls greet()

Purpose:
✔ Makes long names shorter
✔ Resolves naming conflicts
✔ Improves readability

In-Built Modules

RANDOM MODULE

• Used to generate pseudo-random numbers.


• Non-deterministic approach

[Link]()

• Returns a pseudo-random floating-point number in the interval [0.0, 1.0) (0 inclusive,


1 exclusive).
Heartfulness International School, Omega Branch 2025-2026

• Example:
o import random
o print([Link]()) # e.g. 0.37444887175646646
[Link](start=0, stop, step=1)

• Returns a randomly selected element from range(start, stop, step).


• stop excluded.
• Example:
o [Link](1, 10, 2) # picks from 1,3,5,7,9
o [Link](5) # picks from 0,1,2,3,4
• Error: ValueError if the range is empty.

[Link](a, b)

• Return a random integer N such that a <= N <= b — both ends inclusive.
• Example:

[Link](1,6) # simulates a fair 6-sided die

STATISTICS MODULE

Used for basic statistics.

These functions expect non-empty numeric iterables (lists, tuples, etc.). They raise
StatisticsError on empty input.

[Link](data)

• Arithmetic mean (average).

• Example:

o import statistics

o [Link]([10, 20, 30]) # 20

• Errors:

o StatisticsError on empty data.

o If input contains non-numeric items → TypeError.

[Link](data)

• Middle value when data is sorted.


Heartfulness International School, Omega Branch 2025-2026

o If odd number of values → middle item.

o If even → arithmetic mean of two middle values (may be float).

• Example:

o [Link]([3, 1, 4]) #3

o [Link]([1, 2, 3, 4]) # (2 + 3) / 2 = 2.5

• Errors: StatisticsError on empty input.

[Link](data)

• Returns the single most common value.

• Example:

o [Link]([1,2,2,3]) # 2

o [Link]([1,2,3]) #1

• Errors: StatisticsError on empty input.

Term Definition Mathematical Requirement

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

• Square root of x (non-negative).


• Always returns a float
• Errors: ValueError: math domain error if x < 0.
• Example:
o [Link](25) # 5.0

[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)

Trigonometric functions: [Link](x), [Link](x), [Link](x)


• Standard trig functions; argument in radians.
• Examples:
o [Link]([Link](30)) # 0.5
o [Link](0) # 1.0

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

[Link](x) and [Link](x)


• Explanation:
o ceil(x) → smallest integer >= x
o floor(x) → largest integer <= x
• Examples:
o [Link](4.2) # 5
o [Link](4.7) # 4

[Link] and math.e


• Mathematical constants π and e (floating point).
• Examples:
o [Link] # 3.141592653589793
o math.e # 2.718281828459045

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

You might also like