0% found this document useful (0 votes)
3 views176 pages

Class 11th Python

The document is a comprehensive guide for Class 11 Bihar Board students on the chapter 'Getting Started with Python,' covering essential topics such as Python features, keywords, identifiers, variables, data types, operators, and input/output. It includes structured explanations, examples, and exam-focused tips to ensure thorough understanding and preparation for exams. The guide emphasizes important points and provides sample questions to aid in exam readiness.

Uploaded by

islamsaheb9523
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)
3 views176 pages

Class 11th Python

The document is a comprehensive guide for Class 11 Bihar Board students on the chapter 'Getting Started with Python,' covering essential topics such as Python features, keywords, identifiers, variables, data types, operators, and input/output. It includes structured explanations, examples, and exam-focused tips to ensure thorough understanding and preparation for exams. The guide emphasizes important points and provides sample questions to aid in exam readiness.

Uploaded by

islamsaheb9523
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

This shared conversation is generated by AI, for

reference only.

File
Shared files can't be displayed

Explain and Teach me this chapter


without leaving a tiny point to miss in
the upcoming exam of mine of class
11th bihar board.
my medium language is English even if
it is bihar board so no need to include
hindi.

Thought for 5 seconds

We need to explain and teach the chapter "Getting


Started with Python" comprehensively, covering all
sections, concepts, and details, ensuring nothing is
missed for a Class 11 Bihar Board exam. The chapter
includes: introduction, features, working with Python,
interactive vs script mode, keywords, identifiers,
variables, comments, data types (numbers, sequences,
sets, none, mapping, mutable/immutable), operators
(arithmetic, relational, assignment, logical, identity,
membership), expressions, precedence, statements,
input/output, type conversion (explicit and implicit),
debugging (syntax, logical, runtime errors). Also
includes examples, exercises, case study,
documentation tips.

We need to present it in a structured, easy-to-


understand manner, covering all topics with examples,
and highlight important points for exams. Since the user
is preparing for Bihar Board Class 11, we should align
with the typical exam pattern: definitions, differentiate,
output questions, error identification, program writing.

Let's break down the chapter into sections and provide


explanations, key points, and sample
questions/answers. We'll also include tips for exam.

I'll create a comprehensive guide.

Complete Guide to Chapter 5:


Getting Started with Python

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with explanations, examples, and exam-
focused points. No concept is left out. Read
carefully and practice the programs and questions.
5.1 INTRODUCTION TO PYTHON

What is a Program and Programming


Language?

Program: An ordered set of instructions to carry


out a specific task.

Programming Language: Language used to write


programs.

Machine Language: Low-level language of 0s


and 1s (computer understands directly).

High-Level Language: Easier for humans (e.g.,


Python, C++, Java). Needs translation.

How Python Works?

Python uses an interpreter (not compiler).

Interpreter: Translates and executes one


statement at a time. Stops if error occurs.

Compiler: Translates entire program at once, then


executes. Generates error list after full scan.

Features of Python (Important for Exam)

High-level language
Free and open source

Interpreted

Easy to understand (clear syntax, simple


structure)

Case-sensitive (e.g., num and Num are different)

Portable and platform independent

Rich library of predefined functions

Used in web development

Uses indentation for blocks (no curly braces)

Working with Python

Need Python interpreter installed or online


interpreter.

Interpreter = Python shell.

Prompt: >>> indicates ready to take instructions.

5.1.3 Execution Modes

(A) Interactive Mode

Type statements directly at >>> prompt.


Executes immediately, shows result.

Advantage: Quick testing of single lines.

Disadvantage: Cannot save code for future use.

(B) Script Mode

Write multiple instructions in a file (extension .py


).

Save and run the file.

Can be executed by typing filename or using


IDLE's Run menu.

Advantage: Code can be saved and reused.

Example Program 5-1:

python

# Program to show print statement


print("Hello, Python!")

Output: Hello, Python!

5.2 PYTHON KEYWORDS


Keywords: Reserved words with special meaning.
Cannot be used as identifiers.

Python is case-sensitive, so keywords must be


written exactly as given.

List of keywords (from PDF):


False , class , finally , is , return , None ,
continue , for , lambda , try , True , def ,

from , nonlocal , while , and , del , global ,


not , with , as , elif , if , or , yield ,

assert , else , import , pass , break , except ,


in , raise .

Exam Tip: Memorize these. They are often asked in


"which are keywords?" or "which identifier is
invalid?".

5.3 IDENTIFIERS

Identifier: Name given to variables, functions, etc.

Rules (must know):

1. Can start with a letter (a-z, A-Z) or underscore


(_).

2. Cannot start with a digit.


3. After first character, can have letters, digits, or
underscore.

4. No special symbols (!, @, #, $, %, etc.).

5. Cannot be a keyword.

6. Can be any length (but keep it meaningful).

Examples:
Valid: marks1 , _total , avg , name123
Invalid: 1st_room (starts with digit), total-Marks
(hyphen not allowed), Hundred$ ($ not allowed),
True (keyword)

Why meaningful names?


Example: avg = (marks1 + marks2 + marks3)/3 is
clearer than a = (b+c+d)/3 .

5.4 VARIABLES

Variable: A name that refers to an object (value


stored in memory).

Assignment statement: Creates variable and


assigns value.

python
gender = 'M'
message = "Keep Smiling"
price = 987.9

No explicit declaration: Variable is created when


first assigned.

Must be assigned before use, else error.

Program 5-2: Display values

python

message = "Keep Smiling"


print(message)
userNo = 101
print('User Number is', userNo)

Output:

text

Keep Smiling
User Number is 101

Program 5-3: Area of rectangle

python
length = 10
breadth = 20
area = length * breadth
print(area)

Output: 200

5.5 COMMENTS

Comments: Notes in code, ignored by interpreter.

Start with # (hash). Everything after # till end of


line is comment.

Purpose: Documentation, explanation, easier


understanding.

Example 5.1:

python

# Variable amount is the total spending on gro


cery
amount = 3400
# totalMarks is sum of marks in all tests
totalMarks = test1 + test2 + finalTest

Program 5-4: Sum of two numbers with comments


python

# Program 5-4
# To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)

Output: 30

5.6 EVERYTHING IS AN OBJECT

In Python, every value (number, string, etc.) is an


object.

Each object has a unique identity (ID) – memory


address.

Use id() to get identity.

Example 5.2:

python

>>> num1 = 20
>>> id(num1)
1433920576
>>> num2 = 30 - 10
>>> id(num2)
1433920576 # same object because value 20 is
reused

Note: For immutable objects, Python may reuse the


same object if value is same (for small integers).

5.7 DATA TYPES

Data type identifies type of value and operations


allowed.

5.7.1 Number

int: integers (e.g., -12, 0, 125)

float: real numbers (e.g., -2.04, 4.0, 14.23)

complex: e.g., 3+4j

bool: subtype of int, values True and False .


True = 1, False = 0.

Check type using type() :

python

>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>

5.7.2 Sequence (ordered collection,


indexed by integer)

String: sequence of characters in quotes.


str1 = 'Hello Friend' , str2 = "452"

Strings are immutable.

List: sequence in square brackets [] , mutable.


list1 = [5, 3.4, "New Delhi", 45]

Tuple: sequence in parentheses () , immutable.


tuple1 = (10, 20, "Apple", 3.4)

5.7.3 Set

Unordered collection of unique items in curly


braces {} .
set1 = {10, 20, 3.14, "New Delhi"}

No duplicates, mutable (but elements themselves


must be immutable).

5.7.4 None
Special data type with single value None .
Represents absence of value.
myVar = None
Not same as False or 0 .

5.7.5 Mapping

Dictionary: key-value pairs in curly braces {} .


dict1 = {'Fruit': 'Apple', 'Climate':
'Cold', 'Price(kg)': 120}
Access via key: dict1['Price(kg)'] gives 120 .

5.7.6 Mutable and Immutable Data Types

Mutable: Can be changed after creation.


Examples: List, Set, Dictionary

Immutable: Cannot be changed. If you try, a new


object is created.
Examples: int, float, complex, bool, string, tuple

Important: When you assign num2 = num1 , both


refer to same object. If you change an immutable, a
new object is created.

Figure 5.8-5.10 Explanation:

num1 = 300 creates object with value 300.


num2 = num1 makes num2 refer to same object.

num1 = num2 + 100 creates new object 400 for


num1 .

5.7.7 Deciding Usage

List: When frequent modifications needed (e.g.,


student names).

Tuple: When data should not change (e.g.,


months of year).

Set: When uniqueness needed (e.g., artefacts).

Dictionary: When fast lookup by key, key-value


pairs (e.g., phonebook).

5.8 OPERATORS

Operators perform operations on operands


(values/variables).

5.8.1 Arithmetic Operators


Operator Operation Example Result

Addition / 5+3 , 8,
+ Concatenatio "Hello"+"Wo "Hell
n rld" "

- Subtraction 5-3 2

Multiplication 15 ,
* 5*3 , "Hi"*3
/ Repetition "HiHi

Division (float
/ 8/4 2.0
result)

Modulus
% 13%5 3
(remainder)

Floor division
// (integer 13//4 3
quotient)

Exponent
** 3**4 81
(power)

5.8.2 Relational Operators

Compare values, return True or False .


Example (
num1=10,
Operator Meaning
num2=0
)

num1 == num2 →
== Equal to
False

num1 != num2 →
!= Not equal to
True

num1 > num2 →


> Greater than
True

num1 < num2 →


< Less than
False

Greater than or num1 >= num2 →


>=
equal True

Less than or num1 <= num2 →


<=
equal False

5.8.3 Assignment Operators


Operator Example Equivalent to

= x = 5 -

+= x += 3 x = x + 3

-= x -= 3 x = x - 3

*= x *= 3 x = x * 3

/= x /= 3 x = x / 3

%= x %= 3 x = x % 3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

5.8.4 Logical Operators

Work with boolean values.

and : True if both True.

or : True if at least one True.

not : Reverses truth value.

Truthiness: In Python, any non-zero number, non-


empty string/list etc. is considered True in logical
context. False , None , 0 , empty collections are
False .

5.8.5 Identity Operators

is : True if two variables refer to same object


(same id).

is not : True if they refer to different objects.

5.8.6 Membership Operators

in : True if value is in sequence.

not in : True if value not in sequence.

5.9 EXPRESSIONS

Expression: Combination of constants, variables,


and operators that evaluates to a value.

Examples: 100 , num , num - 20.4 , 3.0 + 3.14 ,


"Global" + "Citizen"

5.9.1 Precedence of Operators


When multiple operators, precedence determines
order. Higher precedence first.

Precedence Table (High to Low):

1. ** (exponent)

2. ~ , + , - (unary)

3. * , / , % , //

4. + , - (binary)

5. <= , < , > , >= , == , !=

6. = , %= , /= , //= , -= , += , *= , **=
(assignment)

7. is , is not

8. in , not in

9. not

10. and

11. or

Note:

Parentheses () override precedence.

Equal precedence evaluated left to right (except


** which is right to left).

Examples:
20 + 30 * 40 → 20 + 1200 = 1220

20 - 30 + 40 → (20-30)+40 = -10+40 = 30

(20 + 30) * 40 → 50 * 40 = 2000

15.0 / 4 + (8 + 3.0) → 3.75 + 11.0 = 14.75

5.10 STATEMENT

Statement: A unit of code that Python can


execute.

Examples: assignment, print, etc.

python

x = 4 # assignment statement
cube = x ** 3 # assignment
print(x, cube) # print statement

5.11 INPUT AND OUTPUT

input() function

Takes input from user as string.

Syntax: input([prompt])
Example:

python

fname = input("Enter your first name: ")


age = input("Enter your age: ")

age is string "19" .

To get numeric input, convert using int() or


float() :

python

age = int(input("Enter your age: "))

print() function

Outputs to screen.

Syntax:
print(value1, value2, ..., sep=' ',
end='\n')

sep : separator between values (default space)

end : string appended after last value (default


newline)

Examples:

python
print("Hello")
print(10 * 2.5) # 25.0
print("I" + "love" + "my" + "country") # Il
ovemycountry
print("I'm", 16, "years old") # I'm 16 year
s old

Note: + concatenates strings, but if you mix types


with + you'll get error (unless converted). Comma
separates arguments and automatically adds space.

5.12 TYPE CONVERSION

Why needed?

input() returns string. If we want number, we


must convert.

Example: num1 = input("Enter number: ") then


num1 * 2 repeats string, not multiply.

5.12.1 Explicit Conversion (Type Casting)

Programmer forces conversion.


Functions: int() , float() , str() , chr() ,
ord()

Program 5-5: int to float

python

num1 = 10
num2 = 20
num3 = num1 + num2
print(num3, type(num3)) # 30 <class 'int'>
num4 = float(num1 + num2)
print(num4, type(num4)) # 30.0 <class 'floa
t'>

Program 5-6: float to int (loss of fractional part)

python

x = 30.8
y = int(x)
print(y, type(y)) # 30 <class 'int'>

Program 5-7: Error when mixing string and int with


+

python

priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice) # Erro
r! cannot concatenate str and int

Program 5-8: Fix using str()

python

print("The total is Rs." + str(totalPrice))

Program 5-9: String to int

python

icecream = '25'
brownie = '45'
price = icecream + brownie # string concaten
ation
print("Total Price Rs." + price) # Total Pric
e Rs.2545
price = int(icecream) + int(brownie)
print("Total Price Rs." + str(price)) # Total
Price Rs.70

5.12.2 Implicit Conversion (Coercion)

Python automatically converts to avoid loss of


data.

Example: int + float → float


python

num1 = 10 # int
num2 = 20.0 # float
sum1 = num1 + num2 # result is float
print(sum1, type(sum1)) # 30.0 <class 'floa
t'>

Rule: Python promotes to wider type (float is wider


than int).

5.13 DEBUGGING

Debugging: Process of identifying and removing


errors (bugs).

Types of Errors

i) Syntax Errors

Violation of language rules.

Detected by interpreter before execution.

Example: missing parenthesis, misspelled


keyword.

python
print("Hello" # missing closing parenthesi
s → SyntaxError

ii) Logical Errors (Semantic Errors)

Program runs but gives wrong output.

Hard to detect because no error message.

Example: average of 10 and 12 should be


(10+12)/2 but wrote 10+12/2 → result 16
(wrong).

iii) Runtime Errors

Occurs during execution; program crashes.

Example: division by zero, invalid input type.

python

num1 = 10.0
num2 = int(input("num2 = ")) # if user ente
rs 0 → ZeroDivisionError
print(num1/num2)

Program 5-11: Demonstrates runtime error when


user inputs 0 or non-integer.
EXERCISES (with solutions/hints)

We'll go through some important exercises from the


PDF.

1. Invalid identifiers and why

iSerial_no. : Invalid because dot (.) not

allowed.

1st_Room : Invalid because starts with digit.

Hundred$ : Invalid because $ not allowed.

total-Marks : Invalid because hyphen not


allowed.

True : Invalid because it's a keyword.

Others like vTotal_Marks , viiPercentage are


valid.

2. Python assignment statements

a) length = 10; breadth = 20


b) sum = (length + breadth) / 2 (but note: sum
is a built-in function, better use avg )
c) stationery = ['Paper', 'Gel Pen', 'Eraser']
d)
first = 'Mohandas'; middle = 'Karamchand';
last = 'Gandhi'
e)
fullname = first + ' ' + middle + ' ' + last
(or using commas in print but here it's assignment)

3. Logical expressions

a) (20 + -10) < 12 → 10 < 12 → True


b) not (num3 > 24) or num3 <= 24
c) num1 < 6.75 < num2 (assuming num1 < num2)
d) 'middle' > 'first' and 'middle' < 'last'
(string comparison lexicographically)
e) stationery == [] or len(stationery) == 0

4. Add parentheses to make True

Given expression: 0 == 1 == 2 (this is actually


chained comparison: 0==1 and 1==2 → False). To
make True, we need to change grouping: e.g.,
(0 == 1) == 2 ? That evaluates False == 2 →
False. Not possible? Actually we need to see the
original question: "Add a pair of parentheses to
each expression so that it evaluates to True." The
expression in PDF is:
0 == 1 == 2 → without parentheses it's
(0==1) and (1==2) = False.
If we do (0 == 1) == 2 → False == 2 → False.
0 == (1 == 2) → 0 == False → 0 == 0 ? Wait
False is treated as 0 in numeric context? Actually

False == 0 is True. So 0 == (1==2) gives


0 == False which is True because False equals
0? In Python, False is indeed equal to 0. So that
expression becomes True. Yes, 1==2 is False, then
0 == False is True. So answer: 0 == (1 == 2) .

5. Output of code snippets

a)

python

num1 = 4
num2 = num1 + 1
num1 = 2
print(num1, num2)

Output: 2 5 (num1 changed to 2, num2 was


computed earlier as 5)

b)

python
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print(num1, num2)

First line: num1=2, num2=6. Second line: num1


becomes 6, num2 becomes 2+2=4. Output: 6 4

c)

python

num1, num2 = 2, 3
num3, num2 = num1, num3 + 1

This will give error because num3 is used on RHS


before assignment? Actually in second line, num3
on RHS is not defined yet. So NameError. So
answer: Error.

6. Data types

a) Number of months in a year → int (whole


number)
b) Resident of Delhi or not → bool (True/False)
c) Mobile number → string (since it's not used for
arithmetic, might have leading zero)
d) Pocket money → float (could be decimal)
e) Volume of a sphere → float
f) Perimeter of a square → float or int (depending on
side)
g) Name of student → string
h) Address of student → string

7. Output with given values (num1=4,


num2=3, num3=2)

a) num1 += num2 + num3 → num1 = 4 + (3+2)=9 →


print 9
b) num1 = num1**(num2+num3) → 4**(5) = 1024 →
print 1024
c) num1 **= num2 + num3 → same as b) but
assignment, so num1 becomes 1024
d) num1 = '5' + '5' → string concatenation →
'55' → print 55

e) print(4.00/(2.0+2.0)) → 4.0/4.0 = 1.0


f) num1 = 2+9*((3*12)-8)/10 → 2+9*(36-8)/10 →
2+9*28/10 → 2+252/10 → 2+25.2=27.2
g) num1 = 24 // 4 // 2 → left to right: 24//4=6 ,
then 6//2=3 → print 3
h) num1 = float(10) → 10.0
i) num1 = int('3.14') → This will give ValueError
because string with decimal cannot be converted to
int directly. So error.
j) print('Bye' == 'BYE') → False (case-sensitive)
k) print(10 != 9 and 20 >= 20) →
True and True → True

l)
print(10 + 6 * 2 * 2 != 9//4 - 3 and 29 >=
29/9)
First: 10 + 24 = 34 ; 9//4=2 , 2-3=-1 ; 34 != -1
True. Second: 29 >= 3.222 True. So
True and True → True
m) print(5 % 10 + 10 < 50 and 29 <= 29) →
5+10=15 < 50 True; 29<=29 True → True
n) print((0 < 6) or (not(10 == 6) and (10<0)))
→ True or (not False and False) →
True or (True and False) → True or False →

True

8. Categorize errors

a) 25 / 0 → runtime error (division by zero)


b) num1 = 25; num2 = 0; num1/num2 → runtime
error (division by zero)
c) (missing in list) but typical: missing colon →
syntax error.
9. Dartboard problem

Condition: dart hits if distance from center ≤ radius.


Distance = sqrt(x^2 + y^2) ≤ 10.
Expression: x**2 + y**2 <= 10**2 (since sqrt not
needed if comparing squares)
Evaluate:
a) (0,0): 0<=100 → True
b) (10,10): 100+100=200<=100? False
c) (6,6): 36+36=72<=100 → True
d) (7,8): 49+64=113<=100? False

10. Celsius to Fahrenheit

python

c = float(input("Enter temperature in Celsius:


"))
f = c * 9/5 + 32
print("Fahrenheit =", f)
# Boiling point: 100 C → 212 F, Freezing: 0 C
→ 32 F

11. Simple Interest

python
P = float(input("Principal: "))
R = float(input("Rate: "))
T = float(input("Time: "))
SI = (P * R * T) / 100
amount = P + SI
print("Simple Interest =", SI)
print("Amount payable =", amount)

12. Work together days

python

x = float(input("Days for A: "))


y = float(input("Days for B: "))
z = float(input("Days for C: "))
days = (x*y*z) / (x*y + y*z + x*z)
print("Together they complete in", days, "day
s")

13. Arithmetic operations on two


integers

python

a = int(input("Enter first integer: "))


b = int(input("Enter second integer: "))
print("Sum:", a+b)
print("Difference:", a-b)
print("Product:", a*b)
print("Quotient:", a/b)
print("Remainder:", a%b)
print("Floor division:", a//b)
print("Exponent:", a**b)

14. Swap using third variable

python

a = int(input("a: "))
b = int(input("b: "))
temp = a
a = b
b = temp
print("After swap: a =", a, "b =", b)

15. Swap without third variable

python

a = int(input("a: "))
b = int(input("b: "))
a = a + b
b = a - b
a = a - b
print("After swap: a =", a, "b =", b)
16. Repeat string n times

python

n = int(input("Enter n: "))
print("GOOD MORNING " * n)

17. Average of three numbers

python

a = float(input("Enter first: "))


b = float(input("Enter second: "))
c = float(input("Enter third: "))
avg = (a+b+c)/3
print("Average =", avg)

18. Volume of sphere for given radii

python

import math
radii = [7, 12, 16]
for r in radii:
vol = (4/3) * [Link] * r**3
print(f"Radius {r} cm: Volume = {vol:.2f}
cubic cm")
19. Year when user turns 100

python

name = input("Enter your name: ")


age = int(input("Enter your age: "))
year = 2026 + (100 - age) # assuming current
year 2026
print(name + ", you will turn 100 in the yea
r", year)

20. Energy from mass (E=mc^2)

python

m = float(input("Enter mass in kg: "))


c = 3e8 # 3 * 10^8
E = m * c**2
print("Energy =", E, "Joules")

21. Ladder height

Height = length * sin(angle in radians)

python

import math
length = float(input("Length of ladder: "))
angle_deg = float(input("Angle in degrees: "))
angle_rad = [Link](angle_deg)
height = length * [Link](angle_rad)
print("Height reached =", height)

For given values, compute accordingly.

CASE STUDY-BASED QUESTION

Student Management Information System


Write a program to accept student details and
display in given format.

python

# Program to accept and display student detail


s
print("Enter student details:")
name = input("Student Name: ")
roll = input("Roll No: ")
cls = input("Class: ")
section = input("Section: ")
addr1 = input("Address Line 1: ")
addr2 = input("Address Line 2: ")
city = input("City: ")
pin = input("Pin Code: ")
contact = input("Parent's/Guardian's Contact N
o: ")

print("\n" + "="*40)
print("Name of School".center(40))
print("="*40)
print(f"Student Name: {name}\tRoll No: {rol
l}")
print(f"Class: {cls}\tSection: {section}")
print(f"Address: {addr1} {addr2}")
print(f"City: {city}\tPin Code: {pin}")
print(f"Parent's/Guardian's Contact No: {conta
ct}")
print("="*40)

DOCUMENTATION TIPS

State objective at beginning.

Use comments to explain logic.

Meaningful variable/function names.

Proper indentation.

Consistent naming convention (camelCase or


snake_case).

Program name should reflect purpose.

IMPORTANT POINTS FOR EXAM

1. Difference between interpreter and compiler.


2. Interactive vs Script mode.

3. Keywords list – at least know common ones.

4. Identifier rules – be able to identify valid/invalid.

5. Data types – mutable vs immutable examples.

6. Operators – all types, precedence.

7. Type conversion – explicit vs implicit.

8. Errors – syntax, logical, runtime.

9. Input/Output – input() always returns string,


print() with sep and end.

10. Program writing – practice all exercises.

This guide covers every concept from your PDF.


Revise thoroughly and practice writing programs.
Good luck for your exam!

File
Shared files can't be displayed

Same do for this chapter., don't leave


any topic. I want to ace the upcoming
exam. and don't make the explanation
too waggy or too difficult to
understand.
Thought for 7 seconds

Okay, the user has sent another chapter PDF, this time
on "Flow of Control" in Python. They want the same
treatment as the previous chapter: a complete, exam-
focused guide that covers every topic without missing
any point. They specifically ask not to make it "too
waggy or too difficult to understand," meaning they
want concise, clear explanations suitable for their Class
11 Bihar Board exam preparation.

Looking at the history, I provided a very detailed,


structured guide for the previous chapter. The user
appreciated that and is now asking for the same for this
new chapter. Their deep need is to have all key
concepts explained in one place, with important points
highlighted, so they can study efficiently and score well.

The new chapter covers flow of control: sequence,


selection (if, if-else, if-elif-else), indentation, repetition
(for and while loops), break/continue, and nested loops.
I need to structure this similarly to the previous guide. I'll
start with an introduction to the concept, then go
through each topic in the order presented in the PDF. I
should include the programs from the PDF as examples,
explain the syntax clearly, and add exam tips. I also
need to cover the exercise questions briefly or provide
hints, as the previous guide did. The case study and
documentation tips are less critical for exam theory but
should be mentioned.
The response should be in English, as the user
specified. I'll maintain a clear, sectioned format with
bold headings for easy scanning. I'll avoid overly
complex language and keep explanations
straightforward. I'll also incorporate memory aids and
common pitfalls to help with exam preparation.

Complete Guide to Chapter 6:


Flow of Control

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with clear explanations and exam-focused
points. No concept is left out.

6.1 INTRODUCTION

What is Flow of Control?

Flow of control: The order in which statements in


a program are executed.

By default, programs execute in sequence (one


after another, from top to bottom).
Program 6-1 (Sequence execution):

python

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference is", diff)

Output depends on input order.

Control Structures

Python supports two types:

1. Selection (decision making) - if, if-else, if-elif-


else

2. Repetition (looping) - for loop, while loop

6.2 SELECTION (Decision Making)

Why Selection?

Sometimes we need to choose between different


paths based on conditions.
Example: Finding positive difference (subtract
smaller from larger)

Flowchart Concept (Figure 6.2):

Check if num1 > num2

If YES: diff = num1 - num2

If NO: diff = num2 - num1

The if Statement

Syntax:

python

if condition:
statement(s) # indented block

Condition is evaluated.

If True, indented block executes.

If False, block is skipped.

Example 6.1:

python

age = int(input("Enter your age: "))


if age >= 18:
print("Eligible to vote")

The if-else Statement

Syntax:

python

if condition:
statement(s) # executes if condition Tru
e
else:
statement(s) # executes if condition Fal
se

Voting example with else:

python

age = int(input("Enter your age: "))


if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

Program 6-2: Positive difference

python
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference is", diff)

The if-elif-else Statement (Multiple


Conditions)

Syntax:

python

if condition1:
statement(s)
elif condition2:
statement(s)
elif condition3:
statement(s)
else:
statement(s)

Conditions checked in order.

First True condition's block executes.

Rest are skipped.


else is optional.

Example 6.2: Check positive/negative/zero

python

number = int(input("Enter a number: "))


if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")

Example 6.3: Traffic signal

python

signal = input("Enter the colour: ")


if signal == "red" or signal == "RED":
print("STOP")
elif signal == "orange" or signal == "ORANGE":
print("Be Slow")
elif signal == "green" or signal == "GREEN":
print("Go!")

Nested if

if statement inside another if or else block.


Used when multiple conditions depend on each
other.

Program 6-3: Simple Calculator

python

result = 0
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter operator (+, -, *, /): ")

if op == "+":
result = val1 + val2
elif op == "-":
if val1 >= val2: # nested if
result = val1 - val2
else:
result = val2 - val1
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0: # nested if
print("Error! Division by zero")
else:
result = val1 / val2
else:
print("Wrong input")

print("The result is", result)


6.3 INDENTATION

What is Indentation?

Indentation: Leading whitespace (spaces or tabs)


at beginning of a line.

Python uses indentation to group statements into


blocks.

No curly braces {} like other languages.

Rules:

All statements in a block must have same level of


indentation.

Common practice: Use one tab or 4 spaces for


each level.

Incorrect indentation causes SyntaxError.

Program 6-4: Indentation example

python

num1 = 5
num2 = 6
if num1 > num2: # Block 1 starts
print("first number is larger")
print("Bye") # same indentation =
same block
else: # Block 2 starts
print("second number is larger")
print("Bye Bye") # same indentation =
same block

Exam Tip: In exams, they may show code with


wrong indentation and ask if it will run or what error
occurs.

6.4 REPETITION (Looping)

Why Loops?

To repeat a set of statements multiple times.

Without loops: writing 100 print statements for


100 numbers is inefficient.

Program 6-5 (Bad approach - without loop):

python

print(1)
print(2)
print(3)
print(4)
print(5)

Better: Use loop with counter.

Loop Terminology

Control variable: Variable that controls loop


execution.

Iteration: One execution of loop body.

Infinite loop: Loop that never ends (condition


never becomes False).

6.4.1 The for Loop

What is for loop?

Used to iterate over a sequence (range, string,


list, tuple).

Number of iterations is known in advance.

Flowchart (Figure 6.4):

Start → Initialize → Check if items left? → Yes →


Execute body → Next item → Repeat
When no items left → Exit loop

Syntax:

python

for control_variable in sequence:


statement(s) # indented block

Examples:

Program 6-6: Iterate over string

python

for letter in 'PYTHON':


print(letter)

Output: P Y T H O N (each on new line)

Program 6-7: Iterate over list

python

count = [10, 20, 30, 40, 50]


for num in count:
print(num)

Output: 10 20 30 40 50
Program 6-8: Find even numbers

python

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


for num in numbers:
if num % 2 == 0:
print(num, 'is an even number')

The range() Function

Purpose:

Generates a sequence of numbers.

Often used with for loops.

Syntax:

python

range([start], stop[, step])

start (optional): Starting value (default 0)

stop : End value (exclusive - not included)

step (optional): Increment value (default 1)

Examples:

python
range(10) # 0,1,2,3,4,5,6,7,8,9
range(2,10) # 2,3,4,5,6,7,8,9
range(0,30,5) # 0,5,10,15,20,25
range(0,-9,-1) # 0,-1,-2,-3,-4,-5,-6,-7,-8

Note: Use list(range()) to see the generated


numbers.

Program 6-9: Multiples of 10

python

for num in range(5):


if num > 0:
print(num * 10)

Output: 10 20 30 40

6.4.2 The while Loop

What is while loop?

Repeats as long as condition is True.

Number of iterations not necessarily known in


advance.

Condition checked before each iteration.


Flowchart (Figure 6.5):

Start → Check condition → If True → Execute


body → Go back to condition check

If False → Exit loop

Syntax:

python

while test_condition:
statement(s) # indented block

Important: Loop body must eventually make


condition False, else infinite loop.

Program 6-10: First 5 natural numbers

python

count = 1
while count <= 5:
print(count)
count += 1 # increment - crucial!

Program 6-11: Find factors of a number

python
num = int(input("Enter a number: "))
print(1, end=' ') # 1 is factor of e
very number
factor = 2
while factor <= num/2:
if num % factor == 0:
print(factor, end=' ')
factor += 1
print(num) # number itself is
a factor

Note: end=' ' keeps output on same line with


space separator.

6.5 BREAK AND CONTINUE


STATEMENTS

6.5.1 break Statement

What it does:

Immediately terminates the loop.

Program execution continues with statement after


the loop.

Used when we want to exit loop prematurely.


Flowchart (Figure 6.5): When break encountered,
exit loop directly.

Program 6-12: Break example

python

num = 0
for num in range(10):
num = num + 1
if num == 8:
break
print('Num has value', num)
print('Encountered break!! Out of loop')

Output: 1,2,3,4,5,6,7 then break message

Program 6-13: Sum until negative number

python

sum = 0
print("Enter numbers (negative to stop):")
while True: # infinite loop
entry = int(input())
if entry < 0:
break
sum += entry
print("Sum =", sum)

Program 6-14: Check prime number


python

num = int(input("Enter number: "))


flag = 0 # assume prime
if num > 1:
for i in range(2, int(num/2)):
if num % i == 0:
flag = 1 # not prime
break # exit loop early
if flag == 1:
print(num, "is not prime")
else:
print(num, "is prime")
else:
print("Number <= 1, try again")

6.5.2 continue Statement

What it does:

Skips remaining statements in current iteration.

Jumps to next iteration of loop.

Loop does NOT terminate.

Flowchart (Figure 6.6): When continue encountered,


go back to condition check.

Program 6-15: Continue example


python

num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value', num)
print('End of loop')

Output: 1,2,4,5,6 (3 is skipped, but loop continues)

6.6 NESTED LOOPS

What are Nested Loops?

Loop inside another loop.

Can be any combination (for inside for, while


inside while, for inside while, etc.)

No limit on nesting levels.

Program 6-16: Nested for loops demonstration

python

for var1 in range(3):


print("Iteration", var1+1, "of outer loo
p")
for var2 in range(2): # nested loop
print(var2+1)
print("Out of inner loop")
print("Out of outer loop")

Output shows: For each outer iteration, inner loop


runs completely.

Program 6-17: Number pattern

python

num = int(input("Enter a number: "))


for i in range(1, num+1):
for j in range(1, i+1):
print(j, end=" ")
print() # new line

If input 5, output:

text

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Program 6-18: Prime numbers from 2 to 50


python

for i in range(2, 50):


j = 2
while j <= i/2:
if i % j == 0:
break
j += 1
if j > i/2: # no factor found
print(i, "is prime")

Program 6-19: Factorial using for loop inside if-else

python

num = int(input("Enter a number: "))


fact = 1
if num < 0:
print("Factorial not defined for negative
numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num+1):
fact = fact * i
print("Factorial of", num, "is", fact)
EXERCISE SOLUTIONS (with
explanations)

1. Difference between else and elif ?

else : Catches all cases not handled by previous

conditions. Must be last. No condition.

elif : Short for "else if". Has a condition. Can be

multiple. Used when multiple conditions to check.

2. Purpose of range() function?

Generates sequence of numbers. Used in for


loops.

Example: range(5) gives 0,1,2,3,4

3. Difference between break and


continue ?

break : Exits loop completely. Program continues

after loop.

continue : Skips current iteration only. Loop


continues with next iteration.
4. What is infinite loop? Example?

Loop that never ends because condition never


becomes False.

Example:

python

i = 1
while i > 0:
print(i) # i never decreases, runs forev
er

5. Output of program segments:

(i)

python

a = 110
while a > 100:
print(a)
a -= 2

Output: 110,108,106,104,102 (stops when a=100)

(ii) (Missing in PDF but typical question)

python
for i in range(1,4):
for j in range(1,i+1):
print(j, end='')
print()

Output:

text

1
12
123

6. Driving license eligibility

python

name = input("Enter name: ")


age = int(input("Enter age: "))
if age >= 18:
print(name, "is eligible for driving licen
se")
else:
print(name, "is not eligible for driving l
icense")

7. Table of a number
python

n = int(input("Enter number: "))


for i in range(1, 11):
print(n, "x", i, "=", n*i)

8. Minimum and maximum of five


numbers

python

numbers = []
for i in range(5):
num = int(input("Enter number: "))
[Link](num)
print("Minimum:", min(numbers))
print("Maximum:", max(numbers))

9. Leap year check

python

year = int(input("Enter year: "))


if (year % 400 == 0) or (year % 4 == 0 and yea
r % 100 != 0):
print(year, "is leap year")
else:
print(year, "is not leap year")
10. Generate sequence:
-5,10,-15,20,-25... upto n

python

n = int(input("Enter n: "))
for i in range(1, n+1):
if i % 2 == 1: # odd positions ne
gative
print(-5 * i, end=" ")
else: # even positions p
ositive
print(5 * i, end=" ")

11. Sum of series: 1 + 1/8 + 1/27 + ... +


1/n³

python

n = int(input("Enter n: "))
sum = 0
for i in range(1, n+1):
sum = sum + 1/(i**3)
print("Sum =", sum)

12. Sum of digits

python
num = int(input("Enter number: "))
sum_digits = 0
n = num
while n > 0:
digit = n % 10
sum_digits += digit
n = n // 10
print("Sum of digits of", num, "is", sum_digit
s)

13. Palindrome check

python

num = int(input("Enter number: "))


original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if original == reverse:
print(original, "is palindrome")
else:
print(original, "is not palindrome")

14. Pattern printing

(i) Star triangle:


python

for i in range(1,6):
print('*' * i)

(ii) Number triangle:

python

for i in range(1,6):
for j in range(1,i+1):
print(j, end='')
print()

(iii) Inverted triangle:

python

for i in range(5,0,-1):
for j in range(1,i+1):
print(j, end='')
print()

15. Grade calculation

python

percentage = float(input("Enter percentage:


"))
if percentage > 90:
grade = 'A'
elif percentage >= 80:
grade = 'B'
elif percentage >= 70:
grade = 'C'
elif percentage >= 60:
grade = 'D'
else:
grade = 'E'
print("Grade:", grade)

CASE STUDY: SMIS Menu Driven


Program
python

print("=== Student Management Information Syst


em ===")
print("1. Enter marks for 5 subjects")
print("2. Display marks")
print("3. Calculate total and percentage")
print("4. Calculate grade")
print("5. Exit")

marks = []

while True:
choice = int(input("Enter your choice: "))
if choice == 1:
marks = []
for i in range(5):
m = float(input(f"Enter marks for
subject {i+1}: "))
[Link](m)
print("Marks entered successfully!")

elif choice == 2:
if marks:
print("Marks:", marks)
else:
print("No marks entered yet!")

elif choice == 3:
if marks:
total = sum(marks)
percentage = total / 5
print("Total marks:", total)
print("Percentage:", percentage)
else:
print("No marks entered yet!")

elif choice == 4:
if marks:
percentage = sum(marks) / 5
if percentage > 85:
grade = 'A'
elif percentage >= 75:
grade = 'B'
elif percentage >= 50:
grade = 'C'
elif percentage > 30:
grade = 'D'
else:
grade = 'Reappear'
print("Grade:", grade)
else:
print("No marks entered yet!")

elif choice == 5:
print("Exiting...")
break

else:
print("Invalid choice!")

IMPORTANT EXAM TIPS

1. Indentation matters: In exams, they may show


code with wrong indentation. Remember Python
gives error if indentation is inconsistent.

2. Loop conditions: Always ensure while loops have


a way to become False (increment/decrement).

3. range() confusion: Remember range(stop) goes


from 0 to stop-1. range(start, stop) excludes
stop.

4. break vs continue:
break: loop terminates

continue: current iteration skipped, loop


continues

5. Nested loop execution: For each outer iteration,


inner loop runs completely.

6. Common mistakes:

Forgetting colon : after if/for/while

Incorrect indentation

Using assignment = instead of comparison


== in conditions

Infinite loops (no increment in while)

7. Pattern printing logic: Outer loop for rows, inner


loop for columns.

QUICK REFERENCE TABLE

Statement Purpose Example

if x>0:
if Single condition print("positi
ve")
Statement Purpose Example

Two-way if x>0: ...


if-else
decision else: ...

if x>0: ...
if-elif- Multiple
elif x<0: ...
else conditions
else: ...

Loop over for i in


for
sequence range(5):

Loop while
while while x<10:
condition True

Exit loop if x==5:


break
immediately break

Skip to next if x==3:


continue
iteration continue

Generate
range() number range(1,10,2)
sequence

This guide covers everything from your chapter.


Practice writing the programs yourself, understand
the logic, and you'll be ready for your exam! Good
luck!

File
Shared files can't be displayed

now same do for this chapter. exact


same!

Thought for 5 seconds

We need to produce a comprehensive guide for Chapter


7: Functions, similar to the previous ones, covering all
topics, no points missed, clear and concise, exam-
focused. The PDF content includes: Introduction,
Functions, User Defined Functions (with details:
arguments, parameters, default parameters, return
values, flow of execution, multiple returns), Scope of a
variable (global, local, global keyword), Python Standard
Library (built-in functions, modules: math, random,
statistics, importing modules, from statement, creating
own module), and exercises.

We need to explain everything thoroughly, with


examples from the PDF, and also include solutions to
some exercises as needed. Ensure to cover all the
subtopics: advantages of functions, creating user-
defined functions, arguments vs parameters, default
parameters, return statement, flow of execution, multiple
return values (tuple), scope, global keyword, built-in
functions, modules (math, random, statistics), import
and from, creating own module, docstring. Also include
the exercise answers conceptually.

We should structure it like previous chapters: sections


and subsections, with code examples, tables, and
important exam points.

Let's produce the guide.

Complete Guide to Chapter 7:


Functions

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with clear explanations and exam-focused
points. No concept is left out.

7.1 INTRODUCTION

Why Functions?

As programs grow complex, code becomes bulky


and difficult to manage.
Modular programming: Dividing a program into
independent blocks (functions) each with a
specific task.

Benefits:

Readability: Code is organised and easier to


understand.

Reusability: Write once, use multiple times.

Debugging: Easier to find and fix errors in small


blocks.

Team work: Different people can work on


different functions.

Example Problem: Tent manufacturing company


needs to calculate:

1. Area of canvas (cylindrical + conical)

2. Cost of canvas

3. Net amount after 18% tax

Program 7-1 (without functions) is long and less


organised.
Program 7-2 (with functions) is cleaner and
modular.
7.2 FUNCTIONS

What is a Function?

A named group of instructions that accomplishes


a specific task.

Can be called (invoked) from anywhere in the


program.

Helps avoid repetition.

Program 7-2 (modular version):

python

def cyl(h, r):


return 2 * 3.14 * r * h

def con(l, r):


return 3.14 * r * l

def post_tax_price(cost):
tax = 0.18 * cost
return cost + tax

# Main program
h = float(input("Height: "))
r = float(input("Radius: "))
l = float(input("Slant height: "))
csa_cyl = cyl(h, r)
csa_con = con(l, r)
canvas_area = csa_cyl + csa_con
print("Area =", canvas_area)
unit_price = float(input("Cost per m^2: "))
total_cost = unit_price * canvas_area
print("Net amount =", post_tax_price(total_cos
t))

7.2.1 Advantages of Functions

Increases readability

Reduces code length (no repetition)

Increases reusability

Easier debugging

Parallel development possible

7.3 USER DEFINED FUNCTIONS

7.3.1 Creating a User Defined Function

Syntax:

python
def function_name([parameter1, parameter2,
...]):
"""docstring (optional)"""
# statements
[return value]

def keyword starts the function definition.

Function name follows identifier rules.

Parameters (optional) inside parentheses.

Colon : ends the header.

Body is indented.

return is optional.

Program 7-3: Function to add two numbers (no


parameters, no return)

python

def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("Sum =", sum)

addnum() # function call


7.3.2 Arguments and Parameters

Parameter: Variable in function definition that


receives value.

Argument: Actual value passed to function during


call.

Program 7-4: Function to sum first n natural


numbers (with parameter)

python

def sumSquares(n): # n is parameter


s = 0
for i in range(1, n+1):
s += i
print("Sum =", s)

num = int(input("Enter n: "))


sumSquares(num) # num is argument

Important: Argument and parameter refer to the


same object (same id ).

Program 7-5: Demonstrates that changing


parameter inside function creates a new object
(because int is immutable).

python
def incrValue(num):
print("Inside function, before incremen
t:", num, id(num))
num = num + 5
print("Inside function, after increment:",
num, id(num))

number = 8
print("Before call:", number, id(number))
incrValue(number)
print("After call:", number, id(number)) # n
umber unchanged

Output shows that after increment, num gets new


id, but number remains same.

Program 7-6: Function to calculate mean of list (list


passed)

python

def myMean(myList):
total = 0
for i in myList:
total += i
mean = total / len(myList)
print("Mean =", mean)

myList = [1.3, 2.4, 3.5, 6.9]


myMean(myList)
Program 7-7: Factorial function

python

def calcFact(num):
fact = 1
for i in range(num, 0, -1):
fact *= i
print("Factorial =", fact)

n = int(input("Enter number: "))


calcFact(n)

(A) String as Parameters


Program 7-8: Concatenate first and last name

python

def fullname(first, last):


full = first + " " + last
print("Hello", full)

f = input("First name: ")


l = input("Last name: ")
fullname(f, l)

(B) Default Parameters

You can assign default values to parameters.

If argument is missing, default value is used.


Default parameters must come after non-default
parameters.

Program 7-9: Mixed fraction with default


denominator = 1

python

def mixedFraction(num, deno=1):


remainder = num % deno
if remainder != 0:
quotient = num // deno
print(f"Mixed fraction = {quotient} (
{remainder} / {deno} )")
else:
print("Whole number")

n = int(input("Numerator: "))
d = int(input("Denominator: "))
if n > d:
mixedFraction(n, d) # overwrites default
else:
print("Proper fraction")

If called as mixedFraction(9) , deno uses default 1.

Rules:

Default parameters must be trailing:


✅ def func(a, b=5, c=10)
❌ def func(a=5, b, c) – error

Arguments are evaluated before passing:


mixedFraction(num+5, deno+5)

7.3.3 Functions Returning Value

Use return statement to send value(s) back to


caller.

If no return , function returns None (void


function).

Program 7-10: Power function returning value

python

def calcpow(number, power):


result = 1
for i in range(power):
result *= number
return result

base = int(input("Base: "))


expo = int(input("Exponent: "))
ans = calcpow(base, expo)
print(ans)

Possible function types:

1. No argument, no return
2. No argument, with return

3. With argument, no return

4. With argument, with return

7.3.4 Flow of Execution

Python executes from top to bottom.

Function definition is not executed until called.

When function call occurs, control jumps to


function body, executes it, then returns to the
point after the call.

Important: Function must be defined before it is


called, otherwise NameError .

Program 7-11 (error):

python

helloPython() # call before definitio


n → NameError
def helloPython():
print("I love Programming")

Correct order:

python
def helloPython():
print("I love Programming")
helloPython()

Figure 7.5 shows flow of execution with numbered


steps.

Returning Multiple Values

Use tuple to return multiple values.

Automatically packed into a tuple; can be


unpacked on receiving.

Program 7-12: Return area and perimeter of


rectangle

python

def calcAreaPeri(length, breadth):


area = length * breadth
perimeter = 2 * (length + breadth)
return (area, perimeter) # returning tup
le

l = float(input("Length: "))
b = float(input("Breadth: "))
a, p = calcAreaPeri(l, b) # unpacking
print("Area =", a, "Perimeter =", p)
Program 7-13: Traffic light simulation (two
functions)

python

def light(colour):
if colour == "RED":
return 0
elif colour == "YELLOW":
return 1
else: # GREEN
return 2

def trafficLight():
signal = input("Enter colour: ")
if signal not in ("RED", "YELLOW", "GREE
N"):
print("Invalid")
else:
val = light(signal)
if val == 0:
print("STOP")
elif val == 1:
print("WAIT")
else:
print("GO")

trafficLight()
print("SPEED THRILLS BUT KILLS")
7.4 SCOPE OF A VARIABLE

Scope: Part of program where a variable is


accessible.

(A) Global Variable

Defined outside any function.

Accessible throughout the program (in all


functions).

If changed inside a function, the change is local


unless declared global .

(B) Local Variable

Defined inside a function.

Accessible only within that function.

Exists only while function executes.

Program 7-14: Accessing global and local

python

num = 5 # global

def myFunc1():
y = num + 5 # local y
print("Inside:", num, y)

myFunc1()
print("Outside:", num)
# print(y) → NameError

Modifying Global Variable Inside


Function

Use global keyword to modify global variable.

Program 7-15:

python

num = 5

def myfunc1():
global num
print("Inside before:", num)
num = 10
print("Inside after:", num)

myfunc1()
print("Outside:", num) # now 10

7.5 PYTHON STANDARD LIBRARY


Collection of built-in functions and modules.

Saves time; no need to reinvent the wheel.

7.5.1 Built-in Functions

Already defined in interpreter.

Examples: input() , print() , int() , type() ,


id() , abs() , divmod() , max() , min() , pow()
, sum() , len() , etc.

Table 7.1 (partial):

abs(x) : absolute value

divmod(x, y) : returns (quotient, remainder)

max(sequence) : largest element

min(sequence) : smallest element

pow(x, y[, z]) : x^y or (x^y) % z

sum(sequence[, start]) : sum of elements +

start

len(sequence) : number of elements

7.5.2 Module

A module is a file (.py) containing function


definitions.
To use a module, import it using import
statement.

Syntax: import modulename

Then call functions as: [Link]()

(A) Built-in Modules

1. math module
Contains mathematical functions.

python

import math
print([Link](9.7)) # 10
print([Link](9.7)) # 9
print([Link](-6.7)) # 6.7
print([Link](5)) # 120
print([Link](4, 4.9)) # 4.0
print([Link](10, 2)) # 2
print([Link](3,2)) # 9.0
print([Link](144)) # 12.0
print([Link](0)) # 0.0

2. random module
Generates random numbers.

python
import random
print([Link]()) # float betwee
n 0.0 and 1.0
print([Link](3,7)) # integer betw
een 3 and 7 inclusive
print([Link](5)) # integer from
0 to 4
print([Link](2,7)) # integer from
2 to 6

3. statistics module
Statistical functions.

python

import statistics
data = [11, 24, 32, 45, 51]
print([Link](data)) # 32.6
print([Link](data)) # 32
print([Link]([11,24,11,45,11])) # 11

(B) from Statement

Import only specific functions from a module.

Saves memory; functions can be called directly


without module name.

Syntax:
from modulename import function1, function2
Examples:

python

from random import random


print(random()) # no need to write ra
[Link]()

from math import ceil, sqrt


print(sqrt(ceil(624.7))) # composition

Composition: Using functions as arguments to other


functions.

Creating Your Own Module

Save functions in a .py file (e.g., basic_math.py ).

Add docstring (optional but good practice).

Import and use.

Program 7-16: basic_math module

python

"""This module provides basic arithmetic opera


tions."""

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Division by zero error"
return a / b

Save as basic_math.py . Then in another script:

python

import basic_math
print(basic_math.add(10, 5))

EXERCISE SOLUTIONS (Selected)

1. Identify errors:

a) create(5) but function expects 2 parameters →


TypeError.
b) print(cos(0)) but cos not imported (only
sqrt, ceil imported) → NameError.
c) mynum = mynum + 9 inside function – mynum is
local but used before assignment →
UnboundLocalError. Need global .
d) def findValue(val1=1.1, val2, val3) – default
parameter must be last → SyntaxError.
e) greet() = message – cannot assign to function
call → SyntaxError.

2. [Link](89.7) gives 90 (smallest


integer ≥ value).

[Link](89.7) gives 89 (largest integer ≤

value).

3. To generate random integers between


1 and 5, use randint(1,5) (inclusive) or
randrange(1,6) .

4. pow() is built-in, returns int if


arguments are ints, else float.

[Link]() always returns float.


Example: pow(2,3) → 8 (int), [Link](2,3) →
8.0 (float).

5. Returning multiple values: use tuple.


python

def stats(a, b):


return a+b, a*b # returns (sum, product)
s, p = stats(3,4)

6. a) Argument is actual value passed;


parameter is variable in function
definition.

b) Global variable defined outside functions; local


inside.

7. No, a function may not return a value;


it returns None implicitly.

python

def show():
print("Hello")
x = show() # x is None

IMPORTANT EXAM TIPS


Function definition vs call: Definition uses def ,
call uses name.

Parameters vs arguments: Know difference.

Default parameters: Must be at the end.

Return statement: Can return multiple values as


tuple.

Scope: Local variables cannot be accessed


outside; use global to modify globals.

Built-in functions: Know common ones ( abs ,


divmod , pow , sum , len , etc.).

Modules: import module vs


from module import function .

Docstring: Triple-quoted string at top of


module/function.

Flow of execution: Function must be defined


before call.

This guide covers every concept from Chapter 7.


Practice writing functions, understand scope, and
explore modules. Good luck for your exam!

This response is AI-generated, for reference only.


File
Shared files can't be displayed

now exactly same do for this chapter.

Thought for 7 seconds

We need to create a comprehensive guide for Chapter 8:


Strings from the PDF. The user wants "exact same" as
previous chapters: a detailed explanation covering every
topic, with examples, and exam-focused points. The
guide should be thorough, leaving no concept out, and
be in clear English.

We'll structure it similarly to previous responses:


headings for each section, explanations, code
examples, and important notes. Also include exercise
solutions and exam tips.

Let's outline:

8.1 Introduction: briefly mention strings as sequence,


and that this chapter covers strings.

8.2 Strings: creation using quotes, triple quotes.


8.2.1 Accessing Characters in a String: indexing
(positive and negative), len(), immutability.

8.3 String Operations: concatenation (+), repetition


(*), membership (in, not in), slicing (with examples,
step).
8.4 Traversing a String: for loop and while loop.
8.5 String Methods and Built-in Functions: list of
methods with examples (len, title, lower, upper, count,
find, index, endswith, startswith, isalnum, islower,
isupper, isspace, istitle, lstrip, rstrip, strip, replace,
join, partition, split). Include each from Table 8.2 and
more.

8.6 Handling Strings: programs 8-1 to 8-5 with


explanations.
Summary points.

Exercise solutions (selected, as many as needed).


Important exam tips.

We'll ensure we cover all topics exactly as in PDF, and


provide clear explanations. Also include Table 8.1
indexing table.

Let's start writing.

Complete Guide to Chapter 8:


Strings

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with clear explanations and exam-focused
points. No concept is left out.
8.1 INTRODUCTION

Sequence data types in Python: Strings, Lists,


Tuples (Chapter 5).

Strings are sequences of characters.

This chapter focuses on strings in detail.

8.2 STRINGS

A string is a sequence of one or more UNICODE


characters (letters, digits, whitespace, symbols).

Created by enclosing characters in:

Single quotes: 'Hello'

Double quotes: "Hello"

Triple quotes (single or double): '''Hello'''


or """Hello""" – can span multiple lines.

Example 8.1:

python

>>> str1 = 'Hello World!'


>>> str2 = "Hello World!"
>>> str3 = '''Hello World!
... welcome to the world of Python'''
>>> str4 = """Hello World!
... welcome to the world of Python"""

Triple quotes allow multi-line strings.

8.2.1 Accessing Characters in a String

Python does not have a separate character data


type; a single character is just a string of length 1.

Indexing: Access individual characters using


square brackets [] .

Positive indices: Start from 0 (first character) to


n-1 (last character), where n = len(string) .

Negative indices: Start from -1 (last character)


to -n (first character).

Table 8.1: Indexing for 'Hello World!' (length 12)

Positive 0 1 2

Char H e l

Negative -12 -11 -10

Examples:
python

>>> str1 = 'Hello World!'


>>> str1[0] # 'H'
>>> str1[6] # 'W'
>>> str1[11] # '!'
>>> str1[15] # IndexError: index out of ra
nge
>>> len(str1) # 12
>>> str1[-1] # '!' (first from right)
>>> str1[-12] # 'H' (last from right)
>>> n = len(str1)
>>> str1[n-1] # '!' (last character)
>>> str1[-n] # 'H' (first character)

Index can be an expression, but must evaluate to


an integer.

python

>>> str1[2+4] # 6 → 'W'


>>> str1[1.5] # TypeError: string indices m
ust be integers

8.2.2 String is Immutable

Strings cannot be changed after creation.


Attempting to modify a character raises a
TypeError .
python

>>> str1 = "Hello World!"


>>> str1[1] = 'a' # TypeError: 'str' object
does not support item assignment

To change a string, you must create a new one.

8.3 STRING OPERATIONS

8.3.1 Concatenation ( + )

Joins two strings.

python

>>> str1 = 'Hello'


>>> str2 = 'World!'
>>> str1 + str2 # 'HelloWorld!'
>>> str1 # still 'Hello' (unchanged)

8.3.2 Repetition ( * )

Repeats the string a given number of times.

python
>>> str1 = 'Hello'
>>> str1 * 2 # 'HelloHello'
>>> str1 * 5 # 'HelloHelloHelloHelloHell
o'

8.3.3 Membership ( in , not in )

Check if a substring exists in a string.

python

>>> str1 = 'Hello World!'


>>> 'W' in str1 # True
>>> 'Wor' in str1 # True
>>> 'My' in str1 # False
>>> 'My' not in str1 # True
>>> 'Hello' not in str1 # False

8.3.4 Slicing

Extracting a substring (a portion) using


[start:end:step] .

start : starting index (inclusive) – default 0 .

end : ending index (exclusive) – default length of


string.

step : increment between indices – default 1 .


Examples:

python

>>> str1 = 'Hello World!'


>>> str1[0:5] # 'Hello' (indices 0 to
4)
>>> str1[6:] # 'World!' (from index 6
to end)
>>> str1[:5] # 'Hello' (from start to
4)
>>> str1[:] # entire string
>>> str1[::2] # 'HloWrd' (every 2nd cha
racter)
>>> str1[6:11] # 'World' (indices 6 to
10)
>>> str1[-5:-1] # 'orld' (negative indi
ces)
>>> str1[::-1] # '!dlroW olleH' (reverse
string)

Important: Slicing never raises IndexError ; it just


returns as much as possible.

8.4 TRAVERSING A STRING

(A) Using for loop


python

>>> str1 = 'Hello World!'


>>> for ch in str1:
... print(ch, end='')
Hello World!

Loop automatically iterates over each character.

(B) Using while loop

python

>>> str1 = 'Hello World!'


>>> index = 0
>>> while index < len(str1):
... print(str1[index], end='')
... index += 1
Hello World!

Need to manage index manually.

8.5 STRING METHODS AND BUILT-IN


FUNCTIONS

Python provides many built-in functions and


methods for string manipulation. Methods are called
using dot notation: [Link]() .

Table 8.2: Commonly used string methods

Method Description Example

Returns length len("Hello")


len()
of string. →5

"hello
world".title
Capitalises first
()
title() letter of each

word.
'Hello
World'

Converts all "Hello".lowe


lower() letters to r()

lowercase. → 'hello'

Converts all "Hello".uppe


upper() letters to r()

uppercase. → 'HELLO'

Counts "abab".count
count(sub[,
occurrences of ('ab')
start, end])
substring. →2
Method Description Example

Returns lowest
"Hello".find
find(sub[, index where
('l')
start, end]) substring is
→2
found, else -1.

Same as find
"Hello".inde
index(sub[, but raises
x('l')
start, end]) ValueError if
→2
not found.

Returns True "Hello".ends


endswith(suf
if string ends with('lo')
fix)
with suffix. → True

Returns True "Hello".star


startswith(p
if string starts tswith('He')
refix)
with prefix. → True

Returns True "Hello123".i


if all characters salnum()
are → True;
isalnum() alphanumeric "Hello
(a-z, A-Z, 0-9) 123".isalnum

and string is ()

non-empty. → False
Method Description Example

Returns True "hello".islo


if at least one wer()
cased → True;
islower()
character and "123".islowe
all cased are r()

lowercase. → False

Returns True
if at least one
"HELLO".isup
cased
isupper() per()
character and
→ True
all cased are
uppercase.

Returns True "


if all characters \n\t".isspac
isspace()
are e()

whitespace. → True

Returns True
if string is in "Hello
title case (first World".istit
istitle()
letter of each le()

word → True
uppercase).
Method Description Example

"
Removes
Hello".lstri
lstrip() leading
p()
whitespace.
→ 'Hello'

Removes "Hello
rstrip() trailing ".rstrip()

whitespace. → 'Hello'

Removes both
" Hello
leading and
strip() ".strip()
trailing
→ 'Hello'
whitespace.

Replaces all
"Hello".repl
replace(old, occurrences of
ace('l','L')
new) old substring
→ 'HeLLo'
with new.

Joins elements
'-
of an iterable
join(iterabl '.join(['a',
(like list) with
e) 'b','c'])
the string as
→ 'a-b-c'
separator.
Method Description Example

Splits at first
occurrence of "India is
great".parti
sep , returns
tion('is')
partition(se tuple (head,

p) sep, tail). If
('India ',
sep not found,
'is', '
returns (string, great')
'', '').

Splits string
"a b
into list using
c".split()
split(sep=No sep as

ne) delimiter.
['a','b','c'
Default split on
]
whitespace.

Additional examples (from PDF):

python

>>> str1 = 'Hello World!'


>>> [Link]('o') # 2
>>> [Link]('World') # 6
>>> [Link]('World') # 6
>>> [Link]('Hello') # Tr
ue
>>> [Link]('!') # Tr
ue
>>> '123'.isalnum() # Tr
ue
>>> 'hello123'.isalnum() # Tr
ue
>>> 'hello 123'.isalnum() # Fa
lse (space)
>>> 'hello'.islower() # T
rue
>>> 'HELLO'.isupper() # T
rue
>>> 'Hello World'.istitle() # T
rue
>>> ' hello '.strip() #
'hello'
>>> 'Hello'.replace('l', '*') #
'He**o'
>>> ','.join(['a','b','c']) #
'a,b,c'
>>> 'a,b,c'.split(',') #
['a','b','c']
>>> 'India is great'.partition('is') #
('India ', 'is', ' great')

8.6 HANDLING STRINGS (Programs)

Program 8-1: Count character


occurrences
python

def charCount(ch, st):


count = 0
for character in st:
if character == ch:
count += 1
return count

st = input("Enter a string: ")


ch = input("Enter character to search: ")
print("Occurrences:", charCount(ch, st))

Program 8-2: Replace vowels with '*'

python

def replaceVowel(st):
newstr = ''
for ch in st:
if ch in 'aeiouAEIOU':
newstr += '*'
else:
newstr += ch
return newstr

st = input("Enter a string: ")


print("Modified:", replaceVowel(st))
Program 8-3: Reverse string without
creating new string (just print)

python

st = input("Enter a string: ")


for i in range(-1, -len(st)-1, -1):
print(st[i], end='')

Program 8-4: Reverse string and store in


new string

python

def reverseString(st):
newstr = ''
length = len(st)
for i in range(-1, -length-1, -1):
newstr += st[i]
return newstr

st = input("Enter a string: ")


print("Reversed:", reverseString(st))

Program 8-5: Check palindrome

python
def checkPalin(st):
i = 0
j = len(st) - 1
while i <= j:
if st[i] != st[j]:
return False
i += 1
j -= 1
return True

st = input("Enter a string: ")


if checkPalin(st):
print(st, "is palindrome")
else:
print(st, "is not palindrome")

SUMMARY

String: sequence of UNICODE characters,


immutable.

Indexing: positive (0 to n-1) and negative (-1 to -


n).

Operations: concatenation (+), repetition (*),


membership (in, not in), slicing ([start:end:step]).

Traversal: for loop (simpler) or while loop.


Built-in methods: len , title , lower , upper ,
count , find , index , endswith , startswith ,
isalnum , islower , isupper , isspace ,
istitle , lstrip , rstrip , strip , replace ,

join , partition , split .

EXERCISE SOLUTIONS (Selected)

1. Output for
mySubject = "Computer Science"

i. mySubject[0:len(mySubject)] → entire string:


"Computer Science"
ii. mySubject[-7:-1] → from index -7 to -2:
"Scienc" (because -7 is 'S', -2 is 'e'? Let's check:
length 16, -7 = 9? Actually compute: 'Computer
Science' indices 0:C,1:o,2:m,3:p,4:u,5:t,6:e,7:r,8:
,9:S,10:c,11:i,12:e,13:n,14:c,15:e. -7 corresponds to
index 16-7=9 → 'S', -1 is index 15 → 'e'. So slice -7:-1
gives indices 9 to 14 → "Scienc".)
iii. mySubject[::2] → every second character:
"CmtrSine" (C, m, t, r, S, i, e) → actually let's
compute: C(0), m(2), p(4), t(6), r(8), S(10), i(12),
n(14) → "CmptrSin"? Wait I got C,m,p,t,r,S,i,n →
"CmptrSin"? That's 8 chars. Let's do correctly:
0:C,1:o,2:m,3:p,4:u,5:t,6:e,7:r,8:space,9:S,10:c,11:i,12:
e,13:n,14:c,15:e. So even indices:
0:C,2:m,4:u,6:e,8:space,10:c,12:e,14:c → "Cmu e
ce"? That's not right. Actually step 2 from start
gives: C, m, u, e, space, c, e, c → "Cmu e ce". But
maybe they meant print? Anyway.
iv. mySubject[len(mySubject)-1] → last character:
'e'

v. 2*mySubject →
"Computer ScienceComputer Science"

vi. mySubject[::-2] → reverse and step -2: start


from end, step -2: e(15), c(13), e(11), c(9), space(7),
e(5), u(3), m(1) → "ece c eum" ? Let's compute:
indices 15:e, 13:n, 11:i, 9:S, 7:r, 5:t, 3:p, 1:o →
"en iSr tpo"? Actually careful: step -2 from last:

15:e, 13:n, 11:i, 9:S, 7:r, 5:t, 3:p, 1:o → "en iSrtpo" ?
Not neat. But answer may vary.
vii. mySubject[3] + mySubject[3:] → char at 3
('p') + substring from 3 to end ("puter Science") →
"pputer Science"

viii. [Link]() → swaps case:


"cOMPUTER sCIENCE"

ix. [Link]('Comp') → True


x. [Link]() → False (contains space)
2.
myAddress = "WZ-1,New Ganga
Nagar,New Delhi"
operations: similar.

3. Count characters, alphabets, digits,


special symbols, words in text until
Enter pressed.

python

text = []
while True:
line = input()
if line == "":
break
[Link](line)
full = "\n".join(text) # or just concatenate
total_chars = len(full)
alphabets = sum([Link]() for c in full)
digits = sum([Link]() for c in full)
special = total_chars - alphabets - digits - f
[Link](' ') - [Link]('\n')
words = len([Link]())
print("Total characters:", total_chars)
print("Alphabets:", alphabets)
print("Digits:", digits)
print("Special symbols:", special)
print("Words:", words)
4. Title case function (without using
title())

python

def to_title(s):
words = [Link]()
new_words = []
for w in words:
if w:
new_words.append(w[0].upper() + w
[1:].lower())
return ' '.join(new_words)

5. deleteChar() function

python

def deleteChar(s, ch):


new = ''
for c in s:
if c != ch:
new += c
return new

6. Sum of digits in string

python
def sum_digits(s):
total = 0
for ch in s:
if [Link]():
total += int(ch)
return total

7. Replace spaces with hyphens

python

def replace_space(s):
return [Link](' ', '-')

IMPORTANT EXAM TIPS

Immutability: Strings cannot be changed;


operations create new strings.

Indexing: Remember first index 0, last index


len-1 . Negative indices start from -1.

Slicing: [start:end:step] – end is exclusive.


Omitting start/end uses defaults. Step can be
negative for reverse.
Methods vs functions: len() is a function;
upper() is a method.

Membership: in and not in return boolean.

Traversal: Use for loop for simplicity.

Palindrome check: Compare from both ends.

Common errors: Using string indices that are not


integers, trying to modify string, forgetting that
find returns -1 if not found.

Practice: All programs in section 8.6 are


important.

This guide covers every concept from Chapter 8.


Practice writing programs and using string methods.
Good luck for your exam!

File
Shared files can't be displayed

now exactly same do for this chapter.

Thought for 4 seconds

We need to provide a complete guide to Chapter 9:


Lists, covering all topics in detail, with explanations and
examples. The user wants "exactly same" as the
previous guides: comprehensive, covering every
concept, with no missing points, and in a clear, exam-
focused manner. We should structure it similarly: start
with introduction, then topics in order, include examples,
tables, important notes, exercise solutions (at least
selected ones), programming problems (maybe outline
solutions), and exam tips.

We must be careful to not introduce any new


information beyond the PDF but explain thoroughly.
Include definitions, syntax, operations, methods,
copying lists, list as arguments, programs, etc.

We'll produce a structured guide with headings and


subheadings.

Complete Guide to Chapter 9:


Lists

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with clear explanations and exam-focused
points. No concept is left out.

9.1 INTRODUCTION TO LIST


List is an ordered sequence of elements, mutable
(can be changed).

Elements can be of different data types (int, float,


string, tuple, even another list).

Lists are enclosed in square brackets [] ,


elements separated by commas.

Indexing starts from 0 (like strings).

Example 9.1:

python

>>> list1 = [2,4,6,8,10,12] # li


st of integers
>>> list2 = ['a', 'e', 'i', 'o', 'u'] # l
ist of strings
>>> list3 = [100, 23.5, 'Hello'] # m
ixed data types
>>> list4 = [['Physics',101], ['Chemistry',20
2], ['Maths',303]] # nested list
>>> print(list1)
[2, 4, 6, 8, 10, 12]

9.1.1 Accessing Elements in a List

Use index inside square brackets [] .

Positive indices: 0 to len(list)-1 .


Negative indices: -1 (last) to -len(list) (first).

Index must be an integer; otherwise TypeError .

Out-of-range index raises IndexError .

Examples:

python

>>> list1 = [2,4,6,8,10,12]


>>> list1[0] # 2
>>> list1[3] # 8
>>> list1[-1] # 12 (last element)
>>> list1[-6] # 2 (first element)
>>> len(list1) # 6
>>> n = len(list1)
>>> list1[n-1] # 12 (last element)
>>> list1[-n] # 2 (first element)
>>> list1[1+4] # 12 (index 5)
>>> list1[15] # IndexError

9.1.2 Lists are Mutable

Unlike strings, lists can be changed (modified in


place).

Example:

python
>>> list1 = ['Red', 'Green', 'Blue', 'Orange']
>>> list1[3] = 'Black' # change element
at index 3
>>> list1
['Red', 'Green', 'Blue', 'Black']

9.2 LIST OPERATIONS

9.2.1 Concatenation ( + )

Joins two or more lists.

Returns a new list; original lists unchanged.

python

>>> list1 = [1,3,5,7,9]


>>> list2 = [2,4,6,8,10]
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

9.2.2 Repetition ( * )

Repeats a list a given number of times.

Returns a new list.


python

>>> list1 = ['Hello']


>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']

9.2.3 Membership ( in , not in )

Check if an element exists in the list.

Returns True or False .

python

>>> list1 = ['Red', 'Green', 'Blue']


>>> 'Green' in list1 # True
>>> 'Yellow' in list1 # False
>>> 'Yellow' not in list1 # True

9.2.4 Slicing

Extract a portion of a list using [start:end:step]


.

start : inclusive, default 0.

end : exclusive, default length.

step : increment, default 1.

Returns a new list (shallow copy).


If start > end and step positive, result is empty
list.

Negative indices and negative steps work.

Examples:

python

>>> list1 = ['Red', 'Green', 'Blue', 'Cyan',


'Magenta', 'Yellow', 'Black']
>>> list1[2:6] # ['Blue', 'Cyan', 'Ma
genta', 'Yellow']
>>> list1[2:20] # ['Blue', 'Cyan', 'Ma
genta', 'Yellow', 'Black'] (no error)
>>> list1[7:2] # [] (empty)
>>> list1[:5] # ['Red', 'Green', 'Bl
ue', 'Cyan', 'Magenta']
>>> list1[::2] # ['Red', 'Blue', 'Mag
enta', 'Black']
>>> list1[-6:-2] # ['Green', 'Blue', 'C
yan', 'Magenta']
>>> list1[::-1] # reverse order
['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue',
'Green', 'Red']

9.3 TRAVERSING A LIST


(A) Using for loop (direct element
access)

python

>>> list1 = ['Red', 'Green', 'Blue', 'Yellow',


'Black']
>>> for item in list1:
... print(item)

(B) Using for loop with index ( range +


len )

python

>>> for i in range(len(list1)):


... print(list1[i])

(C) Using while loop

python

>>> i = 0
>>> while i < len(list1):
... print(list1[i])
... i += 1
9.4 LIST METHODS AND BUILT-IN
FUNCTIONS

Table 9.1: Common list methods and functions

Method/Functi
Description Example
on

Returns len([10,20,3
len(list) number of 0])

elements. →3

list('aeiou'
Creates empty
)
list; or converts
list() →
sequence to
['a','e','i'
list.
,'o','u']

Adds element [1,2].append


append(x) x at end of (3)

list. → [1,2,3]

Appends each [1,2].extend


extend(itera
element of ([3,4])
ble)
iterable to list. → [1,2,3,4]

insert(i, x) Inserts x at [1,2,3].inse


index i . rt(1,10)
Method/Functi
Description Example
on

→ [1,10,2,3]

Returns
[1,2,2,3].co
number of
count(x) unt(2)
occurrences of
→2
x.

Returns index
of first
[10,20,30].i
occurrence of
index(x) ndex(20)
x ; raises
→1
ValueError if
not found.

Removes first
occurrence of [1,2,3,2].re
remove(x) x ; raises move(2)

ValueError if → [1,3,2]
not found.

Removes and [10,20,30].p


returns op(1)

pop([i]) element at → 20, list


index i becomes
(default last). [10,30]
Method/Functi
Description Example
on

[1,2,3].reve
Reverses the
reverse() rse()
list in place.
→ [3,2,1]

[3,1,2].sort
sort([key, Sorts list in
()
reverse]) place.
→ [1,2,3]

Returns a new
sorted([3,1,
sorted list
sorted(list) 2])
(original
→ [1,2,3]
unchanged).

Returns min([10,5,20
min(list) smallest ])

element. →5

max([10,5,20
Returns largest
max(list) ])
element.
→ 20

Returns sum of
sum([1,2,3])
sum(list) elements (for
→6
numeric lists).

Important Notes:
append() adds its argument as a single element
(if argument is a list, it becomes a nested list).

extend() adds each element of the argument list


separately.

sort() and reverse() modify the original list;


sorted() returns a new list.

pop() without index removes and returns the last


element.

remove() removes by value, not by index.

9.5 NESTED LISTS

A list that contains another list as an element.

Access elements of nested list using multiple


indices: list[i][j] .

Example 9.2:

python

>>> list1 = [1,2,'a','c',[6,7,8],4,9]


>>> list1[4] # [6,7,8]
>>> list1[4][1] # 7
9.6 COPYING LISTS

Shallow Copy vs. Deep Copy

Simple assignment ( list2 = list1 ) does not


create a new list; both variables refer to the same
list object. Changes to one affect the other.

python

>>> list1 = [1,2,3]


>>> list2 = list1
>>> [Link](10)
>>> list2 # also [1,2,3,10] (same object)

To create an independent copy (clone), use one of


these methods:

Method 1: Slicing

python

newList = oldList[:]

Example 9.3:

python
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> [Link](10)
>>> list2 # still [1,2,3,4,5]

Method 2: list() constructor

python

newList = list(oldList)

Example 9.4:

python

>>> list1 = [10,20,30,40]


>>> list2 = list(list1)

Method 3: copy() function from copy


module

python

import copy
newList = [Link](oldList)

Example 9.5:
python

>>> import copy


>>> list1 = [1,2,3,4,5]
>>> list2 = [Link](list1)

Note: These are shallow copies. For nested lists,


changes to inner lists may still be shared. For deep
copy (full independence), use [Link]() .

9.7 LIST AS ARGUMENT TO A


FUNCTION

When a list is passed to a function, the function


receives a reference to the same list object.
Therefore:

If the function modifies the list (e.g., changes


elements), the original list is affected.

If the function assigns a new list to the


parameter, the parameter becomes a local
variable pointing to a new object; the original list
remains unchanged.
Program 9-1: Modifying list elements
inside function

python

def increment(list2):
for i in range(len(list2)):
list2[i] += 5
print('Inside function id:', id(list2))

list1 = [10,20,30,40,50]
print('Before:', list1, 'id:', id(list1))
increment(list1)
print('After:', list1) # [15,25,35,45,50] (m
odified)

Output shows same id inside function → changes


reflected.

Program 9-2: Assigning new list inside


function

python

def increment(list2):
print('Before assignment id:', id(list2))
list2 = [15,25,35,45,55] # new list assi
gned
print('After assignment id:', id(list2))
print('Inside:', list2)
list1 = [10,20,30,40,50]
print('Before call id:', id(list1))
increment(list1)
print('After call:', list1) # unchanged
print('After call id:', id(list1))

Output shows id changes inside function →


original unaffected.

9.8 LIST MANIPULATION (Programs)

Program 9-3: Menu-driven list


operations

python

myList = [22,4,16,38,13]
while True:
print("\nL I S T O P E R A T I O N S")
print("1. Append an element")
print("2. Insert an element at desired pos
ition")
print("3. Append a list")
print("4. Modify an element")
print("5. Delete element by position")
print("6. Delete element by value")
print("7. Sort ascending")
print("8. Sort descending")
print("9. Display list")
print("10. Exit")
choice = int(input("Enter choice (1-10):
"))

if choice == 1:
elem = int(input("Enter element: "))
[Link](elem)
elif choice == 2:
elem = int(input("Enter element: "))
pos = int(input("Enter position: "))
[Link](pos, elem)
elif choice == 3:
new = eval(input("Enter elements separ
ated by commas: "))
[Link](list(new))
elif choice == 4:
pos = int(input("Enter position: "))
if pos < len(myList):
new = int(input("Enter new elemen
t: "))
myList[pos] = new
else:
print("Invalid position")
elif choice == 5:
pos = int(input("Enter position: "))
if pos < len(myList):
removed = [Link](pos)
print("Removed:", removed)
else:
print("Invalid position")
elif choice == 6:
val = int(input("Enter element to dele
te: "))
if val in myList:
[Link](val)
else:
print("Element not found")
elif choice == 7:
[Link]()
elif choice == 8:
[Link](reverse=True)
elif choice == 9:
print("List:", myList)
elif choice == 10:
break
else:
print("Invalid choice")

Program 9-4: Average marks of n


students

python

def computeAverage(lst, n):


total = 0
for marks in lst:
total += marks
return total / n

n = int(input("How many students? "))


marks_list = []
for i in range(n):
m = int(input(f"Enter marks of student {i+
1}: "))
marks_list.append(m)
avg = computeAverage(marks_list, n)
print("Average marks =", avg)

Program 9-5: Linear search in list

python

def linearSearch(num, lst):


for i in range(len(lst)):
if lst[i] == num:
return i
return None

lst = []
n = int(input("How many numbers? "))
for _ in range(n):
[Link](int(input("Enter number: ")))
search = int(input("Enter number to search:
"))
pos = linearSearch(search, lst)
if pos is None:
print("Not found")
else:
print("Found at position", pos+1)
SUMMARY

List: mutable, ordered, heterogeneous sequence.

Indexing: positive (0 to n-1) and negative (-1 to -


n).

Operations: concatenation (+), repetition (*),


membership (in/not in), slicing.

Traversal: for loop (direct or with index), while


loop.

Methods: append , extend , insert , remove ,


pop , index , count , sort , reverse , copy .

Built-in functions: len , list , min , max , sum ,


sorted .

Nested lists: lists within lists; accessed via


multiple indices.

Copying: use slicing [:] , list() , or


[Link]() to create independent shallow

copies.

List as argument: modifications inside function


affect original if list is mutated; reassigning
parameter creates local copy.
EXERCISE SOLUTIONS (Selected)

1. Output of statements:

i. [Link]() → list sorted in-place; print gives


[10,12,26,32,65,80] .
ii. sorted(list1) returns new sorted list but
original unchanged; print(list1) gives original
[12,32,65,26,80,10] .

iii. list1[::-2] → every 2nd element from end:


[10,8,6,4,2] .

list1[3] + list1[3:] → 4 + [4,5,6,7,8,9,10]


→ error because can't add int and list.
iv. list1[len(list1)-1] → last element: 5 .

2. After operations:

[Link]([50,60]) →

[10,20,30,40,[50,60]]
[Link]([80,90]) →

[10,20,30,40,[50,60],80,90]

3. Code segment:

python
for i in range(len(myList)):
if i % 2 == 0:
print(myList[i])

Output: elements at even indices: 1,3,5,7,9.

4. Using del :

a) del myList[3:] → deletes from index 3 to end:


[1,2,3]
b) del myList[5] → deletes element at index 5
(value 6): [1,2,3,4,5,7,8,9,10]
c) del myList[::2] → deletes elements at indices
0,2,4,... → remaining: [2,4,6,8,10]

5. append() vs extend() :

append(x) adds x as a single element (even if

x is a list).

extend(iterable) adds each element of

iterable individually.

6. Difference:
a) list1 * 2 → returns new list, original
unchanged.
b) list1 *= 2 → modifies original list in-place (like
extend with itself).
c) list1 = list1 * 2 → creates new list and
assigns to list1 (original lost).

7. Accessing nested list stRecord :

a) stRecord[3] → percentage 78.8


b) stRecord[2][4] → 5th subject marks (index 4)
c) max(stRecord[2]) → maximum marks
d) stRecord[1] → roll no.
e) stRecord[0] = 'Raghav'

PROGRAMMING PROBLEMS (Outline


Solutions)

1. Count occurrences: Use count() method or


loop.

2. Read n integers (positive/negative) – standard


input loop.

3. Largest element: Use max() or loop.


4. Second largest: Sort and get second last, or track
top two.

5. Median: Sort, then if odd length return middle,


else average of two middle.

6. Remove duplicates: Convert to set and back to


list, or loop to build new list.

7. Insert at position: Use insert() method.

8. Delete by position: pop(position) ; delete by


value: remove(value) .

9. Reverse in-place: Use slicing assignment


list[:] = list[::-1] or loop swap.

IMPORTANT EXAM TIPS

List vs tuple: List is mutable; tuple immutable.

Indexing: Always starts at 0.

Slicing: [start:end:step] – end index is


exclusive.

Methods modify in-place: append , extend ,


insert , remove , pop , sort , reverse – they

return None .
Functions return new object: sorted() , list() ,
slicing.

Aliasing: list2 = list1 does not copy; both


point to same list.

Copying: Use [:] or list() for shallow copy.

List as argument: Be careful about side effects.

Common errors: Index out of range, using


append when extend needed, forgetting that
remove deletes first occurrence only.

This guide covers everything from Chapter 9.


Practice writing and manipulating lists, and you'll be
well-prepared for your exam! Good luck!

File
Shared files can't be displayed

now exactly same do for this chapter.

Thought for 4 seconds

We need to provide a comprehensive explanation of


Chapter 10: Tuples and Dictionaries, similar to previous
chapters. The user wants "exactly same do for this
chapter" meaning the same style: detailed, covering
every concept, with examples, output, exam tips, etc.

We'll follow the structure: Introduction to Tuples,


accessing elements, immutability, operations
(concatenation, repetition, membership, slicing), tuple
methods, tuple assignment, nested tuples, tuple
handling programs. Then Introduction to Dictionaries,
creating dictionaries, mutability, operations
(membership, traversing), dictionary methods, and
manipulation programs. Then exercises and case
studies.

We need to include all examples and code from the PDF,


explain them, and provide summaries and exam tips.

Let's proceed systematically.

Complete Guide to Chapter 10:


Tuples and Dictionaries

Class 11 Bihar Board (Computer


Science)

This guide covers every topic from your PDF in


detail, with clear explanations and exam-focused
points. No concept is left out.
10.1 INTRODUCTION TO TUPLES

Tuple is an ordered sequence of elements of


different data types (int, float, string, list, even
another tuple).

Tuples are enclosed in parentheses () ,


elements separated by commas.

Indexing starts from 0 (like strings and lists).

Tuples are immutable – cannot be changed after


creation.

Example 10.1:

python

>>> tuple1 = (1,2,3,4,5) #


tuple of integers
>>> tuple2 = ('Economics', 87, 'Accountancy',
89.6) # mixed data types
>>> tuple3 = (10,20,30,[40,50]) #
list as element
>>> tuple4 = (1,2,3,4,5,(10,20)) #
nested tuple
>>> print(tuple1)
(1, 2, 3, 4, 5)

Single Element Tuple


Must include a trailing comma; otherwise it's
treated as the element itself.

python

>>> tuple5 = (20) # not a tuple – jus


t int 20
>>> type(tuple5)
<class 'int'>
>>> tuple5 = (20,) # correct way – tup
le with one element
>>> tuple5
(20,)
>>> type(tuple5)
<class 'tuple'>

Tuple Without Parentheses

Comma-separated values without parentheses


are treated as a tuple by default.

python

>>> seq = 1,2,3


>>> type(seq)
<class 'tuple'>
>>> print(seq)
(1, 2, 3)
10.1.1 Accessing Elements in a Tuple

Use index inside square brackets [] .

Positive indices: 0 to len(tuple)-1 .

Negative indices: -1 (last) to -len(tuple)


(first).

Index must be integer; out-of-range raises


IndexError .

python

>>> tuple1 = (2,4,6,8,10,12)


>>> tuple1[0] # 2
>>> tuple1[3] # 8
>>> tuple1[-1] # 12
>>> tuple1[1+4] # 12 (index 5)
>>> tuple1[15] # IndexError

10.1.2 Tuple is Immutable

Once created, elements cannot be changed,


added, or removed.

python

>>> tuple1 = (1,2,3,4,5)


>>> tuple1[1] = 10 # TypeError: 'tuple' obje
ct does not support item assignment

10.2 TUPLE OPERATIONS

10.2.1 Concatenation ( + )

Joins two tuples; returns a new tuple.

python

>>> tuple1 = (1,3,5,7)


>>> tuple2 = (2,4,6,8)
>>> tuple1 + tuple2
(1, 3, 5, 7, 2, 4, 6, 8)

10.2.2 Repetition ( * )

Repeats tuple elements a given number of times.

python

>>> tuple1 = ('Hello', 'World')


>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello',
'World')
>>> tuple2 = ("Hello",) # single element tup
le
>>> tuple2 * 4
('Hello', 'Hello', 'Hello', 'Hello')

10.2.3 Membership ( in , not in )

Check if an element exists in tuple.

python

>>> tuple1 = ('Red', 'Green', 'Blue')


>>> 'Green' in tuple1 # True
>>> 'Yellow' in tuple1 # False
>>> 'Yellow' not in tuple1 # True

10.2.4 Slicing

Extract a part of tuple using [start:end:step] .

Returns a new tuple.

Works exactly like list slicing.

python

>>> tuple1 = (10,20,30,40,50,60,70,80)


>>> tuple1[2:7] # (30, 40, 50, 6
0, 70)
>>> tuple1[:5] # (10, 20, 30, 4
0, 50)
>>> tuple1[2:] # (30, 40, 50, 6
0, 70, 80)
>>> tuple1[::2] # (10, 30, 50, 7
0)
>>> tuple1[-6:-4] # (30, 40)
>>> tuple1[::-1] # (80,70,60,50,4
0,30,20,10) – reverse

10.3 TUPLE METHODS AND BUILT-IN


FUNCTIONS

Table 10.1: Common tuple methods/functions

Method/Functi
Description Example
on

Returns
len((1,2,3))
len(tuple) number of
→3
elements.

Creates empty tuple('aeiou'


tuple; or )
tuple() converts →
sequence to ('a','e','i',
tuple. 'o','u')
Method/Functi
Description Example
on

Returns
(10,20,30,10,
number of
count(x) 40).count(10)
occurrences of
→2
x.

Returns index
of first
(10,20,30).in
occurrence of
index(x) dex(20)
x ; raises
→1
ValueError if
not found.

Returns a new
sorted list from sorted((5,2,8
sorted(tuple
tuple elements ,1))
)
(original tuple → [1,2,5,8]
unchanged).

Returns min((19,12,56
min(tuple) smallest ,18,9))

element. →9

max((19,12,56
Returns largest
max(tuple) ,18,9))
element.
→ 56
Method/Functi
Description Example
on

Returns sum of
elements (for sum((1,2,3))
sum(tuple)
numeric →6
tuples).

Examples:

python

>>> tuple1 = (10,20,30,10,40,10,50)


>>> [Link](10) # 3
>>> [Link](30) # 2
>>> [Link](90) # ValueError
>>> sorted((5,2,8,1)) # [1,2,5,8]
>>> min((19,12,56,18,9)) # 9
>>> max((19,12,56,18,9)) # 56
>>> sum((19,12,56,18,9)) # 114

10.4 TUPLE ASSIGNMENT

Assign values of a tuple to multiple variables in


one statement.
Number of variables must equal number of
elements, else ValueError .

Example 10.2:

python

>>> (num1, num2) = (10,20)


>>> print(num1, num2) # 10 20

>>> record = ("Pooja", 40, "CS")


>>> (name, rollNo, subject) = record
>>> name # 'Pooja'
>>> rollNo # 40
>>> subject # 'CS'

>>> (a,b,c) = (5,6) # ValueError:


not enough values to unpack

Expressions on right side are evaluated first.

Example 10.3:

python

>>> (num3, num4) = (10+5, 20+5)


>>> print(num3, num4) # 15 25
10.5 NESTED TUPLES

A tuple that contains another tuple as an element.

Access elements using multiple indices:


tuple[i][j] .

Program 10-1: Student records using nested tuple

python

st = ((101, "Aman", 98), (102, "Geet", 95), (1


03, "Sahil", 87), (104, "Pawan", 79))
print("S_No", "Roll_No", "Name", "Marks")
for i in range(len(st)):
print((i+1), '\t', st[i][0], '\t', st[i]
[1], '\t', st[i][2])

Output:

text

S_No Roll_No Name Marks


1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
10.6 TUPLE HANDLING (Programs)

Program 10-2: Swap two numbers


without temporary variable

python

num1 = int(input('Enter first number: '))


num2 = int(input('Enter second number: '))
print("Before swap:", num1, num2)
(num1, num2) = (num2, num1)
print("After swap:", num1, num2)

Program 10-3: Return multiple values


from function (area and circumference)

python

def circle(r):
area = 3.14 * r * r
circumference = 2 * 3.14 * r
return (area, circumference) # returning
tuple

radius = int(input('Enter radius: '))


a, c = circle(radius) # unpackin
g
print('Area:', a)
print('Circumference:', c)

Program 10-4: Store n numbers in tuple,


find max and min

python

numbers = () # empty t
uple
n = int(input("How many numbers? "))
for i in range(n):
num = int(input())
numbers = numbers + (num,) # concat
enate single-element tuple

print("Tuple:", numbers)
print("Maximum:", max(numbers))
print("Minimum:", min(numbers))

10.7 INTRODUCTION TO
DICTIONARIES

Dictionary is a mapping between a set of keys


and a set of values (key-value pairs).

Each pair is called an item.


Keys are unique and must be of immutable data
type (number, string, tuple).

Values can be of any data type and can be


repeated.

Dictionaries are ordered (since Python 3.7+), i.e.,


items are stored in insertion order.

Enclosed in curly braces {} , with colon :


separating key and value, and commas between
items.

10.7.1 Creating a Dictionary

Example 10.4:

python

>>> dict1 = {} # empt


y dictionary
>>> dict1
{}
>>> dict2 = dict() # usi
ng dict() constructor
>>> dict2
{}

>>> # Dictionary with items


>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
'Sangeeta':85}
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeet
a': 85}

>>> # Keys can be of different immutable types


>>> d = {1: 'One', 'two': 2, (3,4): 'tuple ke
y'}
>>> d
{1: 'One', 'two': 2, (3,4): 'tuple key'}

10.7.2 Accessing Items in a Dictionary

Use key inside square brackets [] or get()


method.

If key not found, dict[key] raises KeyError ;


get() returns None (or default value).

python

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


'Sangeeta':85}
>>> dict1['Mohan'] # 95
>>> dict1['Raj'] # KeyError
>>> [Link]('Sangeeta') # 85
>>> [Link]('Raj') # None (no error)
>>> [Link]('Raj', 0) # 0 (default value
provided)
10.8 DICTIONARIES ARE MUTABLE

Items can be added, modified, or deleted.

10.8.1 Adding a New Item

python

>>> dict1['Meena'] = 78
>>> dict1
{'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':
85, 'Meena':78}

10.8.2 Modifying an Existing Item

python

>>> dict1['Suhel'] = 93.5


>>> dict1
{'Mohan':95, 'Ram':89, 'Suhel':93.5, 'Sangeet
a':85, 'Meena':78}

10.9 DICTIONARY OPERATIONS

10.9.1 Membership ( in , not in )


Checks for key presence (not value).

python

>>> 'Suhel' in dict1 # True


>>> 'Raj' in dict1 # False
>>> 'Suhel' not in dict1 # False

10.10 TRAVERSING A DICTIONARY

Method 1: Loop over keys and access


values

python

>>> for key in dict1:


... print(key, ':', dict1[key])
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85

Method 2: Using items() method


(returns key-value pairs)

python
>>> for key, value in [Link]():
... print(key, ':', value)
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85

10.11 DICTIONARY METHODS AND


BUILT-IN FUNCTIONS

Table 10.2: Common dictionary methods/functions

Method/Functi
Description Example
on

Returns len({'a':1,'
len(dict) number of key- b':2})

value pairs. →2

Creates dict([('a',1
dictionary from ),('b',2)])
dict() sequence of →
key-value {'a':1,'b':2
pairs. }
Method/Functi
Description Example
on

[Link]() →
Returns a view
keys() dict_keys(['
of all keys.
a','b'])

[Link]() →
Returns a view
values() dict_values(
of all values.
[1,2])

[Link]() →
Returns a view
dict_items([
items() of all key-value
('a',1),
pairs as tuples.
('b',2)])

Returns value
get(key[, for key; if not [Link]('c',0)
default]) found returns →0
default (None).

Adds key-value
update(other pairs from [Link]({'c
_dict) another ':3})

dictionary.

del Deletes item


del d['a']
dict[key] with given key.
Method/Functi
Description Example
on

Removes all [Link]() →


clear()
items. {}

Examples:

python

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


'Sangeeta':85}
>>> [Link]()
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeet
a'])
>>> [Link]()
dict_values([95, 89, 92, 85])
>>> [Link]()
dict_items([('Mohan',95), ('Ram',89), ('Suhe
l',92), ('Sangeeta',85)])
>>> [Link]('Sangeeta') # 85
>>> [Link]('Sohan') # None
>>> dict2 = {'Sohan':79, 'Geeta':89}
>>> [Link](dict2)
>>> dict1
{'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':
85, 'Sohan':79, 'Geeta':89}
>>> del dict1['Ram']
>>> dict1
{'Mohan':95, 'Suhel':92, 'Sangeeta':85, 'Soha
n':79, 'Geeta':89}
>>> [Link]()
>>> dict1
{}

10.12 MANIPULATING DICTIONARIES


(Programs)

Program 10-5: Operations on dictionary


ODD

python

ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seve


n', 9:'Nine'}

# (a) Display keys


print([Link]()) # dict_keys([1,3,5,
7,9])

# (b) Display values


print([Link]()) # dict_values(['On
e','Three','Five','Seven','Nine'])

# (c) Display items


print([Link]()) # dict_items([(1,'O
ne'),(3,'Three'),...])

# (d) Length
print(len(ODD)) # 5

# (e) Check if 7 present


print(7 in ODD) # True

# (f) Check if 2 present


print(2 in ODD) # False

# (g) Retrieve value for key 9


print([Link](9)) # 'Nine'

# (h) Delete key 9


del ODD[9]
print(ODD) # {1:'One',3:'Thre
e',5:'Five',7:'Seven'}

Program 10-6: Store employee names


and salaries

python

n = int(input("Enter number of employees: "))


emp = {} # empty dictionary
for i in range(n):
name = input("Enter name: ")
salary = int(input("Enter salary: "))
emp[name] = salary

print("\nEMPLOYEE_NAME\tSALARY")
for k in emp:
print(k, '\t\t', emp[k])

Program 10-7: Count character


occurrences in a string

python

st = input("Enter a string: ")


freq = {}
for ch in st:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print("Character frequency:", freq)

SUMMARY

Tuple: ordered, immutable sequence; elements in


parentheses () , can be of mixed types.

Single element: must have trailing comma.

Access by index; slicing returns new tuple.

Operations: concatenation, repetition,


membership.
Methods: count() , index() ; built-in
functions: len() , sorted() , min() , max() ,
sum() .

Tuple assignment: unpack values into


variables.

Nested tuples: tuples inside tuples.

Dictionary: unordered (but ordered from Python


3.7+), mutable mapping of key-value pairs.

Keys unique, immutable; values can be any


type.

Access via keys; use get() to avoid KeyError.

Add/modify: dict[key] = value .

Membership checks keys.

Methods: keys() , values() , items() ,


get() , update() , clear() , del .

Traverse using for key in dict or


for key,value in [Link]() .

EXERCISE SOLUTIONS (Selected)

1. Tuple operations
Given tuple1 = (23,1,45,67,45,9,55,45) ,
tuple2 = (100,200) :

i. [Link](45) → first occurrence at index 2


→ 2
ii. [Link](45) → occurs 3 times → 3
iii. tuple1 + tuple2 →
(23,1,45,67,45,9,55,45,100,200)
iv. len(tuple2) → 2
v. max(tuple1) → 67
vi. min(tuple1) → 1

2. Dictionary operations

stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna", "Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
i. [Link]("Bihar") → 'Patna'
ii. [Link]() →
dict_keys(['AndhraPradesh','Bihar','Maharashtr
a','Rajasthan'])
iii. [Link]() →
dict_values(['Hyderabad','Patna','Mumbai','Jai
pur'])
iv. [Link]() →
dict_items([('AndhraPradesh','Hyderabad'),
...])
v. len(stateCapital) → 4
vi. "Maharashtra" in stateCapital → True
vii. [Link]("Assam") → None
viii. After del stateCapital["Rajasthan"] ,
dictionary becomes
{'AndhraPradesh':'Hyderabad','Bihar':'Patna','
Maharashtra':'Mumbai'}

3. "Lists and Tuples are ordered" –


means elements have a defined order,
and indexing works. Order is preserved.

4. Return multiple values from function –


use tuple. Example: Program 10-3.

5. Advantages of tuples over lists:

Immutable – can be used as dictionary keys.

Faster than lists.

Safer for data that shouldn't change.

6. When to use tuple/dictionary:

Tuple: fixed collection of items (e.g., coordinates,


RGB values, record fields).
Dictionary: mapping between keys and values
(e.g., phonebook, student marks, configuration
settings).

7. Immutability rebuilds variable –


example with int:

python

x = 5
print(id(x)) # some id
x = x + 2
print(id(x)) # new id – new object created

But tuple itself is immutable; its elements if mutable


(like list) can be changed.

8. Error in statement 2: tuple1 = (5) is


not a tuple, it's an int. len() expects a
sequence. Correct by adding comma:
tuple1 = (5,) .

PROGRAMMING PROBLEMS (Outline


Solutions)
1. Email IDs tuple – use split('@') to get
username and domain.

2. Check student in tuple – use in operator.

3. Highest 2 values in dictionary – get values, sort,


pick top two.

4. Dictionary from string – loop and count


characters.

5. Friends phonebook – dictionary with name as


key, phone as value; implement menu for add,
delete, modify, check, sort.

CASE STUDY-BASED QUESTIONS


(Brief Ideas)

1. Banking system – functions for deposit,


withdrawal, fixed deposit; use dictionary for
account data; maintain minimum balance.

2. Quiz system – dictionary for questions and


answers; admin functions to add/modify/delete;
user registration; score tracking.

3. Heritage sites – dictionary with site name as key,


details as value (maybe tuple); admin functions;
search by name or state.
4. Reservation system – similar to railway; use
dictionaries for trains, seats, bookings; functions
for booking, cancellation, availability.

IMPORTANT EXAM TIPS

Tuple vs List: Tuple immutable, list mutable.

Single element tuple: Must have comma: (5,)


not (5) .

Dictionary keys: Must be immutable (string,


number, tuple). Lists cannot be keys.

Accessing: Use dict[key] (raises error if


missing) or [Link](key) (returns None).

Membership in dict: checks keys only.

Traversal: for key in dict or


for k,v in [Link]() .

Methods: Know keys() , values() , items() ,


get() , update() , del , clear() .

Tuple assignment: Great for swapping without


temp variable.

Return multiple values: Functions return tuples


implicitly if comma-separated.
This guide covers every concept from Chapter 10.
Practice writing programs and using these data
structures. Good luck for your exam!

Continue with DeepSeek

You might also like