0% found this document useful (0 votes)
4 views32 pages

Python Notes

The document provides comprehensive study notes on Python programming for Class 11 Computer Science, covering topics such as Python basics, data types, operators, and input/output operations. It includes detailed explanations of Python features, execution modes, data types like integers, floats, and strings, as well as operators and expressions. The notes emphasize Python's readability, versatility, and dynamic typing, making it suitable for beginners.
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)
4 views32 pages

Python Notes

The document provides comprehensive study notes on Python programming for Class 11 Computer Science, covering topics such as Python basics, data types, operators, and input/output operations. It includes detailed explanations of Python features, execution modes, data types like integers, floats, and strings, as well as operators and expressions. The notes emphasize Python's readability, versatility, and dynamic typing, making it suitable for beginners.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming – Complete Study Notes

PYTHON PROGRAMMING
Complete Study Notes
Class 11 Computer Science

Topics Covered:
• Introduction to Python & Basics
• Data Types & Operators
• Expressions, Type Conversion & I/O
• Errors & Flow of Control
• Conditional & Iterative Statements
• Strings, Lists, Tuples & Dictionaries
• Python Modules

Class 11 Computer Science | Page 1 of 32


Python Programming – Complete Study Notes

Chapter 1: Introduction to Python

1.1 What is Python?


Python is a high-level, interpreted, general-purpose programming language. It was created by Guido
van Rossum and first released in 1991. Python emphasizes code readability with its use of significant
indentation.

1.2 Features of Python


•​ Simple and Easy to Learn: Python has a clean and readable syntax, making it ideal for
beginners.
•​ Interpreted: Python code is executed line by line; no compilation step is required.
•​ High-Level Language: Python handles memory management automatically.
•​ Object-Oriented: Supports classes, objects, and inheritance.
•​ Dynamically Typed: You do not need to declare variable types; Python determines them at
runtime.
•​ Platform Independent: Python code runs on Windows, macOS, Linux without modification.
•​ Extensive Standard Library: Python comes with a rich set of built-in modules.
•​ Free and Open Source: Python is freely available and its source code can be modified.
•​ Versatile: Used in web development, data science, AI, automation, scientific computing, etc.

1.3 Hello World Program


The simplest Python program prints text to the screen:
print("Hello, World!")
# Output: Hello, World!

1.4 Execution Modes


Interactive Mode
In interactive mode, you type Python commands directly into the Python shell (>>> prompt) and see the
result immediately.
>>> 2 + 3
5
>>> print("Hi")
Hi
•​ Best for: Quick calculations and testing small code snippets
•​ Start: Type 'python' or 'python3' in the terminal

Script Mode
In script mode, you write Python code in a file (with .py extension) and run it all at once.
# save as [Link]

Class 11 Computer Science | Page 2 of 32


Python Programming – Complete Study Notes
print("Hello from script mode")
# Run with: python [Link]
•​ Best for: Writing programs with multiple lines of code
•​ Allows saving and re-running code

1.5 Python Character Set


A character set is the set of characters Python recognizes. Python uses Unicode character set
(supports multiple languages).
Category Characters
Letters A–Z, a–z (uppercase and lowercase alphabets)
Digits 0–9 (used in numbers and identifiers, not as first char)
Whitespace Space, \t (tab), \n (newline)
Special Symbols + - * / = == () {} [] : # ' " , . ; @ _ &

1.6 Python Tokens


Tokens are the smallest building blocks of a Python program. Every statement is made up of tokens.
Token Type Description Examples
Keywords Reserved words with special if, else, while, for, True, False, None, def
meaning in Python
Identifiers Names for variables, name, total_marks, _value, myFunction
functions, classes, modules
Literals Fixed values/constants used 100, 3.14, 'Python', True, None
directly in code
Operators Symbols that perform +, -, *, /, ==, !=, and, or, not
operations on data
Punctuators Symbols used to structure (), {}, [], :, ,, ;, @, =
code

Keywords
Keywords are predefined reserved words that have special meaning and cannot be used as identifiers.
Category Keywords
Value Keywords True, False, None
Logical/Identity/Membership and, or, not, in, is
Control Flow if, elif, else, for, while, break, continue, pass
Functions & Classes def, return, lambda, class, yield
Exception Handling try, except, finally, raise, assert

Class 11 Computer Science | Page 3 of 32


Python Programming – Complete Study Notes

Import & Aliasing import, from, as


Variable Scope global, nonlocal, del
Async Programming async, await

Identifiers – Rules
•​ Can contain letters (A-Z, a-z), digits (0-9), and underscore (_)
•​ Must start with a letter or underscore, NOT a digit
•​ Cannot use Python keywords as identifiers
•​ Case-sensitive: Name and name are different
•​ No length limit, but should be meaningful
Valid: studentName, _rollNumber, marks123
Invalid: 2score (starts with digit), class (keyword), my-name (contains -)

1.7 Variables, L-value and R-value


A variable is a named location in memory that stores a value. In Python, variables are dynamically
typed — you don't need to declare their type.
x = 10 # x is a variable storing integer 10
name = "Alice" # name stores a string

L-value and R-value


•​ L-value (Left value): The variable on the left side of assignment — refers to a memory location
where a value is stored.
•​ R-value (Right value): The value or expression on the right side — the data being assigned.
x = 5 + 3 # x is L-value, 5+3 is R-value
📝 Note: The L-value must always be a valid variable name. The R-value is evaluated first, then stored in
the L-value.

1.8 Comments
Comments are used to explain code and are ignored by Python during execution.

Single-line Comment
# This is a single-line comment
x = 10 # This sets x to 10

Multi-line Comment
"""
This is a multi-line
comment using triple quotes
"""
★ Always use comments to make your code readable and maintainable.

Class 11 Computer Science | Page 4 of 32


Python Programming – Complete Study Notes

Class 11 Computer Science | Page 5 of 32


Python Programming – Complete Study Notes

Chapter 2: Data Types in Python

A data type defines the kind of value a variable can store and what operations can be performed on it.
Python has the following built-in data types:

2.1 Numeric Data Types


Integer (int)
Whole numbers without decimal points. Can be positive, negative, or zero. No size limit in Python.
a = 10 # positive integer
b = -5 # negative integer
c = 0 # zero
big = 99999999999 # very large integer, no overflow!

Floating Point (float)


Numbers with decimal points or in scientific (exponent) notation.
pi = 3.14159
temp = -0.5
sci = 1.5e3 # = 1500.0 (1.5 × 10³)
small = 2e-2 # = 0.02

Complex Numbers (complex)


Numbers with a real part and an imaginary part. Written as a+bj.
z1 = 4 + 5j
z2 = 2j
print([Link], [Link]) # Output: 4.0 5.0

2.2 Boolean Data Type


Boolean represents one of two values: True or False. Booleans are case-sensitive.
x = True
y = False
print(x == y) # Output: False
print(True + 5) # Output: 6 (True = 1)
print(False + 3)# Output: 3 (False = 0)

Value As Integer Truthy/Falsy


True 1 Truthy
False 0 Falsy
0, 0.0, '', [], {}, None 0 Falsy

Class 11 Computer Science | Page 6 of 32


Python Programming – Complete Study Notes

Any non-zero value or non-zero Truthy


non-empty container

2.3 Sequence Data Types


String (str)
A string is an ordered sequence of characters enclosed in single or double quotes.
s1 = 'Hello'
s2 = "World"
s3 = """Multi-line
string here"""

List
An ordered, mutable (changeable) collection of items. Items can be of different types.
fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'hello', 3.14, True]

Tuple
An ordered, immutable (unchangeable) collection of items. Once created, cannot be modified.
coords = (10, 20)
info = ('Alice', 25, 'Engineer')

2.4 None Type


None represents the absence of a value. It is Python's null value.
result = None
print(type(result)) # <class 'NoneType'>

2.5 Mapping Data Type – Dictionary


A dictionary stores data as key-value pairs. Keys must be unique and immutable.
student = {'name': 'Aarav', 'age': 16, 'marks': 92}
print(student['name']) # Output: Aarav

2.6 Mutable vs Immutable Data Types


Category Data Types Can be changed after creation?
Mutable List, Dictionary, Set YES – items can be
added/removed/modified
Immutable int, float, complex, bool, str, NO – value cannot be changed once
tuple created

Class 11 Computer Science | Page 7 of 32


Python Programming – Complete Study Notes
★ Immutable objects are safer in multi-threading and as dictionary keys. Strings in Python are
immutable — every string operation creates a new string.

Class 11 Computer Science | Page 8 of 32


Python Programming – Complete Study Notes

Chapter 3: Operators in Python

3.1 Arithmetic Operators


Operator Name Example Result
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 3*4 12
/ Division (float) 10 / 3 3.333...
// Floor Division 10 // 3 3
% Modulus 10 % 3 1
(remainder)
** Exponentiation 2 ** 5 32

3.2 Relational (Comparison) Operators


Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>4 True
< Less than 3<5 True
>= Greater than or equal 5 >= 5 True
<= Less than or equal 3 <= 7 True

3.3 Logical Operators


Operator Description Example Result
and True if both are True True and False False
or True if at least one is True True or False True
not Reverses the Boolean value not True False

3.4 Assignment Operators


Operator Example Equivalent To
= x=5 x=5

Class 11 Computer Science | Page 9 of 32


Python Programming – Complete Study Notes

+= x += 3 x=x+3
-= x -= 2 x=x-2
*= x *= 4 x=x*4
/= x /= 2 x=x/2
//= x //= 3 x = x // 3
%= x %= 5 x=x%5
**= x **= 2 x = x ** 2

3.5 Identity Operators


Identity operators check whether two variables refer to the same object in memory (not just equal
value).
Operator Description Example
is True if both refer to the SAME object in x is y
memory
is not True if they refer to DIFFERENT objects x is not y
a = [1, 2]
b = a
c = [1, 2]
print(a is b) # True (same object)
print(a is c) # False (different objects, same value)
print(a == c) # True (same value)

3.6 Membership Operators


Membership operators test whether a value exists within a sequence (string, list, tuple, etc.).
Operator Description Example Result
in True if value found in 'a' in 'cat' True
sequence
not in True if value NOT found in 5 not in [1,2,3] True
sequence
fruits = ['apple', 'mango', 'banana']
print('mango' in fruits) # True
print('grapes' not in fruits) # True

Class 11 Computer Science | Page 10 of 32


Python Programming – Complete Study Notes

Chapter 4: Expressions, Type Conversion & I/O

4.1 Precedence of Operators (PEMDAS/BODMAS)


When an expression contains multiple operators, Python uses operator precedence to decide the order
of evaluation.
Priority Operator(s) Description
1 (Highest) ** Exponentiation
2 +x, -x, ~x Unary plus, minus, bitwise NOT
3 *, /, //, % Multiplication, Division, Floor, Modulo
4 +, - Addition, Subtraction
5 <<, >> Bitwise shifts
6 & Bitwise AND
7 ^ Bitwise XOR
8 | Bitwise OR
9 ==, !=, >, <, >=, <=, is, is not, Comparison & Membership
in, not in
10 not Logical NOT
11 and Logical AND
12 (Lowest) or Logical OR

4.2 Expressions
An expression is a combination of values, variables, and operators that evaluates to a single value.
x = 5
y = 3
result = x * 2 + y - 1 # Expression
# Evaluation: (5*2) + 3 - 1 = 10 + 3 - 1 = 12

4.3 Type Conversion


Implicit Conversion (Automatic)
Python automatically converts one data type to another when needed (lower to higher type to avoid
data loss).
a = 5 # int
b = 2.5 # float
c = a + b # Python converts a to float automatically
print(c) # Output: 7.5 (float)

Class 11 Computer Science | Page 11 of 32


Python Programming – Complete Study Notes
Explicit Conversion (Type Casting)
The programmer manually converts one type to another using built-in functions.
Function Converts to Example
int(x) Integer int('42') → 42, int(3.9) → 3
float(x) Float float('3.14') → 3.14, float(5) → 5.0
str(x) String str(100) → '100', str(3.14) → '3.14'
bool(x) Boolean bool(0) → False, bool(5) → True
complex(x) Complex complex(3) → (3+0j)
x = '42'
y = int(x) + 8 # Explicit conversion
print(y) # Output: 50

4.4 Input and Output


Taking Input from Console
The input() function reads a line from standard input and returns it as a string.
name = input('Enter your name: ')
age = int(input('Enter your age: ')) # Convert to int
marks = float(input('Enter marks: ')) # Convert to float

Displaying Output
The print() function displays values to the console.
print("Hello, World!")
x, y = 10, 20
print(x, y) # Output: 10 20
print(x, y, sep=', ') # Output: 10, 20
print(x, y, sep='-') # Output: 10-20
print('Hello', end='') # No newline at end
print('World') # Output: Hello World (on same line)

Formatted Output using f-strings


name = 'Aarav'
marks = 92.5
print(f'Name: {name}, Marks: {marks}')
# Output: Name: Aarav, Marks: 92.5

Class 11 Computer Science | Page 12 of 32


Python Programming – Complete Study Notes

Chapter 5: Errors in Python

When Python encounters a problem in a program, it reports an error. Understanding errors is essential
for debugging.

5.1 Syntax Errors


Syntax errors occur when code does not follow the rules (grammar) of Python. These are detected
before the program runs.
# Missing colon
if x > 5
print('hi')
# SyntaxError: expected ':'

# Mismatched parenthesis
print('Hello'
# SyntaxError: '(' was never closed

5.2 Logical Errors


Logical errors occur when the program runs without crashing but produces incorrect output due to a
flaw in the algorithm/logic.
# Finding average of two numbers
a = 10
b = 20
avg = a + b / 2 # Wrong! Should be (a+b)/2
print(avg) # Outputs 20.0 instead of 15.0
📝 Note: Logical errors are the hardest to find because Python does not report them. You must test your
program with known inputs and verify outputs.

5.3 Runtime Errors


Runtime errors (also called exceptions) occur during program execution when something unexpected
happens.
Error Type Cause Example
ZeroDivisionError Division by zero 10 / 0
NameError Using an undefined variable print(x) when x not defined
TypeError Wrong data type for an 'hello' + 5
operation
ValueError Invalid value for a function int('abc')
IndexError List/string index out of range lst[10] when list has 5 items

Class 11 Computer Science | Page 13 of 32


Python Programming – Complete Study Notes

KeyError Dictionary key not found d['missing_key']


AttributeError Calling a method on wrong [Link]() when x is an int
type

Class 11 Computer Science | Page 14 of 32


Python Programming – Complete Study Notes

Chapter 6: Flow of Control

6.1 Introduction
Flow of control refers to the order in which individual statements or instructions of a program are
executed.
Type Description
Sequential Flow Default – statements execute one after another, top to bottom
Conditional Flow Certain blocks execute only when a specific condition is True
Iterative (Loop) Flow A block of statements is repeated multiple times

6.2 Indentation
Python uses indentation (whitespace at the beginning of a line) to define code blocks instead of curly
braces {} like other languages.
if x > 0:
print('Positive') # This is indented – belongs to if
print('Number') # This too
print('Done') # Not indented – outside if
★ Consistent indentation is mandatory in Python. Use 4 spaces or 1 tab, but never mix them.

6.3 Conditional Statements


if Statement
if condition:
# code to execute when condition is True

age = 18
if age >= 18:
print('You can vote')

if-else Statement
if condition:
# code when True
else:
# code when False

num = -5
if num >= 0:
print('Positive or Zero')
else:
print('Negative')
Class 11 Computer Science | Page 15 of 32
Python Programming – Complete Study Notes

if-elif-else Statement
marks = 75
if marks >= 90:
print('Grade: A')
elif marks >= 75:
print('Grade: B')
elif marks >= 60:
print('Grade: C')
else:
print('Grade: D')

Practical Programs
Absolute Value:
num = int(input('Enter number: '))
if num < 0:
num = -num
print('Absolute value:', num)

Sort 3 Numbers:
a = int(input('Enter a: '))
b = int(input('Enter b: '))
c = int(input('Enter c: '))
if a <= b and b <= c:
print(a, b, c)
elif a <= c and c <= b:
print(a, c, b)
elif b <= a and a <= c:
print(b, a, c)
elif b <= c and c <= a:
print(b, c, a)
elif c <= a and a <= b:
print(c, a, b)
else:
print(c, b, a)

Class 11 Computer Science | Page 16 of 32


Python Programming – Complete Study Notes

Chapter 7: Iterative Statements (Loops)

7.1 for Loop


A for loop is used to iterate over a sequence (list, string, tuple, range) or any iterable object.
for variable in sequence:
# code to execute

# Example: Print 1 to 5
for i in range(1, 6):
print(i, end=' ')
# Output: 1 2 3 4 5

range() Function
Syntax Description Example Generates
range(stop) 0 to stop-1 range(5) 0,1,2,3,4
range(start, stop) start to stop-1 range(2, 7) 2,3,4,5,6
range(start, stop, step) start to stop-1 with step range(1, 10, 2) 1,3,5,7,9
range(stop, start, -step) Countdown range(5, 0, -1) 5,4,3,2,1

7.2 while Loop


A while loop repeats a block of code as long as a condition is True.
while condition:
# code to execute
# update the condition variable

# Example: Sum of digits


n = int(input('Enter number: '))
total = 0
while n > 0:
total += n % 10
n //= 10
print('Sum of digits:', total)

7.3 break and continue


break Statement
The break statement exits the loop immediately when a condition is met.
for i in range(1, 11):
if i == 6:

Class 11 Computer Science | Page 17 of 32


Python Programming – Complete Study Notes
break
print(i, end=' ')
# Output: 1 2 3 4 5

continue Statement
The continue statement skips the rest of the current iteration and moves to the next one.
for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=' ')
# Output: 1 3 5 7 9 (skips even numbers)

7.4 Nested Loops


A loop inside another loop is called a nested loop.
# Multiplication table using nested loops
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end='\t')
print()
# Output:
# 1 2 3
# 2 4 6
# 3 6 9

Pattern Programs
Right Triangle Pattern:
n = 5
for i in range(1, n+1):
for j in range(i):
print('*', end='')
print()

Factorial of a Number:
n = int(input('Enter n: '))
fact = 1
for i in range(1, n+1):
fact *= i
print(f'{n}! = {fact}')

Sum of Series 1 + 2 + ... + n:


n = int(input('Enter n: '))
total = n * (n + 1) // 2
print('Sum =', total)

Class 11 Computer Science | Page 18 of 32


Python Programming – Complete Study Notes

Class 11 Computer Science | Page 19 of 32


Python Programming – Complete Study Notes

Chapter 8: Strings

8.1 Introduction to Strings


A string is a sequence of characters enclosed in single, double, or triple quotes. Strings in Python are
immutable.
s = 'Hello'
s = "World"
s = '''Multi-line
string'''

8.2 String Operations


Indexing
Each character has a position (index). Positive index starts from 0, negative from -1 (end).
s = 'Python'
print(s[0]) # P (first character)
print(s[-1]) # n (last character)
print(s[2]) # t

Slicing
Extract a portion of a string using s[start:stop:step].
s = 'Python'
print(s[1:4]) # yth (index 1,2,3)
print(s[:3]) # Pyt (start to index 2)
print(s[2:]) # thon (index 2 to end)
print(s[::2]) # Pto (every 2nd character)
print(s[::-1]) # nohtyP (reversed)

Concatenation (+)
s1 = 'Hello'
s2 = ' World'
print(s1 + s2) # Hello World

Repetition (*)
s = 'Ha'
print(s * 3) # HaHaHa

Membership (in / not in)


s = 'Python'
print('Py' in s) # True

Class 11 Computer Science | Page 20 of 32


Python Programming – Complete Study Notes
print('Java' not in s) # True

Traversal
s = 'Hello'
for ch in s:
print(ch, end=' ') # H e l l o

8.3 String Methods


Method Description Example Output
len(s) Length of string len('Hello') 5
capitalize() First letter uppercase 'hello'.capitalize() 'Hello'
title() First letter of each word 'hi there'.title() 'Hi There'
uppercase
lower() All lowercase 'HELLO'.lower() 'hello'
upper() All uppercase 'hello'.upper() 'HELLO'
count(sub) Count occurrences of 'banana'.count('a') 3
substring
find(sub) Index of first occurrence 'hello'.find('l') 2
(-1 if not found)
index(sub) Like find but raises error 'hello'.index('e') 1
if not found
startswith(sub) True if starts with sub 'Python'.startswith('Py') True
endswith(sub) True if ends with sub '[Link]'.endswith('.py') True
isalnum() True if all alphanumeric 'abc123'.isalnum() True
isalpha() True if all letters 'hello'.isalpha() True
isdigit() True if all digits '123'.isdigit() True
islower() True if all lowercase 'hello'.islower() True
isupper() True if all uppercase 'HELLO'.isupper() True
isspace() True if all whitespace ' '.isspace() True
lstrip() Remove leading ' hi'.lstrip() 'hi'
whitespace
rstrip() Remove trailing 'hi '.rstrip() 'hi'
whitespace
strip() Remove both sides ' hi '.strip() 'hi'
whitespace
replace(old, new) Replace all occurrences 'hello'.replace('l','r') 'herro'

Class 11 Computer Science | Page 21 of 32


Python Programming – Complete Study Notes

join(iterable) Join with string as ', '.join(['a','b','c']) 'a, b, c'


separator
split(sep) Split string into list 'a,b,c'.split(',') ['a','b','c']
partition(sep) Split into 3-part tuple 'a:b'.partition(':') ('a',':','b')

Class 11 Computer Science | Page 22 of 32


Python Programming – Complete Study Notes

Chapter 9: Lists

9.1 Introduction to Lists


A list is an ordered, mutable collection of items. Lists allow duplicate elements and can store items of
different data types.
fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'hello', 3.14, True, None]
empty = []

9.2 Indexing & Slicing


lst = [10, 20, 30, 40, 50]
print(lst[0]) # 10
print(lst[-1]) # 50
print(lst[1:4]) # [20, 30, 40]
print(lst[::-1]) # [50, 40, 30, 20, 10] reversed

9.3 List Operations


Operation Example Result
Concatenation (+) [1,2] + [3,4] [1, 2, 3, 4]
Repetition (*) [0] * 3 [0, 0, 0]
Membership (in) 3 in [1,2,3] True
Length (len) len([1,2,3,4]) 4

9.4 List Methods


Method Description Example
append(x) Add x to end of list [Link](6)
extend(iterable) Add all elements of iterable to end [Link]([7,8])
insert(i, x) Insert x at index i [Link](2, 99)
remove(x) Remove first occurrence of x [Link](30)
pop(i) Remove & return item at index i [Link]() or [Link](1)
(default: last)
index(x) Return index of first occurrence of [Link](20)
x
count(x) Count occurrences of x [Link](5)
sort() Sort list in place (ascending) [Link]()

Class 11 Computer Science | Page 23 of 32


Python Programming – Complete Study Notes

sort(reverse=True) Sort descending [Link](reverse=True)


reverse() Reverse list in place [Link]()
sorted(lst) Return new sorted list sorted(lst)
min(lst) Minimum value min([3,1,5]) → 1
max(lst) Maximum value max([3,1,5]) → 5
sum(lst) Sum of all values sum([1,2,3]) → 6
len(lst) Length of list len([1,2,3]) → 3
list() Create list from iterable list(range(5)) → [0,1,2,3,4]

9.5 Nested Lists


matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix[1][2]) # 6 (row 1, col 2)

9.6 Practical Programs


Linear Search on a List:
lst = [15, 30, 45, 60, 75]
key = int(input('Search for: '))
found = False
for i in range(len(lst)):
if lst[i] == key:
print(f'Found at index {i}')
found = True
break
if not found:
print('Not found')

Finding Maximum and Minimum:


nums = [3, 7, 1, 9, 4]
print('Max:', max(nums)) # 9
print('Min:', min(nums)) # 1
print('Mean:', sum(nums)/len(nums)) # 4.8

Class 11 Computer Science | Page 24 of 32


Python Programming – Complete Study Notes

Chapter 10: Tuples

10.1 Introduction to Tuples


A tuple is an ordered, immutable collection of items. Once created, the items cannot be changed,
added, or removed.
t1 = (1, 2, 3)
t2 = ('Alice', 25, 'Engineer')
t3 = (5,) # Single-element tuple (note the comma)
t4 = () # Empty tuple
t5 = 1, 2, 3 # Parentheses are optional

10.2 Indexing & Slicing


t = (10, 20, 30, 40, 50)
print(t[0]) # 10
print(t[-1]) # 50
print(t[1:4]) # (20, 30, 40)

10.3 Tuple Operations


t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4) - Concatenation
print(t1 * 3) # (1, 2, 1, 2, 1, 2) - Repetition
print(2 in t1) # True - Membership

10.4 Tuple Methods & Functions


Function/Method Description Example Output
len(t) Number of items len((1,2,3)) 3
tuple() Create tuple from tuple([1,2,3]) (1,2,3)
iterable
count(x) Count occurrences of x (1,2,1,3).count(1) 2
index(x) First index of x (10,20,30).index(20) 1
min(t) Minimum value min((3,1,5)) 1
max(t) Maximum value max((3,1,5)) 5
sum(t) Sum of values sum((1,2,3)) 6
sorted(t) Returns sorted list sorted((3,1,5)) [1,3,5]

Class 11 Computer Science | Page 25 of 32


Python Programming – Complete Study Notes
10.5 Tuple Assignment (Unpacking)
a, b, c = (10, 20, 30) # Tuple unpacking
print(a, b, c) # 10 20 30

# Swap variables using tuple


x, y = 5, 10
x, y = y, x
print(x, y) # 10 5

10.6 Nested Tuples


nested = ((1,2),(3,4),(5,6))
print(nested[1][0]) # 3

📝 Note: Tuples are faster than lists and should be used when data should not change. They can be used
as dictionary keys since they are immutable.

Class 11 Computer Science | Page 26 of 32


Python Programming – Complete Study Notes

Chapter 11: Dictionaries

11.1 Introduction to Dictionaries


A dictionary is an unordered, mutable collection of key-value pairs. Each key must be unique and
immutable (str, int, tuple). Values can be of any type.
student = {'name': 'Aarav', 'class': 11, 'marks': 92}
empty = {}
d = dict(name='Riya', age=17)

11.2 Accessing Items


d = {'name': 'Aarav', 'marks': 92}
print(d['name']) # Aarav
print([Link]('marks')) # 92
print([Link]('age')) # None (no error)
print(d['age']) # KeyError!

11.3 Mutability of Dictionaries


student = {'name': 'Aarav'}

# Add new key


student['roll'] = 23

# Modify existing
student['name'] = 'Rohan'

# Delete a key
del student['roll']
print(student) # {'name': 'Rohan'}

11.4 Traversing a Dictionary


d = {'a': 1, 'b': 2, 'c': 3}

for k in d: # keys
print(k)

for v in [Link](): # values


print(v)

for k, v in [Link](): # key-value pairs


print(k, ':', v)

Class 11 Computer Science | Page 27 of 32


Python Programming – Complete Study Notes

11.5 Dictionary Methods


Method Description
len(d) Number of key-value pairs
dict() Create a dictionary
keys() Returns view of all keys
values() Returns view of all values
items() Returns view of all (key,value) pairs
get(key, default) Returns value or default if key not found
update(d2) Add/update items from d2
del d[key] Delete a specific key
clear() Remove all items from dictionary
fromkeys(keys, val) Create dict with keys and same value
copy() Returns shallow copy
pop(key) Remove and return value of key
popitem() Remove and return last inserted pair
setdefault(key, val) Returns value; inserts if key missing
max(d) / min(d) Max/min key (alphabetically for strings)
sorted(d) Returns sorted list of keys

11.6 Practical Programs


Count character frequency:
text = 'banana'
freq = {}
for ch in text:
freq[ch] = [Link](ch, 0) + 1
print(freq) # {'b':1, 'a':3, 'n':2}

Employee Salary Dictionary:


employees = {
'Aman': 45000,
'Riya': 52000,
'Karan': 60000
}
for name, salary in [Link]():
print(f'{name}: Rs. {salary}')

Class 11 Computer Science | Page 28 of 32


Python Programming – Complete Study Notes

Chapter 12: Python Modules

12.1 Introduction to Modules


A module is a file containing Python code (functions, variables, classes) that can be reused in other
programs. Python has many built-in modules.

12.2 Importing Modules


Using import
import math
print([Link](25)) # 5.0
print([Link]) # 3.14159...

Using from...import
from math import sqrt, pi
print(sqrt(16)) # 4.0 (no math. prefix needed)
print(pi) # 3.14159...

Using Alias
import math as m
print([Link](9)) # 3.0

12.3 Math Module


Function/Constant Description Example Output
[Link] Value of π [Link] 3.14159265..
.
math.e Value of e (Euler's math.e 2.71828...
number)
[Link](x) Square root of x [Link](16) 4.0
[Link](x) Smallest integer >= x [Link](4.2) 5
(ceiling)
[Link](x) Largest integer <= x [Link](4.9) 4
(floor)
[Link](x, y) x to the power y (returns [Link](2, 10) 1024.0
float)
[Link](x) Absolute value (float) [Link](-7.5) 7.5
[Link](x) Sine of x (x in radians) [Link]([Link]/2) 1.0

Class 11 Computer Science | Page 29 of 32


Python Programming – Complete Study Notes

[Link](x) Cosine of x (radians) [Link](0) 1.0


[Link](x) Tangent of x (radians) [Link]([Link]/4) 1.0

12.4 Random Module


Function Description Example Output
[Link]() Random float between 0.0 [Link]() 0.7342...
and 1.0 (varies)
[Link](a, b) Random integer between a [Link](1, 4 (varies)
and b (inclusive) 6)
[Link](start, Random value from range [Link] 6 (varies)
stop, step) (0, 10, 2)
import random
print([Link]()) # e.g., 0.5432
print([Link](1, 100)) # e.g., 73
print([Link](2, 20, 2)) # Even number 2-18

12.5 Statistics Module


Function Description Example Output
[Link](data) Arithmetic average mean([1,2,3,4,5]) 3
[Link](data) Middle value (sorted) median([1,3,5,7,9]) 5
[Link](data) Most frequent value mode([1,2,2,3,3,3]) 3
import statistics
data = [10, 20, 30, 20, 40, 20]
print([Link](data)) # 23.33...
print([Link](data)) # 20
print([Link](data)) # 20

★ Always import only what you need to keep programs efficient. Use 'from module import
function' to avoid typing module name repeatedly.

Class 11 Computer Science | Page 30 of 32


Python Programming – Complete Study Notes

Quick Reference: Built-in Functions Summary

Function Works On Description


len() str, list, tuple, dict Returns number of elements
type() Any Returns data type of object
print() Any Displays output to console
input() - Reads user input as string
int(), float(), str(), bool() Any Type conversion functions
range() - Generates sequence of numbers
max() list, tuple, str Returns maximum value
min() list, tuple, str Returns minimum value
sum() list, tuple (numeric) Returns sum of all values
sorted() list, tuple, str Returns new sorted list
abs() int, float Returns absolute value
round(x, n) float Rounds to n decimal places
id() Any Returns memory address of object
dir() Module/Object Lists all attributes/methods

Key Concepts Summary

Concept Key Points


Mutable Types List, Dictionary, Set – can be modified after creation
Immutable Types int, float, str, tuple, bool – cannot be changed
Indexing Starts at 0 (positive), -1 from end (negative)
Slicing s[start:stop:step] – stop index is excluded
for loop Iterates over sequences; use range() for numeric loops
while loop Runs while condition is True; update condition inside loop
Function vs Method Methods are called on objects (e.g., [Link]()), functions are
standalone (e.g., len())
Dictionary Keys Must be unique and immutable (str, int, tuple)
break Exits the loop immediately
continue Skips current iteration, proceeds to next

Class 11 Computer Science | Page 31 of 32


Python Programming – Complete Study Notes

Indentation 4 spaces or 1 tab; defines code blocks in Python


Type Conversion Implicit (automatic) vs Explicit (manual using int(), float(), str())
Comments # for single line; triple quotes for multi-line
Module import import module OR from module import function

Class 11 Computer Science | Page 32 of 32

You might also like