Python Notes X CodeWithNishchal
Python Notes X CodeWithNishchal
Roadmap:Python Roadmap
1.3 Why Learn Python?
al
1.4 Main Features of Python
1.5 Python Version
h
1.6 How Python Code Runs
1.7 Compiler vs Interpreter Basics
hc
Chapter 2: Environment Setup is
.1 Installing Python
2
2.2 Checking Python Version
N
2.3 Installing VS Code
2.4 Terminal and Command Line Basics
ith
4.3 Boolean Data Type
al
4.3.1True
4.3.2False
4.4NoneType
h
4.5 Type Checking withtype()
4.6 Type Conversion
hc
4.7 Mutable vs Immutable Data Types
4.8 Simple Memory Understanding
4.9 Quick Revision
is
N
Chapter 5: Operators
.1 Arithmetic Operators
5
ith
al
Chapter 8: Loops and Iteration
.1 for Loop
8
h
8.2 while Loop
hc
8.3 break
8.4 continue
8.5 pass
8.6 else with Loops is
8.7 Nested Loops
8.8 range()
N
8.9 enumerate()
8.10 zip()
8.11 Iterator Protocol Basics
ith
8.12 StopIteration
9.1 Lists
.1.1 Creating Lists
9
9.1.2 Accessing List Values
9.1.3 Updating List Values
od
9.2 Tuples
.2.1 Creating Tuples
9
9.2.2 Tuple Immutability
9.2.3 Tuple Packing
9.2.4 Tuple Unpacking
.2.5 Named Tuples
9
9.2.6 Tuple vs List
9.2.7 Tuple methods
9.2.8 Tuple operations
9.2.9 Tuple packing
9.2.10 Tuple unpacking
9.2.11 Extended Tuple Unpacking
9.2.12 Named Tuples
9.2.13 Tuple vs List
9.3 Dictionaries
.3.1 Creating Dictionaries
9
al
9.3.2 Accessing Dictionary Values
9.3.3 Updating Dictionary Values
h
9.3.4 Dictionary Methods
9.3.5get()Method
hc
9.3.6 Nested Dictionaries
9.3.7 Dictionary Comprehensions
9.3.8 Merging Dictionaries
9.3.9 Real-World Dictionary Use Cases
is
9.3.10 Nested Dictionaries
9.3.11 Dictionary Comprehensions
N
9.3.12 Merging Dictionaries
9.3.13 Copying Dictionaries
ith
9.4 Sets
eW
9.4.9 Union
9.4.10 Intersection
9.4.11 Difference
9.4.12 Symmetric Difference
9.4.13 Subset, Superset, & Disjoint Sets
9.4.14 Set Methods
9.4.15 Set Operators
9.4.16 Updating Sets with Operations
9.4.17 Copying Sets
9.4.18 Frozen Sets
9.4.19 Set Comprehensions
.4.20 Set Conversion
9
9.4.21 Set vs List vs Tuple
al
Chapter 10: Functions
0.1 What is a Function?
1
h
10.2 Defining Functions
10.3 Calling Functions
hc
10.4 Parameters
10.5 Arguments
10.6 Positional Arguments
10.7 Return Values is
10.8 Returning Multiple Values
10.9 Default Parameters
N
10.10 Keyword Arguments
10.11 *args
ith
10.12 **kwargs
10.13 *args vs **kwargs
10.14 Function Parameter Order
10.15 Docstrings
eW
11.4 filter()
11.5 reduce()
11.6 Recursion
11.7 Nested Functions
11.8 Closures
11.9 Function Annotations
11.10 Higher-Order Functions
Chapter 12: Scope and Namespaces
2.1 Local Scope
1
12.2 Global Scope
12.3 Local vs Global Scope
12.4 Variable Shadowing
12.5 global Keyword
12.6 Enclosing Scope
12.7 nonlocal Keyword
12.8 Built-in Scope
12.9 LEGB Rule
12.10 Namespace Concept
al
12.11 locals() and globals()
12.12 NameError & UnboundLocalError
12.13 Important Scope Summary Table
h
hc
Chapter 13: Modules and Packages
3.1 Importing Modules
1
13.2 Different Ways to Import
13.3 Standard Library Modules
13.4 Creating Your Own Modules
is
N
13.5 Importing Specific Code from Your Own Module
13.6 Module Search Path
13.7 Exploring a Module with dir()
ith
13.16 [Link]
13.17 Third-Party Packages
13.18 Circular Import Warning
C
14.3 Special Methods
al
4.3.1__str__
1
14.3.2__repr__
h
14.3.3__len__
14.3.4__getitem__
hc
14.3.5__add__
14.3.6__sub__
14.3.7__call__
14.3.8__enter__ & __exit__ is
14.3.9 Context Manager Real Use
14.3.10 Operator Overloading
N
14.3.11 Magic Methods / Dunder Methods
14.3.12 Reverse and In-place Operator Methods
ith
14.3.13__bool__
14.3.14__iter__and__next__
14.3.15__contains__
eW
16.1.7 Appending Files
al
16.1.8 File Modes
16.1.9withStatement
h
16.1.10 File Object Methods
16.1.11 Binary Files
hc
16.1.12 File Paths
16.1.13 BasicosModule
16.1.14 BasicpathlibModule
16.1.15 Encoding is
16.2 Exception Handling
N
6.2.1 try-except
1
16.2.2 Catching Exception Object
ith
16.2.6 finally
16.2.7 try-except-else-finally Flow
16.2.8 Raising Exceptions
16.2.9 Re-raising Exceptions
16.2.10 Custom Exceptions
od
al
17.2 Generators and Iterators
7.2.1 Generators and Iterators
1
h
17.2.2 Iterable vs Iterator
17.2.3 Iterator Protocol
hc
17.2.4__iter__
17.2.5__next__
17.2.6 Generator Functions
17.2.7yield is
17.2.8 Generator Expressions
17.2.9yield from
N
17.2.10 One-time Consumption of Iterators
17.2.11itertools
ith
6.4.1reModule
1
16.4.2 Pattern Matching
16.4.3 Regex Metacharacters
C
17.1.5 Locks
al
17.1.6 Synchronization
17.2 Multiprocessing
h
7.1.1 Managing Processes
1
hc
17.1.2 Process Pools
17.1.3 Memory Sharing Basics
17.1.4 Concurrent Futures
17.3.4Async Programming
7.4.1asyncio
1
17.4.2asyncand Coroutines
17.4.3await
17.4.4 Event Loop
17.4.5 Tasks
od
17.4.6[Link]()
17.4.7 Async Futures
17.4.8 Async Context Managers
17.4.9 Async vs Threading vs Multiprocessing
C
Chapter 1: Python Overview
1.1 History of Python
Python was created byGuido van Rossum.
He started working on Python in the late 1980s, and Python was first released in1991.
al
he language was designed to be simple, readable, and easy to use. Guido wanted Python
T
code to look clean and understandable, so programmers could focus more on solving
h
problems instead of writing complicated syntax.
hc
ython’s name does not come from the snake. It was inspired by a British comedy show
P
called“Monty Python’s Flying Circus.”
O
professionals.
is
ver time, Python became popular because it was easy for beginners and powerful for
N
Today, Python is used in many fields like:
ith
● eb development
W
● Automation
● Data science
● Artificial intelligence
eW
It is used to write programs for automation, web development, data handling, artificial
intelligence, machine learning, scripting, testing, and many other [Link] is popular
because its syntax is simple and easy to read.
Example:
PYTHON CODE
print("Hello, World!")
● It is beginner-friendly.
● It is used in many industries.
● It has simple syntax.
● It has many libraries.
al
● It is good for automation.
● It is widely used in AI, data science, and backend development.
h
1.4 Main Features of Python
hc
Feature Meaning
Easy syntax
High-level
is
Python code is simple and readable
Large library support Many built-in and external libraries are available
or modern learning, usePython 3. Python 2 is oldand should not be used for new
F
learning.
● ython code is written in.pyfiles.
P
● Python interpreter reads and runs the code.
● Python runs code from top to bottom.
● Output is shown on the screen.
al
1.7 Compiler vs Interpreter Basics
h
Before code runs, it must be translated into a form the computer can understand.
hc
There are two common translators:
● Compiler
● Interpreter is
Compiler
A compiler translates the whole program before running it.
N
Flow:Source Code → Compiler → Executable File → RunProgram
Examples of compiled languages:
ith
●
C
● C++
eW
● Go
● Rust
Interpreter
An interpreter runs code more directly.
od
Compiler vs Interpreter
Translation Translates full code before running Runs code more directly
Error checking Many errors found before running Errors can appear while running
.
1 ython installed on the system
P
2. A code editor like VS Code
3. Terminal/Command Prompt basics
4. Package managerpip
al
5. Virtual environment setup usingvenv
h
Install Python
hc
↓
Check Python Version
↓
Install VS Code is
↓
Write Python Code
N
↓
Run Python File
↓
ith
he safest way is to download Python from the official Python website. The official Python
T
downloads page provides the latest stable Python release and installers for different
operating systems.
od
For Windows
.
1 o to the official Python website.
G
C
Steps:
.
1 ownload the macOS installer from the official Python website.
D
2. Open the.pkgfile.
3. Follow the installation steps.
4. Open Terminal.
5. Check Python version.
al
For Linux
h
Check version: python3 --version
hc
For Ubuntu/Debian-based systems, Python can usually be installed with:
Windows
python --version or: py --version
macOS/Linux
eW
python3 --version
.
1 ownload VS Code from the official website.
D
2. Install it.
3. Open VS Code.
4. Go to Extensions.
5. Search forPython.
6. Install the official Python extension by Microsoft.
7. Open a Python file.
8. Select Python interpreter if VS Code asks.
Creating First Python File in VS Code
Create a file:[Link]
Write:print("Hello CodeWithNishchal")
Run the file.
Output: Hello CodeWithNishchal
al
. C
1 licking theRunbutton.
2. Right-clicking and selectingRun Python File in Terminal.
3. Opening terminal and running:
h
python [Link] or: python3 [Link]
hc
S Code’s Python extension provides multiple ways to run Python files, including the “Run
V
Python File in Terminal” option.
he terminal / command prompt is a place where we type commands to interact with the
T
computer.
eW
Check current folder pwd pwd hows the current folder/location in
S
od
terminal
List files and folders dir ls hows files and folders inside the
S
current folder
C
Go back one folder cd .. cd .. Moves one level back
[Link]
Example file:
PYTHON CODE
al
print("Terminal is running Python")
h
Output: Terminal is running Python
hc
2.5 Python Interpreter
The Python interpreter is the program that reads and runs Python code.
● ead
R
od
● Evaluate
● Print
● Loop
C
Python REPL allows us to run Python code line by line. It is useful for quick testing.
macOS/Linux: python3
al
Use: exit()
or press:
h
trl + Z then Enter on Windows
C
hc
Ctrl + D on macOS/Linux
● esting small calculations
T
● Checking syntax
● Trying functions
C
Examples:
Steps:
.
1 reate a project folder.
C
2. Open it in VS Code.
3. Create a new file.
4. Save it with the.pyextension.
5. Write Python code.
6. Run the file.
Example File
al
File name: [Link]
h
Code:
hc
PYTHON CODE
rint("Hello, Python")
p is
print("This is my first Python file")
N
Run:
Output:
eW
ello, Python
H
This is my first Python file
rint("Start")
p
name = "Nishchal"
print("Name:", name)
C
print("End")
Output:
tart
S
Name: Nishchal
End
Common Mistakes
● aving file as[Link].
S
● Forgetting.pyextension.
● Running the wrong file.
● Writing Python code in the terminal instead of a file.
● Not saving file before running.
● Giving file names with spaces.
Bad:my first python [Link]
al
Good:first_python_file.py
h
Best Practices
hc
● se lowercase file names.
U
● Use underscores for multiple words.
● Keep one project in one folder.
●
●
Save before running.
Keep file names meaningful.
is
N
2.8 Virtual Environments Usingvenv
ith
ython’s official documentation saysvenvis the standard tool for creating virtual
P
environments, and each virtual environment has its own independent set of installed Python
packages.
If both projects use the same global Python environment, package conflicts can happen.
Computer Python
↓
Project A → venv → packages for Project A
Project B → venv → packages for Project B
Project C → venv → packages for Project C
2.9 Installing Packages Usingpip
pipis Python’s package installer. It is used to install external libraries.
What is a Package?
al
Example packages:
h
Package Use
hc
requests Working with APIs
numpy
flask
Numerical computing
Web development
is
N
django Web development
ith
pytest Testing
Install a Package
his makes surepipinstalls the package for the same Python interpreter you are using. This
T
is helpful when multiple Python versions are installed.
xample:
E
requests==2.32.3
pandas==2.2.2
numpy==2.0.1
al
Why[Link]is Important
h
uppose you create a project and install many packages. Later, you share the project with
S
another person. Instead of telling them every package manually, you give them
hc
[Link]. They can install everything usingone command.
Create[Link]
or:
ith
r equests==2.32.3
urllib3==2.2.2
certifi==2024.7.4
od
or:
ust like English has grammar, Python also has grammar. If we do not follow Python syntax
J
rules, the program gives an error Python is beginner-friendly because its syntax is simple,
readable, and close to normal English.
al
Example:
h
hc
Output: Hello, World!
Output:Hello, World!
Part Meaning
eW
Diagram:
C
Another example:
Output:
elcome to Python
W
Python is easy to learn
Eachprint()statement displays output on a new lineby default.
h al
3.2 Python File Structure
hc
Python programs are usually saved with the.pyextension.
Example: [Link]
Inside[Link]:
is
N
ith
Python file can be very simple. It may contain only one line of code. But in larger
A
programs, we usually follow a clean structure.
eW
al
Important point:
ython does not force a fixed file structure for small programs. But writing code in a clean
P
h
order makes it easier to read and maintain.
hc
3.3 Comments
C
is
omments are notes written inside a program. Python ignores comments while running the
code Comments are useful for explaining what the code does.
N
Single-Line Comment
ith
eW
Inline Comment
C
Output: 20
Multi-Line Comments
ython does not have a special multi-line comment symbol. The recommended way is to use
P
#on each line.
al
Output: 30
h
Triple quotes can also be used for multi-line text, but technically they create a string.
hc
is
N
utput: Program started
O
ith
Indentation means spaces at the beginning of a line. Python uses indentation to define code
blocks. In many languages, curly braces{}are usedto define blocks. Python uses
indentation instead.
Example:
od
C
al
Please carry your ID
Program finished
h
Explanation:
hc
if age >= 18: This checks the condition.
print("You are eligible to vote")
print("Please carry your ID")
is
These two lines are indented,so they are inside theifblock.
N
print("Program finished") :This line is not indented,so it is outside theifblock.
Wrong Indentation
ith
eW
Correct code:
od
Example:
al
h
hc
Output:
is
N
ahul
R
21
5.8
ith
ariable Name
V Value
name ------> "Rahul"
eW
Example:
C
Output: 10
al
Python
In the first line,xstores an integer. Later,xstores a string. This is allowed because Python is
h
dynamically typed.
Multiple Variable Assignment
hc
is
utput:
O
N
10
20
ith
30
Same Value to Multiple Variables
eW
utput:
O
od
100
100
100
C
Can contain numbers student1 1student
al
Can contain underscore_ student_name student-name
h
Cannot contain spaces first_name first name
hc
Cannot use keywords course_name class
3.7 Keywords
eywords are reserved words in Python. They already have special meaning, so we cannot
K
use them as variable names. Some common Python keywords:
. if
1
al
2. else
3. for
4. while
h
5. class
hc
6. def
7. return
8. True
9. False is
10.None
11.import
N
12.try
13.except
14.with
ith
15.as
16.break
17.Continue
eW
Wrong example:
Correct example:
C
This prints the list of Python keywords. To check whether a word is a keyword:
Output: True
False
Basic Print
h al
Output: Hello Python
hc
Printing Numbers
is
utput:
O
N
100
25.75
ith
Printing Variables
eW
od
utput:
O
Sneha
22
C
Output:Name: Arjun
Age: 20
Printing Multiple Values
Output:A = 10 B = 20
Using f-strings
f-strings are a clean way to insert variables inside text.
h al
Output:My name is Priya and I am 19 years old.
hc
Another example
is
N
ith
Output:Hello Python
Another example:
h al
Output:
hc
A-B-C
Example:
eW
Important Point
Theinput()function always returns data as a string.
C
xample output:
E
Enter your age: 21
21
<class 'str'>
Even though the user entered21, Python stores itas"21".
Taking Integer Input
To convert input into an integer, useint().
xample output:
E
Enter your age: 21
Your age is: 21
al
<class 'int'>
Taking Float Input
h
To convert input into decimal number, usefloat().
hc
xample output:
E
is
N
Enter product price: 99.50
Price is: 99.5
ith
<class 'float'>
Example: Add Two Numbers
eW
od
xample output:
E
Enter first number: 10
Enter second number: 20
1020
ere, Python joins the two strings.It does not performmathematical addition because
H
both values are strings.
Correct version:
Output: 30
al
A basic Python program usually follows this flow:
h
tart
S
|
hc
v
Take input / define data
|
v is
Process data
|
v
N
Display output
|
ith
v
End
Simple structure:
eW
od
al
yntax errors happen when Python cannot understand the code because syntax rules are
S
broken.
h
hc
1. Missing Parentheses inprint()
Wrong:
PYTHON CODE
print "Hello"
is
N
rror:SyntaxError: Missing parentheses in call to'print'
E
Correct:
ith
PYTHON CODE
print("Hello")
eW
age = 20
print("Eligible")
Correct:
PYTHON CODE
age = 20
A colon:is required after statements like: if, else,elif, for, while, def, class, try, except, finally
3. Wrong Indentation
Wrong:
PYTHON CODE
if True:
print("Hello")
Correct:
PYTHON CODE
if True:
print("Hello")
h al
4. Using Keyword as Variable Name
hc
Wrong:
PYTHON CODE
for = 10
Correct:
is
N
PYTHON CODE
number = 10
ith
Wrong:
PYTHON CODE
rint(name)
p
od
name = "Aman"
PYTHON CODE
ame = "Aman"
n
print(name)
Python reads code from top to bottom. So the variable must be created before using it.
6. Missing Quotes Around String
Wrong:
PYTHON CODE
name = Aman
name = "Aman"
al
7. Mismatched Quotes
h
Wrong:
PYTHON CODE
hc
message = "Hello Python'
Correct:
PYTHON CODE
message = "Hello Python"
is
Also correct:
N
PYTHON CODE
message = 'Hello Python'
ith
Wrong:
PYTHON CODE
student-name = "Nishchal"
Correct:
od
PYTHON CODE
student_name = "Nishchal"
C
Correct:
PYTHON CODE
print("Hello Python")
11. Extra Closing Bracket
al
Wrong:
PYTHON CODE
h
print("Hello"))
hc
Correct:
PYTHON CODE
print("Hello")
is
3.12 Quick Revision Table
N
ith
Example:
h al
hc
Variable Value Data Type
Example:
h al
4.1.1int
hc
intmeansinteger. Integers are whole numbers. Theydo not have decimal points.
Examples: is
N
ith
eW
utput:
O
od
21
95
-5
0
C
Important point:
al
10 is int
10.0 is not int, it is float
h
hc
utput:
O
is
N
<class 'int'>
<class 'float'>
ith
4.1.2float
eW
utput:
O
99.5
5.8
-2.5
85.75
Checking type:
Examples offloat
h al
hc
is
N
ith
eW
Important point:
Example:
C
Output: 99.5
his does not mean the value is wrong. Python simply removes the unnecessary zero
T
at the end.
4.1.3complex
complexnumbers are numbers with two parts:
Real part + Imaginary part
In mathematics, complex numbers are usually written like this:
3 + 4i
But in Python, we usejinstead ofi.
al
Python complex number:
h
hc
utput:
O
is
N
(3+4j)
<class 'complex'>
ith
More examples:
C
utput:
O
(2+5j)
( 10+0j)
(-3+7j)
You can access real and imaginary parts like this
utput:
O
3.0
4.0
al
Important point:
Python uses j for complex numbers, not i.
h
Wrong:
hc
Correct:
is
N
4.2 Strings
ith
Examples:
od
h
Strings can be created using quotes.
hc
Using Double Quotes
is
N
Output: Aman
ith
utput:
O
od
Aman
Both are correct.
C
utput:
O
Python
Python
al
Using Triple Quotes
h
Triple quotes are used for multi-line strings.
hc
is
N
utput:
O
ith
Python is simple.
Python is powerful.
Python is beginner-friendly.
eW
Output:
Hello
Welcome to Python
Empty String
A string can also be empty.
Output:
<class 'str'>
There is no visible text in the first output because the string is empty.
al
4.2.2 String Indexing
h
hc
Indexing means accessing a single character from a string. Every character in a string has a
position number. This position number is called anindex.
Code:
od
C
utput:
O
P
y
t
h
o
n
Positive Indexing
Positive indexing starts from the left side.
Example:
utput:
O
P
h
n
h al
Negative Indexing
hc
Negative indexing starts from the right side.
is
N
Example:
ith
eW
od
utput:
O
n
o
C
P
Important:
Index Error
If you try to access an index that does not exist, Python gives an error.
Error:IndexError: string index out of range
Why?
h al
hc
4.2.3 String Slicing
Slicing means taking a part of a string. is
Syntax:string[start:end]
N
start index is included. end index is excluded
ith
Example:
PYTHON CODE
eW
word = "Python"
print(word[0:2])
od
Output:
Py
C
Explanation:
More examples:
Example:
PYTHON CODE
word = "Python"
print(word[0:4])
print(word[1:4])
print(word[2:6])
utput:
O
al
Pyth
yth
h
thon
hc
If start is empty, Python starts from the beginning.
is
N
Output:
ith
Pyt
Meaning:
Start from beginning
eW
Output: thon
C
Full Slice
Output: Python
This returns the full string.
al
Slicing with Step
h
Syntax:
hc
Example:
is
N
ith
utput:
O
eW
Pto
Explanation:
Start at index 0, Go before index 6, Pick every 2nd character
utput: nohtyP
O
Explanation:[::-1] means read the string from right to left
cannot be changed character by character.
h al
hc
Correct Way
You can create a new string and store it again.
PYTHON CODE
is
ame = "Ravi"
n
N
name = "Kavi"
print(name)
ith
utput:
O
Kavi
eW
Important understanding:
Old string:"Ravi"
New string:"Kavi"
Python does not modify the old string. It creates a new string.
od
Diagram:
C
o this is allowed:
S
name = "Ravi"
name = "Kavi"
But this is not allowed:
name[0] = "K"
Because changing one character inside the same string is not possible.
4.3 Boolean
Boolean is a data type that has only two possible values:
● True
● False
Boolean type is written as: bool
h al
utput:
O
True
hc
False
Checking type:
is
N
ith
Diagram:
eW
od
C
4.3.1True
Truerepresents yes, correct, active, available, or enabled.
Example:
Output:
True
True
al
True
Important:True must start with capital T.
h
Correct:is_active = True
Wrong:is_active = true
hc
Python will not understandtruebecause Python usesTrue.
4.3.2False
is
N
Falserepresents no, incorrect, inactive, unavailable, or disabled.
ith
eW
utput:
O
od
False
False
False
C
Value Meaning
al
0 A number
h
"" Empty string
hc
False Boolean false
Output:
eW
0
False
None
There is a blank line after0becausenameis an empty string.
od
Diagram:
C
Example:
Output:None
Later, the variable can store a real value:
Output:
None
al
Aman
Important:None must start with capital N.
h
Correct:
hc
Wrong:
is
N
ith
Syntax:
Example:
od
PYTHON CODE
ge = 21
a
print(type(age))
C
al
<class 'int'>
<class 'float'>
<class 'str'>
h
<class 'bool'>
hc
<class 'NoneType'>
<class 'complex'>
is
N
ith
Example:
PYTHON CODE
eW
= "100"
x
print(x)
print(type(x))
Output:
od
100
<class 'str'>
Even though it looks like a number, it is inside quotes, so it is a string.
C
Example:
PYTHON CODE
x = 100
print(x)
print(type(x))
Output: 100
<class 'int'>
Here,100is not inside quotes, so it is an integer.
4.6 Type Conversion
ype conversion means changing one data type into another.
T
Example:
String "100" ---> Integer 100
Integer 10 ---> Float 10.0
Number 50 ---> String "50"
Function Converts Into
al
int() Integer
h
float() Float
hc
str() String
bool() Boolean
utput:
O
100
<class 'int'>
Before conversion:x = "100" type is str
After conversion:y = 100 type is int
Invalidint()Conversion
This works:
PYTHON CODE
umber = int("50")
n
print(number)
al
Output:50
This does not work:
h
PYTHON CODE
umber =
n
hc
int("hello")
print(number)
E is
rror: ValueError: invalid literal for int()
Why?Because"hello"is not a valid number.
This also does not work:
N
PYTHON CODE
umber = int("10.5")
n
ith
print(number)
intoint.
Output:25.5
<class 'float'>
Integer to float:
Output:10.0
<class 'float'>
String integer to float:
h al
utput:
O
100.0
hc
<class 'float'>
Invalid conversion:
is
N
Error:ValueError: could not convert string to float
4.6.3 Converting tostr
ith
Output:21
<class 'str'>
C
Checking types:
PYTHON CODE
price = 99.5
converted_price = str(price)
print(type(price))
print(type(converted_price))
Output:
<class 'float'>
<class 'str'>
Important:
After converting to str, the value becomes text.
Example:
PYTHON CODE
x = 100
al
y = "100"
print(type(x))
h
print(type(y))
hc
Output:
<class 'int'>
<class 'str'>
is
Both look similar when printed, but their data types are different.
Example:
PYTHON CODE
x = 1
eW
y = 0
print(bool(x))
print(bool(y))
od
Output:True
False
Some simple conversions:
C
PYTHON CODE
print(bool(1))
print(bool(0))
print(bool("Python"))
print(bool(""))
Output:
True
False
True
False
We will study this more deeply inTruthy and FalsyValuesin the Control Flow section.
h al
hc
Output:
(10+0j)
<class 'complex'>
String to complex:
is
N
ith
eW
Output:
( 5+0j)
<class 'complex'>
od
C
● int
● float
● complex
● str
● bool
● NoneType
h al
Example with string:
hc
PYTHON CODE
ame = "Ravi"
n
is
N
name[0] = "K"
ith
PYTHON CODE
name = "Ravi"
name = "Kavi"
print(name)
od
Output: Kavi
Output: 21
al
Mutable Data Types
h
Mutable data types can be changed after creation. Some mutable data types in Python are:
hc
list
●
● dictionary
● set
is
These will be studied in detail later in theDataStructures[Link] now, only remember:
N
. Mutable objects can be modified.
1
2. Immutable objects cannot be modified directly.
ith
int Immutable
eW
float Immutable
complex Immutable
str Immutable
od
bool Immutable
NoneType Immutable
C
list Mutable
dict Mutable
set Mutable
4.8 Simple Memory Understanding
variable is like a name tag.
A
It points to a value.
Example: x = 10 Means x -----> 10
Now: x = 20 Means x -----> 20
The namexnow points to20. It does not mean10changed into20.
This idea is very useful for understanding mutable and immutable data later.
al
Topic Meaning
h
Data type Type/category of value
hc
int Whole numbers
tring
S Strings cannot be changed directly
immutability
od
bool StoresTrueorFalse
C
Simple meaning:
Example:
PYTHON CODE
al
a = 10
b = 5
h
print(a + b)
hc
Output:
15
Here,+is an operator. It addsaandb.
Diagram: is
N
ith
eW
Operators
│
├── Arithmetic operators
od
.
1 ddition
A
2. Subtraction
3. Multiplication
4. Division
5. Power
6. Remainder
al
Arithmetic operators work mostly with numbers.
h
hc
Operator Name Example
-
*
Subtraction
Multiplication
10 - 5
10 * 5
is
N
/ Division 10 / 5
ith
Addition+
od
PYTHON CODE
C
= 10
a
b = 5
result = a + b
print(result)
Output: 15
Subtraction-
The-operator subtracts one number from another.
PYTHON CODE
= 10
a
b = 5
result = a - b
print(result)
al
Output: 5
h
Multiplication*
hc
The*operator multiplies two numbers.
PYTHON CODE
= 10
a
is
N
b = 5
result = a * b
print(result)
ith
Output: 50
eW
Division/
The/operator divides one number by another. Divisionusing / always gives a float result.
od
PYTHON CODE
= 10
a
b = 5
C
result = a / b
print(result)
print(type(result))
utput:
O
2.0
<class 'float'>
Even though10 / 5is mathematically2, Python gives2.0.
That means the result is a float.
Floor Division//
he//operator divides and gives the whole-numberpart.
T
Example:
PYTHON CODE
= 10
a
b = 3
result = a // b
print(result)
h al
utput: 3
O
Explanation: 10 / 3 = 3.333...
hc
Floor division gives 3
Important point:
/ gives normal division
// gives floor division
is
Example:
N
PYTHON CODE
ith
rint(10 / 3)
p
print(10 // 3)
eW
utput:
O
3.3333333333333335
3
Modulus%
od
= 10
a
b = 3
result = a % b
print(result)
utput:1
O
Explanation:
10 divided by 3 => 3 goes into 10 three times: 3 × 3 = 9 Remainder: 10 - 9 = 1
Exponent / Power**
The**operator is used to calculate power.
PYTHON CODE
r esult = 2 ** 3
print(result)
utput:8
O
Explanation: 2 ** 3 means 2 raised to the power 3
Example :
PYTHON CODE
al
= 20
a
b = 6
print(a + b)
h
print(a - b)
hc
print(a * b)
print(a / b)
print(a // b)
print(a % b) is
print(a ** 2)
N
utput:
O
26
ith
14
120
3.3333333333333335
eW
3
2
400
od
al
>= Greater than or equal to 10 >= 10
h
hc
Equal To==
is
The==operator checks whether two values are equal.
N
PYTHON CODE
print(10 == 10)
ith
print(10 == 5)
Output:
True
eW
False
PYTHON CODE
print(10 != 5)
print(10 != 10)
C
Output:
True
False
Explanation:
10 != 5 True because 10 is not equal to 5
10 != 10 False because 10 is equal to 10
Greater Than>
The>operator checks whether the left value is greater than the right value.
PYTHON CODE
Output:
True
False
al
Less Than<
The<operator checks whether the left value is less than the right value.
h
PYTHON CODE
hc
print(5 < 10)
print(10 < 5)
Output:
is
True
N
False
ith
PYTHON CODE
Output:
True
C
True
False
Explanation:
10 >= 5 True because 10 is greater than 5
10 >= 10 True because 10 is equal to 10
5 >= 10 False
Less Than or Equal To<=
The<=operator checks whether the left value is less than or equal to the right value.
PYTHON CODE
Output:
True
al
True
False
Explanation:
h
5 <= 10 True because 5 is less than 10
hc
10 <= 10 True because 10 is equal to 10
20 <= 10 False
a = 15
ith
b = 20
print(a == b)
print(a != b)
eW
Output:
C
False
True
False
True
False
True
5.3 Logical Operators
Logical operators are used to combine Boolean values.
Python has three logical operators:
● and
● or
● not
These operators work withTrueandFalse.
al
Operator Meaning
h
or True when at least one side is True
hc
not Reverses True/False
andOperator is
Theandoperator givesTrueonly when both valuesareTrue.
N
PYTHON CODE
Output:
True
False
od
False
False
Truth table:
C
PYTHON CODE
age_valid = True
id_available = True
print(age_valid and id_available)
Output:
True
al
orOperator
Theoroperator givesTruewhen at least one value isTrue.
h
PYTHON CODE
print(True or True)
hc
print(True or False)
print(False or True)
print(False or False) is
Output:
N
True
True
ith
True
False
Truth table:
eW
PYTHON CODE
has_email = True
has_phone = False
print(has_email or has_phone)
Output: True
notOperator
Thenotoperator reverses a Boolean value.
PYTHON CODE
print(not True)
print(not False)
Output:
False
True
al
Simple meaning:
not True becomes False
h
not False becomes True
hc
Example:
PYTHON CODE
is_logged_in = True
print(not is_logged_in)
is
N
Output: False
ith
Example:
PYTHON CODE
age = 20
od
marks = 85
print(age > 18 and marks > 80)
Output:
C
True
Explanation: age > 18 True
marks > 80 True
True and True = True
5.4 Assignment Operators
Assignment operators are used to assign values to variables.
The most basic assignment operator is: =
Example:
PYTHON CODE
x = 10
print(x)
Output: 10
al
Here,10is assigned tox.
h
List of Assignment Operators
hc
Operator Example Same As
+= x += 5 x = x + 5
N
-= x -= 5 x = x - 5
ith
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
eW
//= x //= 5 x = x // 5
%= x %= 5 x = x % 5
**= x **= 5 x = x ** 5
od
Basic Assignment=
C
PYTHON CODE
x = 10
print(x)
Output: 10
Add and Assign+=
PYTHON CODE
x = 10
x += 5
print(x)
Output: 15
Explanation:
al
x += 5
Same as:
h
x = x + 5
hc
Subtract and Assign-=
PYTHON CODE
x = 10
is
N
x -= 3
print(x)
ith
Output: 7
Explanation: x -= 3
eW
Same as: x = x - 3
PYTHON CODE
x = 10
x *= 2
print(x)
C
Output:20
Explanation: x *= 2
Same as: x = x * 2
Divide and Assign/=
PYTHON CODE
x = 10
x /= 2
print(x)
Output: 5.0
Important: /= gives float result because / gives float result.
al
Floor Divide and Assign//=
h
PYTHON CODE
x = 10
hc
x //= 3
print(x)
Output: 3 is
Explanation:x //= 3
Same as:x = x // 3
N
ith
x %= 3
print(x)
Output: 1
od
Explanation: x %= 3
Same as: x = x % 3
PYTHON CODE
x = 2
x **= 3
print(x)
Output:8
Explanation: x **= 3
Same as: x = x ** 3
5.5 Membership Operators
Membership operators are used to check whether a value exists inside another value.
Python has two membership operators:
. in
1
2. not in
or now, we will use membership operators with strings because strings are already
F
covered.
inOperator
al
Theinoperator checks whether something is present.
Example:
h
PYTHON CODE
text = "Python"
hc
print("P" in text)
print("Py" in text)
print("Java" in text) is
Output:
N
True
True
ith
False
Explanation:
"P" exists in "Python" True
eW
not inOperator
Thenot inoperator checks whether something is not present.
od
Example:
PYTHON CODE
C
ext = "Python"
print("Java" not in text)
print("Py" not in text)
Output:
True
False
Membership Is Case-Sensitive
Python checks uppercase and lowercase carefully.
Example:
PYTHON CODE
text = "Python"
print("P" in text)
print("p" in text)
al
Output:
True
False
h
Explanation:
hc
"P" and "p" are different in Python.
. is
1
2. is not
Important:
eW
isOperator
od
PYTHON CODE
a = None
b = None
print(a is b)
Output:True
Explanation:
a refers to None
b refers to None
Both refer to the same None object.
is notOperator
Theis notoperator checks whether two variables donot point to the same object.
Example:
PYTHON CODE
a = None
b = 10
print(a is not b)
Output:
al
True
Explanation:
a refers to None
h
b refers to 10
hc
They are not the same object.
Difference Between==andis is
== checks whether values are equal.
N
is checks whether both variables refer to the same object.
PYTHON CODE
ith
a = 100
b = 100
print(a == b)
eW
print(a is b)
Possible output:
True
True
od
For some simple values, Python may reuse the same object internally.
ut beginners should remember this rule: Use == for value comparison. Use is mainly with
B
C
None.
Best example:
PYTHON CODE
result = None
print(result is None)
print(result is not None)
Output: True
False
5.7 Bitwise Operators
Bitwise operators work on binary numbers.
Binary means numbers written using only:
0 and 1
Computers store numbers internally in binary form.
Example:
Decimal 5 = Binary 101
Decimal 3 = Binary 011
Bitwise operators compare or shift bits.
al
List of Bitwise Operators
h
Operator Name
hc
& Bitwise AND
` ` is
^ Bitwise XOR
N
~ Bitwise NOT
ith
Bitwise AND&
Bitwise AND compares bits.
Rule:
od
C
Example:
PYTHON CODE
a = 5
b = 3
print(a & b)
Output: 1
So: 5 & 3 = 1
al
Bitwise OR|
Bitwise OR compares bits.
h
hc
is
N
Example:
ith
eW
Output: 7
Explanation:
od
C
Bitwise XOR^
Bitwise XOR gives1when bits are different.
Rule:
Example:
al
PYTHON CODE
= 5
a
b = 3
h
print(a ^ b)
hc
Output: 6
Explanation:
is
N
ith
Bitwise NOT~
eW
Example: x = 5
PYTHON CODE
C
print(~x)
Output: -6
Explanation:
~5 = -(5 + 1)
~5 = -6
For beginners, remember:
Bitwise NOT does not simply make 5 into -5.
It gives -(number + 1).
Left Shift<<
Left shift moves bits to the left.
Simple meaning:
x << n means x multiplied by 2 power n
Example:
PYTHON CODE
x = 5
print(x << 1)
al
Output:10
Explanation:
h
5 << 1
hc
5 × 2 = 10
Binary view:
5 in binary = 101
After left shift by 1:
1010
is
N
1010 in decimal = 10
ith
Right Shift>>
Right shift moves bits to the right.
eW
Simple meaning:
x >> n means x divided by 2 power n and gives whole-number result
Example:
PYTHON CODE
od
x = 10
print(x >> 1)
C
Output: 5
Explanation:
10 >> 1
10 // 2 = 5
Binary view: 10 in binary = 1010
After right shift by 1:
101
101 in decimal = 5
5.8 Operator Precedence
Operator precedence means the order in which Python solves operators.
Example:
PYTHON CODE
result = 10 + 5 * 2
print(result)
Output:20
A beginner may think:
al
10 + 5 = 15
15 * 2 = 30
h
But Python does multiplication first.
Correct solving:
hc
10 + 5 * 2
10 + 10
20
So the result is20.
is
N
Why Operator Precedence Matters
ith
andHappens Beforeor
C
PYTHON CODE
result = True or False and False
print(result)
Output:True
Using parentheses:
result = (True or False) and False
print(result)
Output:False
Common Operator Precedence Table
Higher operators are solved first.
Priority Operators Meaning
al
6 <<,>> Bitwise shifts
7 & Bitwise AND
h
8 ^ Bitwise XOR
hc
9 ` `
10 ==,!=,>,<,>=,<= Comparisons
11 not Logical NOT
12
13
and
or
is Logical AND
Logical OR
N
Parentheses()Have Highest Priority
ith
PYTHON CODE
result = (10 + 5) * 2
eW
print(result)
Output: 30
Explanation: (10 + 5) * 2 = 15 * 2 = 30
od
Without parentheses:
PYTHON CODE
result = 10 + 5 * 2
C
print(result)
Output: 20
Output: 18
Chapter 6. String Operations
Astringis a sequence of characters enclosed in quotes.
name = "Python"
trings are one of the most used data types in Python because text handling is needed in
S
almost every program.
al
PYTHON CODE
s1 = "Hello"
h
s2 = 'Hello'
s3 = """Hello Python"""
hc
All three are valid.
S
used for multi-line strings.
is
ingle quotes and double quotes are commonly used for one-line strings. Triple quotes are
N
PYTHON CODE
Python is powerful.
Python is widely used."""
eW
Example:
C
PYTHON CODE
word = "Python"
print(word[0])
print(word[3])
Output:
P
h
For negative indexing, counting starts from the end.
Example:
PYTHON CODE
print(word[-1])
print(word[-2])
Output:n
o
Index diagram:
h al
6.3 String Slicing
hc
Slicing means taking a part of a string.
Syntax:
is
N
Important rule: thestart index is included, and theend index is excluded.
Example:
ith
PYTHON CODE
word = "Python"
print(word[0:3])
eW
print(word[2:])
print(word[:4])
Output:
Pyt
od
thon
Pyth
You can also use step values:
C
PYTHON CODE
print(word[0:6:2])
Output:Pto
To reverse a string:
PYTHON CODE
print(word[::-1])
Output:
nohtyP
6.4 String Methods
String methods are built-in functions that work on strings.
ommon string methods are used for cleaning, checking, changing case, finding text, and
C
replacing text.
lower()
Converts string to lowercase.
PYTHON CODE
text = "Python"
print([Link]())
al
Output:
python
h
hc
upper()
Converts string to uppercase.
PYTHON CODE
text = "Python"
is
N
print([Link]())
Output:
ith
PYTHON
eW
strip()
Removes extra spaces from the beginning and end.
PYTHON CODE
print([Link]())
Output:
C
Python
replace()
Replaces one part of a string with another.
PYTHON CODE
Output:
I like Python
split()
Splits a string into a list of parts using a separator.
PYTHON CODE
text = "apple,banana,mango"
print([Link](","))
Output:
['apple', 'banana', 'mango']
al
find()
h
Finds the position of a substring.
hc
PYTHON CODE
text = "Python"
print([Link]("th"))
Output:
is
2
N
If the text is not found, it returns-1.
ith
count()
Counts how many times a character or substring appears.
eW
PYTHON CODE
text = "banana"
print([Link]("a"))
od
Output: 3
startswith()andendswith()
C
PYTHON CODE
text = "Python"
print([Link]("Py"))
print([Link]("on"))
Output:
True
True
These methods are very useful in text checking and validation.
6.5 String Formatting
String formatting means placing values inside a string in a clean way.
This is better than manually joining many values.
Python has three main ways to format strings:
● f-strings
● format()
● old%formatting
6.5.1 f-strings
al
f-strings are the most readable and modern way.
Writefbefore the string and place variables inside{}.
h
PYTHON CODE
hc
name = "Aman"
age = 20
is
print(f"My name is {name} and I am {age} years old.")
Output:
N
My name is Aman and I am 20 years old.
You can also place expressions inside f-strings.
ith
PYTHON CODE
a = 10
eW
b = 5
print(f"Sum is {a + b}")
Output:
Sum is 15
od
6.5.2format()
Theformat()method inserts values into placeholders.
C
PYTHON CODE
name = "Aman"
age = 20
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Aman and I am 20 years old.
You can also use position numbers:
print("My name is {0} and I am {1} years old.".format(name, age))
This is useful when you want control over the order of values.
6.5.3 Old%Formatting
This is the older style of formatting.
PYTHON CODE
name = "Aman"
age = 20
print("My name is %s and I am %d years old." % (name, age))
● %sis used for string
al
● %dis used for integer
This style is still found in older code, but f-strings are preferred in modern Python.
h
hc
6.6 String Concatenation
Concatenation means joining strings together.
The+operator is used for this. is
PYTHON CODE
N
first = "Python"
second = "Programming"
ith
Output:
eW
Python Programming
Important point:only strings can be joined directly.
\\ Backslash
\' Prints a Single Quote print('It\'s Python') It's Python
al
\" Prints a Double Quote print("He said \"Hello\"") He said "Hello"
h
\b ackspace (removes
B print("ABC\bD") ABD
hc
previous character)
\f
beginning of line)
Form Feed
is
print("Hello\fPython") Inserts a form-feed
N
character
ith
PYTHON CODE
path = r"C:\new_folder\test"
print(path)
C
Output: C:\new_folder\test
PYTHON CODE
text = "Hi"
print(text * 3)
Output: HiHiHi
Common String Methods
Method Description Example Result
swapcase() onverts uppercase to lowercase and "PyThOn".swapcase()
C "pYtHoN"
al
lowercase to uppercase
strip() Removes spaces from both ends " Python ".strip() "Python"
h
lstrip() Removes spaces from the left side " Python".lstrip() "Python"
hc
rstrip() Removes spaces from the right side "Python ".rstrip() "Python"
r eplace(old, Replaces one substring with another " I like "I like Python"
new) Java".replace("Java","Python")
find()
is
Returns the first index of a substring "Python".find("th") 2
N
index() eturns the index of a substring
R "Python".index("th") 2
(raises error if not found)
count() Counts occurrences of a substring "banana".count("a") 3
ith
substring
split() Splits a string into a list "a,b,c".split(",") ['a', 'b', 'c']
join() Joins iterable elements into a string "-".join(["A","B","C"]) "A-B-C"
isalpha() eturnsTrueif all characters are
R "Python".isalpha() True
od
alphabets
isdigit() eturnsTrueif all characters are
R "12345".isdigit() True
digits
isalnum() eturnsTrueif all characters are
R "Python3".isalnum() True
C
letters or digits
center(width) C
enters the string within the specified "Python".center(12) " Python "
width
7.1ifStatement
Syntax
h al
heifstatement is used when we want to run somecode only when a condition isTrue.
T
If the condition isTrue, Python executes the indented block.
hc
If the condition isFalse, Python skips the indentedblock.
Flow Chart is
N
ith
eW
Example
PYTHON CODE
od
ge = 20
a
if age >= 18:
print("Eligible to vote")
C
Output:Eligible to vote
example:
PYTHON CODE
arks = 35
m
if marks >= 40:
print("Passed")
print("Program finished")
Output:Program finished
7.2if-elseStatement
Syntax
al
Explanation
h
heif-elsestatement is used when we want to runone block if the condition is Trueand
T
hc
another block if the condition is False.
Only one block runs.
If the condition isTrue, theifblock runs.is
If the condition isFalse, theelseblock runs.
N
Flow Chart
ith
eW
od
C
Example
PYTHON CODE
ge = 16
a
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
h al
hc
is
N
Explanation
ith
elifmeanselse if.
It is used when we need to checkmultiple conditions.Python checks conditions from top
eW
to bottom. The first condition that becomesTruegetsexecuted. After that, Python skips the
remaining conditions.
Theelseblock runs only when all previous conditionsareFalse.
Example
od
PYTHON CODE
arks = 75
m
if marks >= 90:
print("Grade A")
C
Output:Grade B
7.4 Nested Conditions
Syntax
Withelse:
h al
hc
N
is
ested condition means writing one condition inside another condition. The inner condition is
checked only when the outer condition isTrue. Thisis useful when one decision depends on
N
another decision.
Flow Chart
ith
eW
od
Example
C
Common usage:
al
he ternary operator is a short way to write a simpleif-elsestatement in one line. It is useful
T
when we need to choose between two values. Use it only for simple conditions. For complex
h
logic, normalif-elseis better.
hc
Flow Chart
is
N
ith
eW
Normalif-else:
PYTHON CODE
ge = 20
a
od
print(status)
utput:Adult
O
Same code using ternary operator:
PYTHON CODE
ge = 20
a
status = "Adult" if age >= 18 else "Minor"
print(status)
Output: Adult
7.6match-case
Syntax
h al
hc
Explanation
atch-caseis used to compare one value with multiplepossible cases. It is similar to
m
checking many fixed options.
is
he_case works like a default case. It runs whenno other case matches.match-casewas
T
N
introduced in Python 3.10.
ith
Flow Chart
eW
od
C
Example
al
Output:Starting program
PYTHON CODE
h
ay = 3
d
hc
match day:
case 1:
print("Monday")
case 2: is
print("Tuesday")
case 3:
N
print("Wednesday")
case _:
ith
print("Invalid day")
Output: Wednesday
eW
Explanation
In Python, conditions do not always need direct comparison like: if age >= 18:
Python can also treat values asTrueorFalse. Theseare calledtruthyandfalsyvalues.
Atruthy valuebehaves likeTrue.A falsy value behaveslikeFalse.
Common falsy values:
Value Meaning
al
None No value
h
Common truthy values:
hc
Value Meaning
Flow Chart
od
C
Example 1: Non-empty string
PYTHON CODE
ame = "Rahul"
n
if name:
print("Name is available")
else:
print("Name is missing")
Output:
Name is available
Example 2: Empty string
al
PYTHON CODE
ame = ""
n
h
if name:
hc
print("Name is available")
else:
print("Name is missing")
Output:Name is missing
is
N
Example 3: Number
ith
PYTHON CODE
mount = 0
a
if amount:
eW
print("Amount available")
else:
print("Amount is zero")
od
ithout a loop, we write manyprint()statements.With loop, we write the logic once and
W
Python repeats it.
8.1forLoop
al
Syntax
h
hc
Explanation
.
1 forloop is used to repeat code over a sequence.
A
2.
3.
is
A sequence can be a string, range, list, tuple, etc.
In each round, Python takes one value from the sequence.
N
4. The loop stops automatically when all values are finished.
Flow Chart
ith
eW
od
utput:
O
P
y
t
h
o
n
Example 2: Loop withrange()
utput:
O
1
2
3
4
5
8.2 while Loop
al
Syntax
h
Explanation
hc
.
1
is
whileloop runs as long as the condition isTrue.
A
N
2. Before every round, Python checks the condition.
3. If the condition isTrue, the loop block runs.
ith
Flow Chart
eW
od
C
Example 1:Print numbers from 1 to 5
PYTHON CODE
number = 1
utput:
O
1
2
3
al
4
5
h
forLoop vswhileLoop
hc
Point forLoop whileLoop
Main use Used to loop over a sequence is Used to repeat while a condition isTrue
becomesFalse
When to Useforandwhile
Explanation
. b
1 reakis used to stop a loop immediately.
2. When Python seesbreak, it exits the loop.
3. Code after the loop continues normally.
al
Flow Chart:
h
hc
is
N
ith
Output:
1
2
C
3
Explanation:
1. The loop starts from1.
2. Whennumberbecomes4,breakruns.
3. The loop stops before printing4.
8.4continue
Syntax
Explanation
1. continueskips the current round of the loop.
2. It does not stop the full loop.
al
3. Aftercontinue, Python moves to the next round.
Flow Chart
h
hc
is
N
ith
PYTHON CODE
for number in range(1, 6):
eW
Output:
1
2
C
4
5
Explanation:
1. When number is 3, continue runs.
2. print(number) is skipped for 3.
3. The loop continues with 4 and 5.
8.5pass
Syntax
1. p
assmeans “do nothing”. It is used when Python needsa statement, but we do not
want to write logic yet. It does not stop or skip the loop likebreakorcontinue.
Flow Chart
h al
Example 1: Empty loop block
hc
PYTHON CODE
is
N
for number in range(1, 4):
pass
ith
PYTHON CODE
for number in range(1, 4):
if number == 2:
pass
od
print(number)
utput:
O
1
C
2
3
break Stop the loop Exits the loop completely Stop when required value is found
continue Skip current round Moves to next iteration Skip unwanted values
Explanation
al
. A
1 loop can have anelseblock. Theelseblock runswhen the loop finishes normally.
2. If the loop stops because ofbreak, theelseblockdoes not run.
h
Flow Chart
hc
is
N
Example 1: Loop finishes normally
ith
eW
utput:
O
1
2
3
od
Loop finished
Example 2: Loop stops withbreak
PYTHON CODE
C
utput:
O
1
2
8.7 Nested Loops
Syntax
Explanation
al
.
1 ested loop means one loop inside another loop.
N
2. The outer loop runs first.
3. For every one round of the outer loop, the inner loop runs completely.
h
4. Nested loops are useful for patterns, tables, rows and columns.
hc
Flow Chart
is
N
ith
eW
PYTHON CODE
for row in range(1, 3):
for column in range(1, 4):
C
print(row, column)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
Example 2: Simple pattern
PYTHON CODE
Output:
*
**
***
h al
8.8range()
hc
Syntax
is
N
Explanation
ith
.
1 r ange()creates a sequence of numbers.
2. It is commonly used withforloops.
eW
Flow Chart
od
C
Example 1:range(stop)
PYTHON CODE
for number in range(5):
print(number)
Output:
0
1
2
3
4
Explanation:
1. range(5)starts from0.
2. It stops before5.
al
Example 2:range(start, stop)
h
PYTHON CODE
for number in range(1, 6):
hc
print(number)
utput:
O
1 is
2
3
N
4
5
ith
print(number)
utput:
O
2
4
od
6
8
10
C
range()Forms
Syntax Meaning Example Output Values
range(start, stop, step) Uses step/gap between values range(2, 10, 2) 2, 4, 6, 8
Positive and Negative Step inrange()
Example Meaning Output Values
range(10, 0, -2) Decrease by2 10, 8, 6, 4, 2
h al
8.9enumerate()
hc
Syntax
is
N
ith
Explanation
1. enumerate()gives both index and value while looping.
eW
Flow Chart
od
C
Example 1: Enumerate a string
PYTHON CODE
word = "Python"
for index, letter in enumerate(word):
print(index, letter)
Output:
0 P
1 y
al
2 t
3 h
h
4 o
5 n
hc
Example 2: Start index from 1
PYTHON CODE
word = "Python"
is
N
for index, letter in enumerate(word,
ith
start=1):
print(index, letter)
eW
Output:
1 P
2 y
3 t
od
4 h
5 o
6 n
C
Explanation
1. zip()is used to loop over two or more sequences together.
2. It takes one item from each sequence at the same time.
al
3. The loop stops when the shortest sequence ends.
Flow Chart
h
hc
is
N
ith
PYTHON CODE
letters = "ABC"
numbers = "123"
od
Output:
A 1
B 2
C 3
Example 2: Different length sequences
PYTHON CODE
letters = "ABCD"
numbers = "12"
for letter, number in zip(letters,
numbers):
print(letter, number)
Output:
A 1
al
B 2
Explanation:
h
1. lettershas 4 characters.
hc
2. numbershas 2 characters.
3. zip()stops after the shorter sequence ends.
Explanation
.
1 n iterator is an object that gives values one by one.
A
2. iter()creates an iterator from an iterable value.
3. next()gets the next value from the iterator.
od
4. Loops internally use this idea to get values one by one.
Term Meaning
C
al
h
hc
Example 1: Usingiter()andnext()
is
N
ith
eW
utput:
O
A
B
C
od
PYTHON CODE
Output:
A
B
C
Internally, the idea is similar to:
PYTHON CODE
iterator = iter("ABC")
print(next(iterator))
print(next(iterator))
print(next(iterator))
utput:
O
A
B
al
C
Iterable vs Iterator
h
Term Meaning Example
hc
Iterable Something we can loop over String,range()
iter("ABC")
N
next() Gets next value next(iterator)
ith
Example 1: Iterable
eW
Output: A
B
od
C
Here,"ABC"is iterable because we can loop over it.
Example 2: Iterator
C
Output:A
B
C
8.12StopIteration
When an iterator has no more values, Python raisesStopIteration.
al
Output:
h
A
hc
B
StopIteration
Infinite Loop is
n infinite loop is a loop that never stops. This usually happens when the condition in awhile
A
N
loop never becomesFalse.
Problem:
od
utput:
O
1
2
3
4
5
Chapter 9. Data Structure in Python
Syntax
al
Explanation
h
hc
.
1 ists are written using square brackets[].
L
2. List items are separated by commas.
3. Lists are ordered, so every item has an index.
4. Lists are mutable, meaning we can change them after creation.
is
5. Lists can store duplicate values.
6. Lists can store different data types together.
N
Example 1
ith
eW
Allows duplicates Same value can appear multiple times [10, 10, 20]
Mixed data allowed Can store different data types ["Aman", 20, True]
h al
9.1.1 Creating Lists
hc
Syntax
is
N
. A
1 list can store numbers, strings, Boolean values, or mixed values.
ith
Example 1
eW
od
C
utput:
O
[10, 20, 30, 40]
['Aman', 'Riya', 'Kabir']
['Python', 100, 99.5, True]
[]
Different Ways to Create Lists
Type Example
Nested list matrix = [[1, 2], [3, 4]]
al
Usinglist() letters = list("ABC")
h
hc
9.1.2 Accessing Values
Syntax is
N
ith
Explanation
eW
.
1 ist items are accessed using index numbers.
L
2. Python indexing starts from0.
3. Positive indexing starts from the left.
4. Negative indexing starts from the right.
od
C
Example 1
utput:
O
Aman
Kabir
Neha
Indexing Table
Code Meaning Result
9.1.3 Updating Values
al
Syntax
h
hc
1. Lists are mutable.
2. We can change an existing item using its index.
is
3. The index must exist in the list.
Example 1
N
ith
eW
clear() Removes all items [Link]() Empty list
al
index() Returns index of value [Link](30) Gives position
count() Counts occurrences [Link](10) Count of10
h
sort() Sorts list [Link]() Ascending order
hc
reverse() Reverses list [Link]() Reverse order
copy() Creates shallow copy new = [Link]() New list copy
Example 1
is
N
PYTHON CODE
numbers = [10, 20, 30]
ith
[Link](40)
[Link](1, 15)
eW
[Link](20)
print(numbers)
od
Explanation
1. Slicing is used to get a part of a list.
2. The start index is included.
3. The end index is excluded.
4. Step controls the gap between selected items.
al
Example 1
h
PYTHON CODE
hc
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[::2])
is
N
print(numbers[::-1])
utput:
O
ith
Slicing Table
od
With condition:
.
1 ist comprehension is a short way to create a new list.
L
al
2. It is commonly used when each item needs to be processed.
3. It can also filter values usingif.
h
4. It makes code shorter and cleaner.
hc
Example 1
PYTHON CODE
numbers = [1, 2, 3, 4, 5]
quares = [number * number for
s
is
number in numbers]
N
print(squares)
ith
PYTHON CODE
numbers = [1, 2, 3, 4, 5, 6]
Output:[2, 4, 6]
Syntax
list_name = [[item1, item2], [item3, item4]]
Explanation
. A
1 nested list means a list inside another list.
2. It is useful for matrix-like data, rows and columns, or grouped values.
3. To access nested list values, use multiple indexes.
Example 1
PYTHON CODE
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0])
print(matrix[1][2])
al
Output:[1, 2, 3]
6
h
Index Diagram
hc
is
N
ith
PYTHON CODE
matrix = [
[1, 2, 3],
od
[4, 5, 6]
]
C
atrix[1][0] = 40
m
print(matrix)
Sort ascending [Link]() Yes Small to large
al
Sort descending [Link](reverse=True) Yes Large to small
h
Sorted copy sorted(numbers) No Returns new sorted list
hc
Reverse original [Link]() Yes Reverses same list
Example 1
N
PYTHON CODE
ith
print(numbers)
[Link](reverse=True)
print(numbers)
od
[Link]()
print(numbers)
C
utput:
O
[10, 20, 30, 40]
[40, 30, 20, 10]
[10, 20, 30, 40]
sort()vssorted()
Point sort() sorted()
Original list Changes original list Does not change original list
al
Example 2
h
PYTHON CODE
hc
numbers = [30, 10, 20]
ew_numbers =
n
sorted(numbers)
print(numbers)
print(new_numbers)
is
N
utput:
O
[30, 10, 20]
ith
Syntax
new_list = old_list.copy()
od
Other ways:
new_list = old_list[:]
C
new_list = list(old_list)
Explanation
.
1 opying means creating another list with the same values.
C
2. Direct assignment does not create a real copy.
3. Direct assignment makes two variables point to the same list.
4. To create a separate list, usecopy(), slicing, orlist().
Direct Assignment
PYTHON CODE
[Link](40)
print(list1)
print(list2)
al
Output:
[10, 20, 30, 40]
h
[10, 20, 30, 40]
hc
Explanation:
Output:
al
9.1.10 Shallow Copy vs Deep Copy
h
hc
Explanation
This concept matters when a list contains another list. There are two types of copy:
S
● hallow copy
● Deep copy
is
N
Shallow Copy
ith
A shallow copy creates a new outer list, but nested lists inside are still shared.
eW
list2 = [Link]()
list2[0][0] = 99
print(list1)
C
print(list2)
Output:
[[99, 20], [30, 40]]
[[99, 20], [30, 40]]
Deep Copy
al
A deep copy creates a completely separate copy of both the outer list and inner lists.
h
Example 2: Deep Copy
hc
PYTHON CODE
import copy
list1 = [[10, 20], [30, 40]]
list2 = [Link](list1)
is
N
list2[0][0] = 99
ith
print(list1)
print(list2)
eW
al
Insert item [Link](1, 15) Adds at index
h
Remove by index [Link](0) Removes by index
hc
Slice list items[1:3] Gets part of list
Syntax
tuple_name = (value1, value2, value3)
al
Explanation
h
.
1 uples are written using parentheses().
T
2. Tuple items are separated by commas.
hc
3. Tuples are ordered, so items have index positions.
4. Tuples are immutable, so items cannot be changed after creation.
5. Tuples allow duplicate values.
6. is
Tuples can store different data types.
Example 1
N
ith
eW
Allows duplicates Same value can appear more than once (10, 10, 20)
Mixed data allowed Can store different data types ("Aman", 20, True)
al
9.2.1 Creating Tuples
h
Syntax
hc
tuple_name = (item1, item2, item3)
1. T uples can store numbers, strings, Booleans, or mixed values. An empty tuple can
is
also be created.
2. A tuple can be created with or without parentheses, but parentheses are
N
recommended for clarity.
3. A single-item tuple must have a comma.
ith
Example 1
eW
PYTHON CODE
numbers = (10, 20, 30)
names = ("Aman", "Riya", "Kabir")
mixed = ("Python", 100, 99.5, True)
empty_tuple = ()
od
print(numbers)
print(names)
print(mixed)
C
print(empty_tuple)
Output:
Nested tuple matrix = ((1, 2), (3, 4))
al
Without parentheses items = 10, 20, 30
h
Usingtuple() letters = tuple("ABC")
hc
9.2.2 Single-Item Tuple is
Syntax
N
tuple_name = (value,)
ith
Explanation
eW
. A
1 single-item tuple must contain a comma.
2. Without the comma, Python does not treat it as a tuple.
3. Parentheses alone are not enough.
Example 1
od
PYTHON CODE
C
a = ("Python")
b = ("Python",)
print(type(a))
print(type(b))
utput:
O
<class 'str'>
<class 'tuple'>
9.2.3 Accessing Tuple Values
Syntax
tuple_name[index]
.
1 uple values are accessed using index numbers.
T
2. Python indexing starts from0.
3. Positive indexing starts from the left.
4. Negative indexing starts from the right.
al
Index Diagram
h
hc
Example 1 is
N
PYTHON CODE
students = ("Aman", "Riya", "Kabir", "Neha")
print(students[0])
ith
print(students[2])
print(students[-1])
eW
utput:
O
Aman
Kabir
Neha
od
tuple_name[start:end:step]
Explanation
.
1 licing is used to get a part of a tuple.
S
2. The start index is included.
3. The end index is excluded.
4. Step controls the gap between selected values.
5. Slicing returns a new tuple.
Example 1
Output:
al
( 20, 30, 40)
(10, 20, 30)
h
(40, 50, 60)
(10, 30, 50)
hc
(60, 50, 40, 30, 20, 10)
Slicing Table is
Code Meaning Result
N
numbers[1:4] Index1to before4 (20, 30, 40)
ith
tuple_name[index] = new_value
This syntax isnot allowedfor tuples.
Explanation
.
1 uples are immutable.
T
2. Once a tuple is created, its values cannot be changed directly.
3. We cannot update, add, or remove tuple items directly.
4. If changes are needed, use a list or create a new tuple.
Example 1
PYTHON CODE
Correct Way
Create a new tuple:
al
PYTHON CODE
h
numbers = (10, 25, 30)
print(numbers)
hc
Output:(10, 25, 30)
Memory Idea is
efore:numbers ----> (10, 20, 30)
B
After:numbers ----> (10, 25, 30)
N
The old tuple is not changed. The variable starts pointing to a new tuple.
ith
Syntax
tuple_name = ([item1, item2], value)
. A
1 tuple itself is immutable.
od
2. But if a tuple contains a mutable item like a list, the inner list can be changed.
3. This happens because the tuple is still pointing to the same inner list.
C
Example 1
PYTHON CODE
data = ([10, 20], "Python")
data[0][1] = 99
print(data)
9.2.7 Tuple Methods
al
Method Purpose Example Result
h
count() Counts how many times a value appears [Link](10) Count of10
hc
index() Returns index of first matching value [Link](20) Position of20
Explanation
. T
1 uple packing means storing multiple values together in a tuple.
2. Python automatically packs comma-separated values into a tuple.
3. Parentheses are optional, but recommended for readability.
al
Example 1
h
PYTHON CODE
student = "Aman", 21, "Python"
hc
print(student)
print(type(student))
Explanation
1. T uple unpacking means taking values from a tuple and storing them in separate
variables.
2. The number of variables should match the number of tuple values.
3. Unpacking makes code cleaner and readable.
Example 1
utput:
O
al
Aman
21
h
Python
hc
Important Point
This gives an error: is
PYTHON CODE
N
student = ("Aman", 21, "Python")
name, age = student
ith
Because the tuple has 3 values, but only 2 variables are given.
od
Explanation
1. E xtended unpacking is used when we do not want to manually create variables for
every value.
2. The starred variable collects extra values.
3. The starred variable becomes a list.
Example 1
PYTHON CODE
numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)
print(middle)
print(last)
utput:
O
al
10
[20, 30, 40]
50
h
Important point:The starred variable stores valuesin a list, not a tuple.
hc
9.2.12 Named Tuples
Syntax
is
N
from collections import namedtuple
TupleName = namedtuple("TupleName", ["field1", "field2"])
ith
Explanation
eW
.
1 named tuple is a tuple with named fields.
A
2. Normal tuple values are accessed by index.
3. Named tuple values can be accessed by name.
4. This makes code more readable.
5. Named tuples are immutable like normal tuples.
od
Example 1
C
Output:Aman
21
Python
Normal Tuple vs Named Tuple
Normal Tuple Named Tuple
al
Point List Tuple
h
Mutability Mutable Immutable
hc
Can update items Yes No
Can add/remove items Yes No
Speed
Best for
is
Slightly slower
Data that may change
Slightly faster
Data that should not change
N
Important Tuple Operations Table
ith
Syntax
h al
.
1 dictionary stores data usingkeysandvalues.
A
2. Each key is connected to one value.
hc
3. Keys are used to access values.
4. Dictionaries are mutable, so values can be changed.
5. Dictionary keys must be unique.
6. Dictionaries are written using curly braces{}.
is
Flow Chart
N
ith
eW
od
Example 1
PYTHON CODE
student = {
C
"name": "Aman",
"age": 21,
"course": "Python"
}
print(student)
al
Dictionary Properties Table
h
Property Meaning Example
hc
Key-value based Stores data as pairs "name": "Aman"
Ordered
is
Keeps insertion order Python 3.7+
N
Unique keys Duplicate keys are not allowed Last value replaces old value
Mixed values allowed Values can be any data type string, int, list, tuple, dict
eW
Explanation
.
1 ictionaries are created using{}.
D
2. Keys and values are separated using a colon:.
3. Each pair is separated using a comma.
4. Keys are usually strings, but numbers and tuples can also be used.
5. Values can be any data type.
PYTHON CODE
student = {
"name": "Rahul",
"age": 20,
"marks": 85.5,
"is_passed": True
}
print(student)
Output:{'name': 'Rahul', 'age': 20, 'marks': 85.5,'is_passed': True}
al
Different Ways to Create Dictionaries
h
Type Example
hc
Empty dictionary data = {}
Normal dictionary student = {"name": "Aman", "age": 21}
is
Usingdict() student = dict(name="Aman", age=21)
Nested dictionary students = {"s1": {"name": "Aman"}}
N
Dictionary with list value data = {"marks": [80, 90, 85]}
ith
Syntax
od
C
Explanation
.
1 keyis used to identify a value.
A
2. Avalueis the data stored against the key.
3. Keys must be unique.
4. Values can be duplicate.
5. Keys should be immutable types like string, number, or tuple.
Output:Aman
al
Key Rules Table
h
Rule Allowed? Example
hc
String key Yes "name": "Aman"
Output:{'name': 'Rahul'}
The second value replaces the first value because dictionary keys must be unique.
9.3.3 Accessing Values
Syntax
dictionary_name[key]
Explanation
.
1 ictionary values are accessed using keys.
D
2. Unlike lists and tuples, dictionaries are not accessed mainly by index.
al
3. If the key exists, Python returns its value.
4. If the key does not exist, Python givesKeyError.
h
hc
is
N
ith
eW
Example 1
od
C
utput:
O
Aman
21
Accessing Table
Code Meaning Result
KeyError Example
al
PYTHON CODE
student = {
h
"name": "Aman",
hc
"age": 21
}
print(student["marks"])
utput:
O
KeyError: 'marks'
is
N
The key"marks"does not exist.
Syntax
eW
dictionary_name[key] = new_value
.
1 ictionaries are mutable.
D
2. Existing values can be updated using keys.
3. If the key already exists, its value is updated.
od
4. If the key does not exist, a new key-value pair is added.
PYTHON CODE
student = {
C
"name": "Aman",
"age": 21
}
student["age"] = 22
student["course"] = "Python"
print(student)
PYTHON CODE
student = {
"name": "Aman",
al
"age": 21,
"course": "Python"
h
}
hc
Dictionary Methods Table
Method Purpose
is Example Result / Effect
N
keys() Returns all keys [Link]() dict_keys(['name', 'age', 'course'])
inserted pair
setdefault() G
ets value or adds [Link]("city",
s Adds city if missing
default "Delhi")
al
update() Yes None
h
popitem() Yes Removed key-value pair
hc
clear() Yes None
9.3.6get()Method
eW
Syntax
od
C
Explanation
.
1 et()is used to access dictionary values safely.
g
2. If the key exists, it returns the value.
3. If the key does not exist, it returnsNoneby default.
4. We can also provide our own default value.
5. get()avoidsKeyError.
Flow Chart
al
Example 1
h
PYTHON CODE
hc
student = {
"name": "Aman",
"age": 21 is
}
N
print([Link]("name"))
print([Link]("marks"))
ith
utput:
O
Aman
eW
None
Not available
[]vsget()Table
od
student["name"] eturns
R GivesKeyError
value
C
[Link]("name") eturns
R ReturnsNone
value
Explanation
al
.
1 op(key)removes a specific key and returns its value.
p
2. popitem()removes the last inserted key-value pair.
h
3. delremoves a specific key.
hc
4. clear()removes all items.
Example 1
od
PYTHON CODE
student = {
"name": "Aman",
C
"age": 21,
"course": "Python"
}
[Link]("age")
print(student)
Explanation
al
.
1 dictionary can be looped through usingfor.
A
h
2. By default, looping over a dictionary gives keys.
3. Usevalues()to loop through values.
hc
4. Useitems()to loop through both keys and values.
is
N
ith
Example 1
eW
PYTHON CODE
student = {
"name": "Aman",
"age": 21,
od
"course": "Python"
}
for key, value in [Link]():
C
print(key, value)
utput:
O
name Aman
age 21
course Python
9.3.9 Checking Key Membership
Syntax
al
Explanation
h
. inchecks whether a key exists in the dictionary.
1
2. It checks keys, not values.
hc
3. It returnsTrueorFalse.
Example 1 is
N
ith
eW
utput:
O
od
True
False
Membership Table
C
Code Meaning
h al
hc
Explanation is
1. A nested dictionary means a dictionary inside another dictionary.
2. It is useful for storing structured data.
N
3. To access inner values, use multiple keys.
4. N
ested dictionaries are common in real-world data like users, students, products, and
ith
API responses.
eW
od
C
Example 1
PYTHON CODE
students = {
"student1": {
"name": "Aman",
"age": 21
},
"student2": {
"name": "Riya",
"age": 20
al
}
}
h
print(students["student1"]["name"])
hc
print(students["student2"]["age"])
utput:
O
Aman is
20
N
ith
eW
With condition:
h al
Explanation
hc
.
1 ictionary comprehension is a short way to create a dictionary.
D
2. It is similar to list comprehension.
3.
4.
is
It creates key-value pairs using a loop.
It can also include conditions.
N
Flow Chart
ith
Take sequence
|
v
Loop through items
eW
|
v
Create key-value pair
|
v
od
Example 1
C
PYTHON CODE
Output:
{1: 1, 2: 4, 3: 9, 4: 16}
Example 2: With Condition
PYTHON CODE
Dictionary Comprehension Parts
al
Part Meaning
h
numberbefore: Key
hc
number * number Value
if number % 2 == 0
is
Optional condition
N
9.3.12 Merging Dictionaries
ith
Example 1: Usingupdate()
PYTHON CODE
student = {
od
"name": "Aman",
"age": 21
}
C
extra = {
"course": "Python",
"city": "Delhi"
}
[Link](extra)
print(student)
student = {
"name": "Aman",
"age": 21
}
extra = {
"course": "Python",
al
"city": "Delhi"
}
h
result = student | extra
print(result)
hc
Output: {'name': 'Aman', 'age': 21, 'course': 'Python', 'city': 'Delhi'}
PYTHON CODE
Syntax
new_dict = old_dict.copy()
Explanation
. c
1 opy()creates a shallow copy of a dictionary.
2. Direct assignment does not create a new dictionary.
3. Direct assignment makes both variables point to the same dictionary.
Direct Assignment Example
PYTHON CODE
student2["age"] = 22
print(student1)
print(student2)
al
utput:
O
{'name': 'Aman', 'age': 22}
h
{'name': 'Aman', 'age': 22}
hc
Real Copy Example
PYTHON CODE
student2["age"] = 22
print(student1)
print(student2)
eW
Output:
Copying Table
C
al
Example ["Aman", 21] {"name": "Aman", "age": 21}
h
9.3.15 Important Dictionary Operations
hc
Operation Code Meaning
Create dictionary
pairs
Syntax
al
Explanation
h
.
1 ets are written using curly braces{}.
S
2. Set items are separated by commas.
hc
3. Sets store only unique values.
4. Sets are unordered, so items do not have fixed positions.
5. Sets are mutable, so we can add or remove items.
6. Set elements must be immutable/hashable values.
is
Example 1
N
PYTHON CODE
ith
{40, 10, 20, 30} : The output order may look different because sets are unordered.
Unique values Duplicate values are removed {10, 10, 20}becomes{10, 20}
Mixed data allowed Can store different immutable types {10, "Aman", True}
. S
1 ets can store numbers, strings, Booleans, and tuples.
2. Sets cannot store mutable values like lists or dictionaries.
3. Empty set must be created usingset().{}createsan empty dictionary, not an empty
set.
Example 1
al
PYTHON CODE
h
numbers = {10, 20, 30}
hc
names = {"Aman", "Riya", "Kabir"}
mixed = {"Python", 100, 99.5, True}
empty_set = set() is
print(numbers)
N
print(names)
ith
print(mixed)
print(empty_set)
utput:
O
eW
a = {}
b = set()
print(type(a))
print(type(b))
utput:
O
<class 'dict'>
al
<class 'set'>
h
hc
Syntax
set_name = {value1, value2, value1} is
.
1 ets automatically remove duplicate values.
S
N
2. Each value appears only once.
3. This makes sets useful for removing duplicates from data.
4. Sets check uniqueness using the value, not position.
ith
Example 1
eW
PYTHON CODE
numbers = {10, 20, 10, 30, 20, 40}
print(numbers)
od
PYTHON CODE
numbers = [10, 20, 10, 30, 20, 40]
unique_numbers = set(numbers)
print(unique_numbers)
Explanation
.
1 et elements must be hashable.
S
2. Immutable values like numbers, strings, and tuples can be stored in a set.
al
3. Mutable values like lists, dictionaries, and sets cannot be stored in a set.
4. This is because sets internally need stable values to check uniqueness.
h
Example 1
hc
PYTHON CODE
valid_set = {10, "Python", (1, 2)}
print(valid_set)
is
N
Output:{10, 'Python', (1, 2)}
ith
Invalid example:
PYTHON CODE
eW
Explanation
.
1 ets do not support indexing.
S
2. Sets do not support slicing.
3. Values can be accessed by looping.
al
4. Membership can be checked usingin.
Example 1
h
PYTHON CODE
hc
languages = {"Python", "Java", "C++"}
for language in languages:
print(language)
ossible output:
P
is
N
Java
Python
ith
C++
Output order may differ.
Invalid Access:
eW
PYTHON CODE
languages = {"Python", "Java", "C++"}
print(languages[0])
od
Accessing Table
C
Explanation
.
1 ets are very useful for checking whether a value exists.
S
al
2. inreturnsTrueif value exists.
3. not inreturnsTrueif value does not exist.
h
4. Membership checking in sets is usually faster than lists for large data.
Example:
hc
is
N
ith
utput:
O
True
False
True
eW
Explanation
.
1 dd()adds one item.
a
2. update()adds multiple items.
3. If an added value already exists, it is not added again.
4. Sets automatically maintain uniqueness.
Example 1
PYTHON CODE
numbers = {10, 20, 30}
[Link](40)
[Link]([50, 60, 20])
print(numbers)
20was already present, so it is not duplicated.
al
add()vsupdate()
h
Method Adds Example
hc
add() One item [Link](10)
set_name.remove(value)
set_name.discard(value)
set_name.pop()
eW
set_name.clear()
.
1 r emove()removes a specific item.
2. discard()also removes a specific item.
od
Example:
C
PYTHON CODE
numbers = {10, 20, 30, 40}
[Link](20)
[Link](50)
print(numbers)
al
9.4.8 Set Operations
h
et operations are used to compare or combine sets.
S
hc
Main set operations:
.
1 nion
U
2.
3.
4.
Intersection
Difference
Symmetric difference
is
N
5. Subset
6. Superset
ith
7. Disjoint
ssume:
A
a = {1, 2, 3}
eW
b = {3, 4, 5}
Set Operations Table
Operation Symbo Method Meaning Result
l
od
utput:
O
al
{1, 2, 3, 4, 5}
{3}
h
{1, 2}
{1, 2, 4, 5}
hc
9.4.9 Union
Syntax
et1 | set2
s
is
N
[Link](set2)
ith
Explanation
. U
1 nion combines two sets.
eW
Example 1
od
PYTHON CODE
a = {1, 2, 3}
C
b = {3, 4, 5}
result = [Link](b)
print(result)
Output:{1, 2, 3, 4, 5}
= {1, 2, 3}
a
b = {3, 4, 5}
Union = all unique values = {1, 2, 3, 4, 5}
9.4.10 Intersection
Syntax
set1 & set2
[Link](set2)
al
PYTHON CODE
a = {1, 2, 3}
h
b = {3, 4, 5}
hc
result = [Link](b)
print(result)
Output: {3}
is
N
9.4.11 Difference
ith
Syntax
et1 - set2
s
eW
[Link](set2)
. D
1 ifference returns values present in the first set but not in the second set.
2. a - bandb - acan give different results.
od
PYTHON CODE
a = {1, 2, 3}
b = {3, 4, 5}
C
print(a - b)
print(b - a)
utput:
O
{1, 2}
{4, 5}
a - b = values in a but not in b = {1, 2}
b - a = values in b but not in a = {4, 5}
9.4.12 Symmetric Difference
Syntax
set1 ^ set2
set1.symmetric_difference(set2)
. S
1 ymmetric difference returns values that are not common.
2. It removes common values from the final result.
al
PYTHON CODE
a = {1, 2, 3}
b = {3, 4, 5}
h
result = a.symmetric_difference(b)
hc
print(result)
[Link](set2)
s
[Link](set2)
[Link](set2)
eW
. A
1 subset means all values of one set exist inside another set.
2. A superset means one set contains all values of another set.
3. Disjoint sets have no common values.
od
PYTHON CODE
a = {1, 2}
b = {1, 2, 3, 4}
C
c = {5, 6}
print([Link](b))
print([Link](a))
print([Link](c))
utput:
O
True
True
True
Comparison Table
Concept Meaning Example Result
Subset All items ofaare inb {1, 2} <= {1, 2, 3} True
Superset bcontains all items ofa {1, 2, 3} >= {1, 2} True
al
Method Purpose Example Result / Effect
h
update() Adds multiple items [Link]([10, 20]) Adds all items
hc
remove() Removes item [Link](10) Error if missing
ymmetric_differe
s Items not common a.symmetric_difference(b) New set
nce()
od
ifference_update( R
d emoves items found in other a.difference_update(b) Changesa
) set
ymmetric_differe
s Keeps non-common items .symmetric_difference_u Changesa
a
nce_update() pdate(b)
- Difference [Link](b)
al
^ Symmetric difference a.symmetric_difference(b)
h
<= Subset check [Link](b)
hc
< Proper subset check a < b
Syntax
et1.intersection_update(set2)
s
set1.difference_update(set2)
eW
set1.symmetric_difference_update(set2)
. N
1 ormal set operation methods return a new set.
2. Update methods change the original set.
3. These are useful when we do not need the old set.
od
PYTHON CODE
a = {1, 2, 3}
C
b = {3, 4, 5}
a.intersection_update(b)
print(a)
Output: {3}
9.4.17 Copying Sets
Syntax
new_set = old_set.copy()
. c
1 opy()creates a shallow copy of a set. Direct assignmentdoes not create a new set.
2. Direct assignment makes both variables point to the same set.
PYTHON CODE
a = {10, 20, 30}
al
b = [Link]()
[Link](40)
h
print(a)
print(b)
hc
Output:{10, 20, 30}
{40, 10, 20, 30}
Copying Table
is
N
Code Creates New Set? Meaning
frozenset_name = frozenset(iterable)
. A
1 normal set is mutable. A frozenset is immutable.
2. Values cannot be added or removed from a frozenset. Frozensets can be used as
C
PYTHON CODE
numbers = frozenset([10, 20, 30])
print(numbers)
print(type(numbers))
Mutable Yes No
al
Add items Allowed Not allowed
Remove items Allowed Not allowed
h
Unique values Yes Yes
hc
Unordered Yes Yes
Can be dictionary key No Yes
Can be set element No is Yes
Syntax {1, 2, 3} frozenset([1, 2, 3])
N
Frozenset Methods Table
ith
.
1 et comprehension is a short way to create a set.
S
2. It is similar to list comprehension.
3. It automatically keeps only unique values.
al
4. It can include conditions.
h
Example 1
hc
PYTHON CODE
numbers = [1, 2, 2, 3, 4, 4]
squares = {number * number for number in numbers}
is
print(squares)
N
Output:{16, 1, 4, 9} :Duplicate input values donot create duplicate set values.
ith
PYTHON CODE
numbers = [1, 2, 3, 4, 5, 6]
ven_numbers = {number for number in
e
numbers if number % 2 == 0}
print(even_numbers)
od
list(set_name)
tuple(set_name)
.
1 et()converts an iterable into a set.
s
al
2. This is often used to remove duplicates.
3. A set can be converted back to a list or tuple.
h
4. Order may change after converting to a set.
hc
Example 1
PYTHON CODE
print(list(unique_numbers))
utput:
O
{10, 20, 30}
eW
Conversion Table
od
al
Slicing Yes Yes No
h
Example [10, 20] (10, 20) {10, 20}
hc
Important Set Operations Table
Operation Code
is Meaning
Syntax
h al
hc
.
1 ollectionsis a built-in Python module.
c
2. It gives ready-made advanced data structures.
3. These structures help solve common problems easily.
4. They are useful for counting, grouping, ordering, fast queue operations, and
is
combining dictionaries.
N
Collections Module Overview
Tool Main Use
ith
9.5.1Counter
C
Syntax
Explanation
.
1 ountercounts repeated values.
C
2. It returns a dictionary-like object.
3. Items become keys.
4. Their counts become values.
5. It is commonly used for frequency counting.
Flow Chart
Input data
|
al
v
Counter checks each item
h
|
v
hc
Counts repeated items
|
v
Returns item-count pairs is
Example 1
N
PYTHON CODE
ith
print(count)
Example 2
PYTHON CODE
C
update() Adds more counts [Link](data)
al
subtract() Subtracts counts [Link](data)
h
hc
9.5.2defaultdict
defaultdictis a dictionary that gives a default valuewhen a key does not exist.
Syntax
is
N
from collections import defaultdict
dictionary_name = defaultdict(default_type)
ith
Explanation
eW
.
1 ormal dictionaries giveKeyErrorif a key does notexist.
N
2. defaultdictavoids this problem.
3. It automatically creates a default value for missing keys.
4. Common default types areint,list, andset.
od
Flow Chart
C
Example 1: Usingint
PYTHON CODE
from collections import defaultdict
marks = defaultdict(int)
marks["math"] += 10
marks["science"] += 20
print(marks)
Here, missing keys start with default value0.
al
Common Default Types
h
Default Type Default Value Common Use
hc
int 0 Counting
set set()
is
Grouping unique values
Example 2: Usinglist
PYTHON CODE
from collections import defaultdict
eW
students = defaultdict(list)
students["Python"].append("Aman")
students["Python"].append("Riya")
od
students["Java"].append("Kabir")
print(students)
C
Syntax
PYTHON CODE
from collections import OrderedDict
dictionary_name = OrderedDict()
al
Explanation
h
.
1 rderedDictstores key-value pairs in order.
O
2. Normal dictionaries also preserve insertion order in modern Python.
hc
3. OrderedDictis still useful because it has extra order-relatedmethods.
4. It can move items to the beginning or end.
5. It can remove items from either side.
Example 1
is
N
PYTHON CODE
from collections import OrderedDict
ith
student = OrderedDict()
student["name"] = "Aman"
student["age"] = 21
eW
student["course"] = "Python"
print(student)
od
UsefulOrderedDictMethods
C
ove_to_end(key,
m oves key to the
M ata.move_to_end("name",
d
last=False) beginning last=False)
reserves insertion
P Yes, in modern Python Yes
order
al
9.5.4deque
h
hc
dequemeansdouble-ended queue.
Syntax
is
N
from collections import deque
ith
deque_name = deque(iterable)
.
1 equeis used when we need fast insert/remove fromleft and right.
d
2. It works like a queue and stack.
eW
Example 1
od
PYTHON CODE
from collections import deque
numbers = deque([10, 20, 30])
C
[Link](40)
[Link](5)
print(numbers)
CommondequeMethods
Method Meaning Example
al
clear() Removes all items [Link]()
List vsdeque
h
Point List deque
hc
Add at end Fast Fast
9.5.5ChainMap
eW
Syntax
od
.
1 hainMapgroups multiple dictionaries together.
C
2. It does not merge them permanently.
3. It creates a combined view.
4. When searching for a key, Python checks dictionaries from left to right.
5. If the same key exists in multiple dictionaries, the first one is used.
Example 1
PYTHON CODE
from collections import ChainMap
defaults = {
"theme": "light",
"language": "English"
}
user_settings = {
"theme": "dark"
}
al
settings = ChainMap(user_settings, defaults)
print(settings["theme"])
h
print(settings["language"])
hc
utput:
O
dark
English is
Explanation:
N
. " theme"exists inuser_settings, so"dark"is used.
1
2. "language"is not inuser_settings, so Python checksdefaults.
ith
eW
UsefulChainMapFeatures
Feature Meaning Example
Basic idea
Function = reusable block of code
Simple flow
al
Define function
|
v
h
Call function
hc
|
v
Function code runs
| is
v
Result/output is produced
N
10.1 What is a Function?
ith
Syntax
eW
od
.
1 function groups related code together.
A
2. A function runs only when it is called.
3. Functions help avoid repeated code.
4. Functions make code clean, reusable, and easy to understand.
C
Function body executes
al
|
v
Program continues
h
PYTHON CODE
hc
def greet():
print("Hello, welcome to Python")
greet()
is
N
Output:Hello, welcome to Python
ith
.
1 efis used to define a function.
d
2. The function name comes afterdef.
C
This only defines the function. It does not run yet. To run it, we must call it.
say_hello()
Output:Hello
Empty Function
al
If we want to create a function but write logic later, usepass.
h
PYTHON CODE
hc
def future_function():
pass
function_name()
eW
.
1 alling a function means executing it.
C
2. A function can be called once or many times.
3. The function body runs every time the function is called.
4. If a function is defined but never called, its code will not execute.
od
Example 1
PYTHON CODE
def greet():
C
print("Hello")
greet()
greet()
greet()
Output:Hello
Hello
Hello
10.4 Parameters
parameteris a variable written inside the functiondefinition. It receives values when the
A
function is called.
Syntax
PYTHON CODE
def function_name(parameter):
statement
Explanation
al
.
1 arameters make functions flexible.
P
h
2. Parameters allow us to send data into a function.
3. A function can have one or more parameters.
hc
4. Parameters are written inside parentheses during function definition.
Flow Chart is
Function definition has parameter
|
N
v
Function call sends value
|
ith
v
Parameter receives value
|
eW
v
Function uses that value
Example 1
od
PYTHON CODE
def greet(name):
print("Hello", name)
greet("Aman")
C
utput:
O
Hello Aman
Here,nameis a parameter.
10.5 Arguments
Anargumentis the actual value passed to a functionduring function call.
Syntax
function_name(argument)
Explanation
. P
1 arameter is written in function definition.
al
2. Argument is passed during function call.
3. Arguments provide real values to parameters.
h
Parameter vs Argument
hc
Term Where It Appears Meaning
Example 1
N
PYTHON CODE
ith
def greet(name):
print("Hello", name)
greet("Riya")
eW
Output:Hello Riya
Code Role
od
name Parameter
"Riya" Argument
C
Syntax
function_name(argument1, argument2)
Explanation
.
1 ython passes arguments in the same order as parameters.
P
2. The first argument goes to the first parameter.
3. The second argument goes to the second parameter.
4. Order matters in positional arguments.
Example 1
PYTHON CODE
def student_info(name, age):
al
print("Name:", name)
print("Age:", age)
h
student_info("Aman", 21)
hc
utput:
O
Name: Aman
Age: 21
is
N
Flow Chart
ith
student_info("Aman", 21)
| |
eW
v v
name age
Syntax
def function_name():
return value
.
1 r eturnsends a value back to the place where the function was called.
2. A function can return one value or multiple values.
3. Afterreturn, the function stops executing.
4. If there is noreturn, Python returnsNoneautomatically.
Flow Chart
h al
Example 1
hc
PYTHON CODE
def add(a, b):
result = a + b
return result
is
N
answer = add(10, 20)
print(answer)
ith
Output:
eW
30
PYTHON CODE
def greet():
print("Hello")
C
result = greet()
print(result)
Output:Hello
None
. M
1 ultiple values can be returned using commas.
2. Python returns them as a tuple.
3. Returned values can be unpacked into variables.
al
Example 1
h
PYTHON CODE
def calculate(a, b):
hc
total = a + b
difference = a - b
return total, difference
is
sum_result, diff_result = calculate(20, 10)
print(sum_result)
print(diff_result)
N
utput:
O
ith
30
10
eW
Syntax
C
.
1 efault parameters make arguments optional.
D
2. If an argument is provided, Python uses the given value.
3. If no argument is provided, Python uses the default value.
4. Non-default parameters must come before default parameters.
Example 1
PYTHON CODE
def greet(name="Guest"):
print("Hello", name)
greet("Aman")
greet()
Output:
Hello Aman
Hello Guest
al
Correct and Incorrect Order
h
Code Valid? Reason
hc
def show(name, age=18): Yes efault parameter comes after normal
D
parameter
Wrong style:
eW
od
Output:['A']
['A', 'B']
The same list is reused between function calls.
C
Better style:
Output: ['A']
['B']
10.10 Keyword Arguments
Keyword arguments pass values using parameter names.
Syntax
.
1 eyword arguments use names while calling a function.
K
2. Order does not matter when keyword arguments are used.
3. They make function calls more readable.
4. Positional arguments must come before keyword arguments.
al
Example 1
h
PYTHON CODE
hc
def student_info(name, age, course):
print("Name:", name)
print("Age:", age)
print("Course:", course)
tudent_info(age=21, course="Python",
s
is
N
name="Aman")
Output:Name: Aman
ith
Age: 21
Course: Python
Positional vs Keyword Arguments
eW
Important Rule
C
Correct:
Incorrect:
Syntax
.
1 * argscollects extra positional arguments.
2. The collected values are stored as a tuple.
al
3. The nameargsis a convention; the*is important.
4. Use*argswhen the number of arguments is flexible.
h
Flow Chart
hc
Function call has many positional arguments
|
v
*args collects them
|
is
N
v
Values are stored as a tuple
ith
Example 1
eW
PYTHON CODE
def add_numbers(*numbers):
total = 0
for number in numbers:
total += number
od
return total
print(add_numbers(10, 20, 30))
C
print(add_numbers(5, 15))
utput:
O
60
20
Here,numbersbehaves like a tuple.
10.12**kwargs
**kwargsis used when we do not know how many keywordarguments will be passed.
Syntax
al
Explanation
h
.
1 * *kwargscollects extra keyword arguments.
2. The collected values are stored as a dictionary.
hc
3. Keys are argument names.
4. Values are argument values.
5. The namekwargsis a convention; the**is important.
Flow Chart
is
N
Function call has many keyword arguments
|
ith
v
**kwargs collects them
|
v
eW
Example 1
od
PYTHON CODE
def show_profile(**details):
for key, value in [Link]():
print(key, value)
C
how_profile(name="Aman", age=21,
s
course="Python")
Output:
name Aman
age 21
course Python
al
Example 1
h
PYTHON CODE
def show_data(*args, **kwargs):
hc
print(args)
print(kwargs)
Syntax
C
Explanation
.
1 ormal parameters come first.
N
2. Default parameters come after normal parameters.
3. *argscomes after normal/default parameters.
4. **kwargscomes last.
5. This order keeps function calls clear and valid.
Parameter Order Table
Order Parameter Type Example
Example 1
h al
hc
Output:
is
ame: Aman
N
N
Age: 21
Marks: (80, 90, 85)
ith
10.15 Docstrings
Adocstringis a string written inside a function to explain what the function does.
od
Syntax
C
.
1 docstring is written using triple quotes.
A
2. It is usually written as the first statement inside a function.
3. It explains the purpose of the function.
4. It helps other programmers understand the function.
5. It can be viewed usinghelp()or.__doc__.
Example 1
Output:30
al
Return the sum of two numbers.
h
hc
is
N
ith
eW
Syntax
def function_name():
C
statement
.
1 unction names should be meaningful.
F
2. Usesnake_casefor function names.
3. Function names should usually describe an action.
4. Avoid using Python keywords as function names.
5. Avoid unclear names likex(),abc(), ortest1().
Chapter 11. Advanced Functions
Advanced functions help us write more flexible, reusable, and compact code.
.
1 function can be stored in a variable.
A
2. A function can be passed as an argument.
3. A function can be returned from another function.
4. A function can be written inside another function.
al
11.1 Functions as First-Class Objects
h
Syntax
hc
def function_name():
statement
new_name = function_name
is
N
In Python, functions behave like normal objects. We can store a function in a variable and
call it using that variable.
ith
Flow Chart
Create function
eW
|
v
Assign function to variable
|
v
od
Example 1
C
PYTHON CODE
def greet():
print("Hello Python")
message = greet
message()
utput:
O
Hello Python
Here,messagerefers to the same function asgreet.
11.2 Lambda Functions
lambda functionis a small anonymous function. Anonymousmeans it does not need a
A
normal function name.
Syntax
lambda arguments: expression
.
1 ambda functions are used for small one-line functions.
L
2. They can take any number of arguments.
al
3. They can contain only one expression.
4. They automatically return the result of the expression.
5. Lambda functions are commonly used withmap(),filter(),and sorting.
h
Example 1
hc
Normal function:
is
N
ith
utput:
O
25
Same logic using lambda:
eW
od
Output:25
Example 2
C
Output:30
Lambda is best for simple logic. For complex logic, use normal def functions.
11.3map()
map()applies a function to every item of an iterable.
Syntax
map(function, iterable)
Explanation
al
.
1 ap()takes a function and an iterable.
m
2. It applies the function to each item.
3. In Python 3,map()returns a map object, which isan iterator.
h
4. To display all results at once, convert it usinglist().
hc
Example 1
PYTHON CODE
numbers = [1, 2, 3, 4]
is
squares = map(lambda number: number * number, numbers)
N
print(list(squares))
ith
Output:[1, 4, 9, 16]
Example 2
eW
map()Table
C
Part Meaning
numbers Iterable
Syntax
filter(function, iterable)
Explanation
.
1 filter()takes a function and an iterable.
2. The function must returnTrueorFalse.
3. Items that returnTrueare kept.
al
4. Items that returnFalseare removed.
5. In Python 3,filter()returns a filter object, whichis an iterator.
h
Flow Chart
hc
Iterable values
|
v is
filter() checks condition
|
N
├── True -> keep item
|
└── False -> remove item
ith
|
v
Filtered result
eW
Example 1
PYTHON CODE
umbers = [1, 2, 3, 4, 5, 6]
n
even_numbers = filter(lambda number: number % 2 == 0, numbers)
od
print(list(even_numbers))
Output:[2, 4, 6]
map()vsfilter()
C
Syntax
from functools import reduce
reduce(function, iterable)
al
Explanation
h
.
1 r educe()takes a function and an iterable.
2. It combines values step by step.
hc
3. It returns one final result.
4. It is useful for cumulative calculations.
5. For simple addition,sum()is usually better.
is
Example 1
N
PYTHON CODE
ith
print(total)
utput:10
O
Working idea:
1 + 2 = 3
od
3 + 3 = 6
6 + 4 = 10
C
map()vsfilter()vsreduce()
Function Purpose Final Result
A correct recursive function must have a stopping condition.
al
1. R ecursion is used when a problem can be broken into smaller versions of the same
problem.
h
2. A recursive function calls itself.
3. Every recursion must have a base case.
hc
4. The base case stops the recursion.
5. Without a base case, recursion continues until Python raisesRecursionError.
Part
Base case
is
Meaning
Flow Chart
eW
od
Example 1: Factorial
Factorial means: 5! = 5 × 4 × 3 × 2 × 1
PYTHON CODE
C
def factorial(number):
if number == 1:
return 1
return number * factorial(number - 1)
print(factorial(5))
Output: 120
factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 *
factorial(1) = 5 * 4 * 3 * 2 * 1 = 120
11.7 Nested Functions
A nested function is a function defined inside another function.
Syntax
PYTHON CODE
def outer_function():
def inner_function():
statement
inner_function()
al
.
1 nested function is created inside another function.
A
2. The inner function can be used only inside the outer function.
3. Nested functions are useful for hiding helper logic.
h
4. They are also used in closures and decorators.
hc
Example 1
PYTHON CODE is
def outer():
print("Outer function started")
N
def inner():
print("Inner function executed")
ith
inner()
outer()
eW
11.8 Closures
od
closure is created when an inner function remembers variables from its outer function,
A
even after the outer function has finished.
Syntax
C
.
1 closure needs a nested function.
A
2. The inner function uses a variable from the outer function.
3. The outer function returns the inner function.
4. The inner function remembers the outer variable.
5. Closures are useful for creating customized functions.
al
Output:10
h
hc
11.9 Function Annotations
Function annotations are used to add type hints to function parameters and return values.
is
Syntax
N
def function_name(parameter: type) -> return_type:
statement
ith
1. F unction annotations describe expected data types. They make code easier to
understand.
2. They help editors and tools detect possible mistakes.
eW
Example 1
od
PYTHON CODE
def add(a: int, b: int) -> int:
return a + b
C
print(add(10, 20))
Output: 30
utput: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
O
Important point:Type hints are hints. Python does not stop wrong types automatically.
11.10 Higher-Order Functions
A higher-order function is a function that does at least one of these:
. T
1 akes another function as an argument.
2. Returns another function.
Syntax
h al
hc
OR
Explanation is
.
1 igher-order functions are possible because Python functions are objects.
H
N
2. They are used inmap(),filter(),reduce(), decorators,and callbacks.
3. They make code flexible and reusable.
ith
PYTHON CODE
def shout(text):
return [Link]()
od
Output:HELLO
al
local scopeis created inside a function. Variablescreated inside a function are local
A
variables.
h
Syntax
hc
is
N
Explanation
ith
.
1 local variable is created inside a function.
A
2. It can be used only inside that function.
3. It cannot be accessed directly outside the function.
eW
Example 1
od
PYTHON CODE
def show_name():
name = "Aman"
print(name)
C
show_name()
utput:Aman
O
Invalid outside access:
PYTHON CODE
print(name)
Syntax
PYTHON CODE
variable_name = value
al
def function_name():
statement
h
hc
Explanation
.
1 global variable is created outside functions.
A
2.
3.
4.
is
It can be accessed inside functions.
It can also be accessed outside functions.
Reading a global variable inside a function does not require theglobalkeyword.
N
5. To modify a global variable inside a function, we need theglobalkeyword.
ith
Example 1
PYTHON CODE
eW
course = "Python"
def show_course():
print(course)
od
show_course()
print(course)
C
utput:
O
Python
Python
NOTE: Global variables are accessible throughout the file after they are defined.
12.3 Local vs Global Scope
Point Local Scope Global Scope
Accessible where? Only inside that function Inside and outside functions
al
12.4 Variable Shadowing
h
hc
Variable shadowing happens when a local variable has the same name as a global variable.
Explanation is
1. If a local and global variable have the same name, Python uses the local variable
inside the function.
N
2. The global variable is not changed.
3. This is called shadowing.
ith
Example 1
eW
PYTHON CODE
name = "Global Aman"
def show_name():
od
show_name()
print(name)
Output:
ocal Aman
L
Global Aman
NOTE:Inside the function, the local variable gets priority over the global variable.
12.5globalKeyword
Theglobalkeyword is used to modify a global variable inside a function.
Syntax
global variable_name
Explanation
1. U seglobalwhen you want to assign a new value toa global variable inside a
al
function.
2. Withoutglobal, assignment inside a function createsa local variable.
h
3. Reading a global variable does not needglobal. Usingtoo many global variables is
not recommended.
hc
Example 1
PYTHON CODE
count = 0
is
N
def increase_count():
global count
ith
count += 1
increase_count()
eW
print(count)
output:1
Withoutglobal
od
PYTHON CODE
count = 0
C
def increase_count():
count += 1
increase_count()
OTE:Use global only when you really need to modify a global variable. Better style is
N
usually to return a value:
PYTHON CODE
def increase_count(count):
return count + 1
ount = 0
c
count = increase_count(count)
print(count)
Output: 1
al
12.6 Enclosing Scope
h
Anenclosing scopeexists when a function is definedinside another function.
hc
Syntax
is
N
ith
.
1 nclosing scope belongs to the outer function.
E
eW
2. Inner functions can access variables from the outer function.
3. This scope is between local and global scope.
4. Enclosing scope is important for nested functions and closures.
Example 1
od
PYTHON CODE
def outer():
C
message = "Hello"
def inner():
print(message)
inner()
outer()
Output: Hello
12.7nonlocalKeyword
henonlocalkeyword is used to modify a variablefrom the nearest enclosing function
T
scope.
Syntax
nonlocal variable_name
1. n onlocalis used inside nested functions. It allows the inner function to modify a
variable from the outer function.
2. It does not work with global variables.
al
3. The variable must already exist in the enclosing function.nonlocalis commonly used
in closures.
h
Example 1
hc
PYTHON CODE
def outer():
count = 0
def inner(): is
nonlocal count
count += 1
N
print(count)
inner()
ith
outer()
Output:1
eW
Withoutnonlocal
PYTHON CODE
def outer():
od
count = 0
def inner():
C
nonlocal count
count += 1
print(count)
inner()
outer()
utput: UnboundLocalError: cannot access local variable 'count' where it is not associated
O
with a value
globalvsnonlocal
Keyword Used For Scope Affected
al
12.8 Built-in Scope
h
Built-in scope contains names already provided by Python.
Examples: print, len, type, range, sum, max, min
hc
Explanation
.
1
2.
is
uilt-in names are available automatically.
B
We do not need to define them.
N
3. Python searches built-in scope last in the LEGB rule.
4. Avoid using built-in names as variable names.
ith
Example 1
eW
Output: 3
Bad Practice
od
C
his is bad because the list is already a built-in name. Do not use names like list, dict, str, int,
T
sum, or max as variable names.
.
1 ocal scope: inside the current function.
L
2. Enclosing scope: inside outer functions.
3. Global scope: main program/file.
4. Built-in scope: built-in Python names.
Example 1
PYTHON CODE
x = "global"
def outer():
x = "enclosing"
al
def inner():
x = "local"
h
print(x)
hc
inner()
outer() is
Output:local ⇒ Python findsxin the local scopefirst, so it does not search further.
N
LEGB Search Table
ith
Syntax Idea
name -> object
.
1 namespace maps names to values or objects.
A
2. Python uses namespaces to avoid name conflicts.
3. Different scopes have different namespaces.
4. Local, global, and built-in scopes each have their own namespaces.
5. The same name can exist in different namespaces without conflict.
Example 1
PYTHON CODE
= 100
x
def show():
x = 50
print(x)
how()
s
print(x)
Output:50
100
al
. T
1 he global namespace hasx = 100. The local namespaceinsideshow()hasx = 50.
2. Both names arex, but they belong to different namespaces.
h
hc
Namespace Table
Namespace Contains
Local namespace
Global namespace
is
Names inside a function
Names created at file/program level
N
Built-in namespace Python built-in names
Enclosing namespace Names inside outer functions
ith
12.11locals()andglobals()
eW
Syntax
od
C
.
1 locals()returns the current local namespace as a dictionary.
2. globals()returns the global namespace as a dictionary.
3. These are mainly used for debugging and learning.
4. Usually, we should not modify program logic using them.
Example 1
PYTHON CODE
course = "Python"
def show():
name = "Aman"
print(locals())
show()
Output:{'name': 'Aman'}
al
12.12 NameError & UnboundLocalError
h
These errors are common in scope-related topics.
hc
NameError
NameErroroccurs when Python cannot find a name inLEGB search.
PYTHON CODE
print(age)
is
N
Output: NameError: name 'age' is not defined
ith
UnboundLocalError
nboundLocalErroroccurs when Python treats a variableas local because it is assigned
U
eW
print(x)
x = 20
show()
C
utput:UnboundLocalError: cannot access local variable 'x' where it is not associated with a
o
value
Error Meaning
Built-in scope Python built-in names
al
global Modifies global variable inside function
h
nonlocal Modifies enclosing function variable
hc
LEGB Search order for names
locals()
is
Shows local namespace
N
globals() Shows global namespace
Example:
al
[Link] -> module
h
Why Modules and Packages Are Used
hc
.
1 o organize large programs.
T
2. To reuse code. is
3. To avoid writing the same logic again.
4. To separate code into meaningful files.
N
5. To use built-in Python features from the standard library.
ith
Syntax
import module_name
od
.
1 importloads a module.
2. After importing, we can use functions, classes, and variables from that module.
3. We access module members using dot.notation.
C
4. Import statements are usually written at the top of the file.
Example 1
PYTHON CODE
import math
print([Link](25))
Import with alias import module as alias import math as m [Link](25)
al
Import specific item from module import item from math import sqrt sqrt(25)
h
Import multiple items from module import a, b from math import sqrt, pow sqrt(25)
hc
Import all from module import * from math import * sqrt(25)
Example 1
is
N
PYTHON CODE
from math import sqrt
ith
print(sqrt(36))
eW
Output: 6.0
Important Point
void using from module import * in large programs. It can make code unclear and may
A
od
hestandard libraryis a collection of modules that come with Python. We do not need to
T
install them separately.
Explanation
1. Standard library modules are built into Python.
2. T
hey help with math, dates, files, operating system tasks, random values, JSON, and
more.
3. We can use them by importing them.
Common Standard Library Modules
Module Purpose Example Use
al
sys Python runtime information [Link]
h
statistics Basic statistics [Link](data)
hc
collections Advanced data structures Counter,deque
itertools
pathlib
Iterator tools
Path("[Link]")
N
Example 1
ith
PYTHON CODE
import random
eW
File Structure
project/
│
├── [Link]
└── [Link]
[Link]
PYTHON CODE
def add(a, b):
return a + b
[Link]
PYTHON CODE
import calculator
al
Output: 30
Explanation
.
1 [Link]is a module.
c
h
2. [Link]imports thecalculatormodule.
hc
3. The functionadd()is accessed using[Link]().
4. Both files should be in the same folder for this simple import to work.
is
13.5 Importing Specific Code from Your Own Module
Syntax
N
from module_name import function_name
ith
File structure:
project/
│
├── [Link]
eW
└── [Link]
Example 1
[Link]
PYTHON CODE
def add(a, b):
od
return a + b
return a - b
[Link]\
PYTHON CODE
from calculator import add
print(add(10, 20))
Output: 30
13.6 Module Search Path
When we import a module, Python searches for it in specific locations.
Explanation
Python searches in this general order:
.
1 urrent working directory.
C
2. Paths listed inPYTHONPATH, if set.
3. Standard library directories.
al
4. Installed third-party package directories.
h
Syntax
hc
is
N
13.7 Exploring a Module withdir()
ith
Syntax
dir(module_name)
Explanation
od
. d
1 ir()helps us inspect a module.
2. It shows functions, variables, classes, and special names inside the module.
3. It is useful while learning or debugging.
C
Example 1
PYTHON CODE
import math
print(dir(math))
utput:
O
List of names available inside the math module
NOTE: dir() does not explain what each name does. For explanation, use help().
13.8__name__ == "__main__"
This is used to control whether code should run directly or only when imported.
Syntax
al
.
1 very Python file has a special variable called__name__.
E
2. If the file is run directly,__name__becomes"__main__".
h
3. If the file is imported,__name__becomes the modulename.
4. This is useful for testing module code safely.
hc
5. It prevents some code from running during import.
Example 1 is
[Link]
N
ith
eW
hen importing[Link]into another file, thefunction is available, but the test print
W
od
Flow Chart
Python file runs
C
|
v
Is file run directly?
|
├── Yes -> __name__ is "__main__"
|
└── No -> __name__ is module name
13.9 Package Structure
A package is a folder containing Python modules.
└── mypackage/
al
├── __init__.py
├── [Link]
└── [Link]
h
hc
Explanation
.
1 ypackageis a package.
m
2.
3.
4.
is
[Link]and[Link]are modules inside thepackage.
__init__.pymarks the folder as a regular Python package.
[Link]can import modules from the package.
N
Example 1
ith
mypackage/[Link]
eW
PYTHON CODE
def add(a, b):
return a + b
od
[Link]
PYTHON CODE
C
print(add(10, 20))
Output: 30
13.10__init__.py
__init__.pyis a special file used in Python packages.
Explanation
.
1 _init__.pyis placed inside a package folder.
_
2. It tells Python that the folder is a regular package.
3. It can be empty.
4. It can also contain package-level initialization code.
5. It can control what is exposed when importing from the package.
al
mypackage/
h
├── __init__.py
hc
├── [Link]
└── [Link]
Example 1
is
N
mypackage/__init__.py
ith
PYTHON CODE
from .calculator import add
eW
[Link]
PYTHON CODE
from mypackage import add
od
print(add(10, 20))
Output: 30
C
13.11 Absolute Imports
An absolute import uses the full path from the project/package root.
Syntax
from [Link] import name
Explanation
.
1 bsolute imports are clear and easy to understand.
A
2. They show the full location of the imported module.
3. They are generally preferred in larger projects.
al
4. They reduce confusion compared to complex relative imports.
h
Example 1
hc
Inside[Link]:
This means:
is
N
rom package app,
F
inside module calculator,
ith
import add
A relative imports code based on the current module’s location inside a package.
Syntax
od
Explanation
.
1 elative imports use dots.
R
2. One dot.means current package.
3. Two dots..means parent package.
4. Relative imports are used inside packages.
5. They are not meant for simple standalone scripts.
Syntax Meaning
Example Structure
roject/
p
│
└── app/
al
├── __init__.py
├── [Link]
h
└── [Link]
Inside[Link]:
hc
from .calculator import add
Explanation
C
.
1 he Python standard library comes with Python.
T
2. Third-party packages must be installed separately.
3. pipis used to install third-party packages.
4. Virtual environments are used to keep project dependencies separate.
5. [Link]is used to record project dependencies.
13.14pipBasics
pipis Python’s package installer.
CommonpipCommands
Task Command
Install package python -m pip install package_name
al
Install specific version python -m pip install package_name==1.2.3
h
Upgrade package python -m pip install --upgrade package_name
hc
Uninstall package python -m pip uninstall package_name
how installed
S python -m pip list
packages
is
Show package details python -m pip show package_name
N
NOTE:Use python -m pip instead of only pip. Thismakes surepipbelongs to the
ith
.
1 ifferent projects may need different package versions.
D
2. It prevents package conflicts.
3. It keeps the global Python installation clean.
4. It makes projects easier to share and manage.
C
Deactivate
deactivate
al
13.16[Link]
h
hc
[Link]stores a list of packages neededfor a project.
Syntax is
package_name==version
N
Example
ith
requests==2.32.3
numpy==2.0.0
Task Command
eW
Explanation
1. [Link]helps share project dependencies.
C
2. Another user can install the same packages using one command.
3. It is commonly used in Python projects.
13.17 Third-Party Packages
Third-party packages are packages created by other developers.
They are not part of the Python standard library.
pandas Data analysis
al
flask Web development
h
django Web applications
hc
pytest Testing
Example Structure
N
[Link] imports [Link]
ith
.
1 ircular imports can cause errors or incomplete imports.
C
2. They usually happen when modules depend on each other too much.
eW
Example Problem
od
Better Structure
[Link] -> shared logic
c
[Link] imports [Link]
[Link] imports [Link]
Chapter 14. Object-Oriented Programming in Python
bject-Oriented Programming, orOOP, is a programmingstyle where code is organized
O
usingclassesandobjects.
lass -> blueprint
C
al
Object -> real item created from class
Example idea:
h
lass:Student;
C
hc
Objects:
student1
student2
student3
14.1.1 Classes
Aclassis a blueprint for creating objects.
od
Syntax
C
.
1 class defines the structure of an object.
A
2. A class can contain attributes and methods.
3. Class names usually usePascalCase.
4. A class does not represent one real object by itself.
5. Objects are created from classes.
Example 1
PYTHON CODE
class Student:
pass
student1 = Student()
print(type(student1))
Output: <class '__main__.Student'>
al
Class Naming Style
h
Good Class Name Reason
hc
Student Clear class name
object_name = ClassName()
.
1 n object is created from a class.
A
2. One class can create many objects.
3. Each object can have its own data.
od
Example 1
C
PYTHON CODE
class Student:
pass
student1 = Student()
student2 = Student()
print(student1)
print(student2)
utput:
O
<__main__.Student object at ...>
<__main__.Student object at ...>
The memory address may be different in every run.
Class vs Object
Point Class Object
al
Created using classkeyword Class name with()
h
Memory No object data yet Stores actual object data
hc
14.1.3 Attributes
is
Attributes are variables that belong to an object or class.
Syntax
N
object_name.attribute_name = value
ith
Explanation
. A
1 ttributes store data about an object.
2. Each object can have different attribute values.
eW
Example 1
od
PYTHON CODE
class Student:
pass
C
student1 = Student()
[Link] = "Aman"
[Link] = 21
print([Link])
print([Link])
Output: Aman
21
Attribute Table
Code Meaning
[Link] Accessesnameattribute
[Link] Accessesageattribute
14.1.4 Methods
al
Amethodis a function defined inside a class.
h
hc
Syntax
is
N
ith
.
1 ethods define object behavior.
M
2. Methods are functions inside a class.
eW
Example 1
od
PYTHON CODE
class Student:
def greet(self):
C
print("Hello")
student1 = Student()
[Link]()
Output: Hello
14.1.5self
selfrefers to the current object.
Syntax
def method_name(self):
statement
.
1 elfrepresents the object that is calling the method.
s
2. It is used to access object attributes and methods.
3. Python automatically passes the object asself.
4. selfis not a keyword, but it is the standard convention.
5. Always useselffor instance methods.
al
Example 1
PYTHON CODE
h
class Student:
def show_name(self):
hc
print([Link])
tudent1 = Student()
s is
[Link] = "Aman"
student1.show_name()
N
Output: Aman
ith
14.1.6__init__
eW
Syntax
od
C
.
1 _init__runs automatically when an object is created.
_
2. It is used to set initial attribute values.
3. It is commonly called a constructor.
4. Technically,__init__initializes the object afterit is created.
5. The actual object creation is handled by__new__,which is advanced and usually not
needed in core notes.
Example 1
PYTHON CODE
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
Output:Aman
21
al
14.1.7 Instance Variables
h
hc
Instance variables are variables that belong to a specific object.
Syntax
self.variable_name = value
is
N
.
1 Instance variables are usually created inside__init__.
2. Each object gets its own copy.
3. Changing one object’s instance variable does not affect another object.
ith
Example 1
eW
PYTHON CODE
class Student:
def __init__(self, name):
[Link] = name
od
student1 = Student("Aman")
student2 = Student("Riya")
C
print([Link])
print([Link])
Output: Aman
Riya
Syntax
al
Explanation
h
hc
.
1 lass variables are defined directly inside the class.
C
2. They are shared by all objects.
3. They are useful for common data.
4. They can be accessed using the class name or object name.
is
5. Prefer accessing class variables using the class name.
N
Example 1
ith
PYTHON CODE
class Student:
school_name = "ABC School"
eW
student1 = Student("Aman")
student2 = Student("Riya")
print(student1.school_name)
C
print(student2.school_name)
print(Student.school_name)
utput:
O
ABC School
ABC School
ABC School
Important Warning
al
Avoid mutable class variables unless shared data is intentional.
h
hc
is
This list is shared by all objects, which can cause unexpected behavior.
N
14.1.9 Methods vs Functions
ith
function is independent.
A
A method belongs to a class or object.
eW
Comparison Table
Point Function Method
od
14.2.1 Encapsulation
ncapsulation meansbinding data and methods together inside a classand controlling
E
how data is accessed or modified.
Basic Idea
Data + Methods = Encapsulation
.
1 ncapsulation keeps related data and behavior inside one class.
E
2. It helps protect data from direct unwanted changes.
3. Python does not have strict private variables like Java or C++.
4. Python uses naming conventions to show access level.
5. Encapsulation is commonly handled using:
1. Public attributes
al
2. Protected attributes
3. Private/name-mangled attributes
4. Getter and setter methods
h
5. @property
hc
PYTHON CODE
class BankAccount:
def __init__(self, balance): is
self.__balance = balance
N
def deposit(self, amount):
if amount > 0:
ith
self.__balance += amount
eW
def get_balance(self):
return self.__balance
account = BankAccount(1000)
od
[Link](500)
print(account.get_balance())
C
Output: 1500
Example 1
PYTHON CODE
al
class Student:
def __init__(self):
h
[Link] = "Aman"
self._marks = 85
hc
self.__grade = "A"
student = Student()
print([Link])
is
N
print(student._marks)
Output:Aman
ith
85
Direct access to__gradewill fail:
print(student.__grade)
eW
Important Point
ouble underscore does not make data fully private.
D
od
So technically it can still be accessed, but it should not be used directly.
al
3. Setter can validate data before updating.
4. This protects the object from invalid values.
h
Example 1
hc
PYTHON CODE
class Student:
def __init__(self, marks): is
self.__marks = marks
N
def get_marks(self):
ith
return self.__marks
student = Student(80)
student.set_marks(90)
print(student.get_marks())
C
Output: 90
Encapsulation Using@property
@propertyallows a method to behave like an attribute.
Syntax
.
1 propertyis a clean way to control access to data.
@
2. It allows validation before changing data.
al
3. It supports getter and setter behavior.
4. It makes code look simple while still protecting data.
h
Example 1
hc
PYTHON CODE
class Student:
def __init__(self, marks):
[Link] = marks
is
N
@property
ith
def marks(self):
return self._marks
eW
@[Link]
def marks(self, value):
if value < 0:
r aise ValueError("Marks cannot be
od
negative")
self._marks = value
C
student = Student(85)
[Link] = 95
print([Link])
Output: 95
14.2.2 Inheritance
Inheritance allows one class to reuse the properties and methods of another class.
Syntax
al
Explanation
h
.
1 Inheritance supports code reuse.
2. The parent class is also called base class or superclass.
hc
3. The child class is also called derived class or subclass.
4. The child class can use parent class attributes and methods.
5. The child class can also define its own attributes and methods.
6. The child class can override parent methods.
is
7. Inheritance represents anis-arelationship.
N
Basic Example
ith
PYTHON CODE
class Animal:
def eat(self):
eW
print("Eating")
class Dog(Animal):
def bark(self):
od
print("Barking")
dog = Dog()
[Link]()
C
[Link]()
Output: Eating
Barking
Inheritance Flow
Parent class
|
v
Child class
|
v
Child class can reuse parent features
Use Meaning
al
Code reuse Child class reuses parent code
h
Extensibility Child class can add new features
hc
Maintainability Common logic stays in parent class
Student is a Person
Multilevel inheritance Child inherits from parent, and another child inherits from that child
Single Inheritance
Single inheritance means one child class inherits from one parent class.
Syntax
Example 1
al
PYTHON CODE
class Animal:
h
def eat(self):
hc
print("Eating")
class Dog(Animal):
def bark(self):
print("Barking")
is
N
dog = Dog()
ith
[Link]()
[Link]()
eW
Output:Eating
Barking
od
C
Multilevel Inheritance
Multilevel inheritance means a class inherits from a child class, forming a chain.
Syntax
al
Example 1
h
PYTHON CODE
class Animal:
hc
def eat(self):
print("Eating")
class Dog(Animal):
is
N
def bark(self):
print("Barking")
ith
class Puppy(Dog):
def weep(self):
eW
print("Weeping")
puppy = Puppy()
[Link]()
od
[Link]()
[Link]()
C
utput:
O
Eating
Barking
Weeping
Hierarchical Inheritance
Hierarchical inheritance means multiple child classes inherit from one parent class.
Syntax
al
Example 1
PYTHON CODE
class Animal:
h
def eat(self):
print("Eating")
hc
class Dog(Animal):
def bark(self):
print("Barking") is
class Cat(Animal):
N
def meow(self):
print("Meowing")
ith
og = Dog()
d
cat = Cat()
[Link]()
eW
[Link]()
[Link]()
[Link]()
Output: Eating
Barking
od
Eating
Meowing
Diagram
C
Animal
/ \
v v
Dog Cat
Multiple Inheritance
Multiple inheritance means one child class inherits from more than one parent class.
Syntax
PYTHON CODE
class Parent1:
pass
class Parent2:
pass
al
.
1 ython supports multiple inheritance.
P
2. A child class can use methods from multiple parent classes.
3. If parents have methods with the same name, Python uses MRO.
h
4. MRO means Method Resolution Order.
hc
Example 1
PYTHON CODE
class Father:
def father_skill(self):
is
print("Gardening")
N
class Mother:
ith
def mother_skill(self):
print("Painting")
eW
child = Child()
od
hild.father_skill()
c
child.mother_skill()
C
child.child_skill()
utput:
O
Gardening
Painting
Coding
Diagram
Father Mother
\ /
v v
Child
Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance.
.
1 ybrid inheritance mixes different inheritance types.
H
2. It can include multiple, multilevel, or hierarchical inheritance together.
3. It is powerful but can become complex.
4. MRO is important in hybrid inheritance.
al
Example 1
h
PYTHON CODE
class Person:
hc
def show_person(self):
print("Person")
class Student(Person):
def show_student(self):
print("Student")
is
N
class Employee(Person):
ith
def show_employee(self):
print("Employee")
def show_ta(self):
print("Teaching Assistant")
ta = TeachingAssistant()
ta.show_person()
od
ta.show_student()
ta.show_employee()
ta.show_ta()
Output:
C
Person
Student
Employee
Teaching Assistant
Diagram
Person
/ \
v v
Student Employee
\ /
v v
TeachingAssistant
h al
hc
14.17 Method Resolution Order - MRO
is
MRO is the order Python follows while searching for methods in inheritance.
N
Syntax
ith
eW
OR
.
1 RO decides which method is called first.
M
od
Example 1
PYTHON CODE
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
class C(A):
def show(self):
al
print("C")
h
class D(B, C):
pass
hc
obj = D()
[Link]()
print([Link]())
is
N
Output: B
ith
MRO Flow
D -> B -> C -> A -> object
SinceBcomes beforeC,[Link]()runs.
od
C
Diamond Problem
he diamond problem happens when a child class inherits from two classes that both inherit
T
from the same parent.
.
1 lassBand classCboth inherit fromA.
C
al
2. ClassDinherits from bothBandC.
3. If the same method exists in multiple classes, Python uses MRO to decide.
4. Python handles this safely using MRO.
h
5. super()also follows MRO.
hc
Example 1
PYTHON CODE
class A:
def show(self):
is
N
print("A")
class B(A):
ith
def show(self):
print("B")
eW
class C(A):
def show(self):
print("C")
pass
d = D()
[Link]()
C
utput:B
O
Because the MRO is:
D -> B -> C -> A -> object
Constructor in Inheritance
hen a child object is created, Python runs the child class__init__method.
W
If the child class does not have__init__, Pythonuses the parent class__init__.
al
class Student(Person):
pass
h
student = Student("Aman")
hc
print([Link])
Output: Aman is
The child class uses the parent class constructor.
N
Case 2: Child Has Its Own__init__
ith
PYTHON CODE
class Person:
def __init__(self, name):
eW
[Link] = name
class Student(Person):
od
student = Student("Python")
print([Link])
Output:
Python
Here, parent__init__does not run automatically becausethe child has its own__init__.
super()
super()is used to call the next method in the MRO,usually from the parent class.
Syntax
super().method_name()
Explanation
al
.
1 uper()is commonly used to call parent class methods.
s
2. It is commonly used inside__init__.
h
3. It avoids directly writing the parent class name.
4. In multiple inheritance,super()follows MRO.
hc
5. It helps avoid repeating parent class logic.
Example 1 is
PYTHON CODE
class Person:
N
def __init__(self, name):
[Link] = name
ith
class Student(Person):
eW
print([Link])
C
print([Link])
Output:
Aman
Python
14.2.3 Method Overriding
ethod overriding means a child class defines a method with the same name as a parent
M
class method.
Syntax
h al
hc
Explanation
is
N
.
1 he method name is the same in parent and child.
T
2. The child class provides its own version.
ith
Example 1
PYTHON CODE
class Animal:
od
def sound(self):
print("Animal sound")
C
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog()
[Link]()
Output:Bark
Overriding withsuper()
PYTHON CODE
class Animal:
def sound(self):
print("Animal sound"
class Dog(Animal):
def sound(self):
super().sound()
print("Bark")
al
dog = Dog()
[Link]()
h
Output: Animal sound
Bark
hc
14.2.4 Polymorphism
is
Polymorphism means the same method or operation behaves differently for different objects.
Explanation
N
. P
1 olymorphism means “many forms”.
2. The same method name can work differently in different classes.
ith
print("Bark")
class Cat:
C
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
[Link]()
Output: Bark
Meow
Polymorphism Types in Python
Type Meaning Example
14.2.5 Duck Typing
al
Duck typing means Python focuses on what an object can do, not its exact type.
h
hc
Basic Idea
If an object has the needed method, Python can use it.
Example 1
is
N
PYTHON CODE
class Duck:
ith
def speak(self):
print("Quack")
eW
class Person:
def speak(self):
print("Hello")
od
def call_speak(obj):
[Link]()
C
call_speak(Duck())
call_speak(Person())
utput:
O
Quack
Hello
ython does not care whether the object isDuckorPerson. It only checks whetherspeak()
P
exists.
14.2.6 Abstraction
Abstraction means hiding internal implementation and showing only essential features.
Explanation
.
1 bstraction focuses on what an object does.
A
2. It hides how the object does it internally.
3. Python supports abstraction using abstract base classes.
4. Abstract base classes are created using theabcmodule.
5. A class with abstract methods cannot be instantiated directly.
al
6. Child classes must implement abstract methods.
h
Example 1
hc
PYTHON CODE
from abc import ABC, abstractmethod
class Payment(ABC):
is
@abstractmethod
N
def pay(self, amount):
ith
pass
class UpiPayment(Payment):
eW
payment = UpiPayment()
od
[Link](500)
C
Important Point
Payment cannot be used directly because it has an abstract method.
This gives an error:
payment = Payment()
Output:
TypeError: Can't instantiate abstract class Payment with abstract method pay
Encapsulation vs Abstraction
Point Encapsulation Abstraction
Abstraction = How unnecessary details are hidden
al
14.2.7 Composition
h
hc
Composition means one class contains an object of another class.
Basic Idea
Inheritance = is-a relationship is
Composition = has-a relationship
N
. C
1 omposition is used when one object is made of another object.
2. It represents ahas-arelationship.
3. It is often preferred over inheritance when there is no true is-a relationship.
ith
Example 1
eW
PYTHON CODE
class Engine:
def start(self):
print("Engine started")
od
class Car:
def __init__(self):
[Link] = Engine()
C
def start(self):
[Link]()
car = Car()
[Link]()
utput:Engine started
O
Explanation:
Car has an Engine.
So this is composition.
Association, Aggregation, & Composition
Relationship Meaning Example
Important Difference
al
Point Aggregation Composition
h
Child object can exist alone? Yes Usually no
hc
Example Team has Players Car has Engine
isinstance()andissubclass() is
These functions are useful when working with inheritance.
N
Syntax
isinstance(object, ClassName)
ith
issubclass(ChildClass, ParentClass)
.
1 isinstance()checks whether an object belongs to aclass.
eW
Example 1
od
PYTHON CODE
class Animal:
pass
C
class Dog(Animal):
pass
og = Dog()
d
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(issubclass(Dog, Animal))
Output: True
True
True
Inheritance vs Composition
Point Inheritance Composition
Code style Child class extends parent Class contains another object
euse
R Inherit methods se contained object
U
method methods
al
Flexibility an become tightly
C Usually more flexible
connected
h
Use Inheritance When
hc
Child really is a type of parent.
Example:Dog is an Animal
Student is a Person
Composition Build one object using another Object inside object
h al
Important OOP Scenario Table
hc
Scenario Use
S
● pecial methods
● Magic methods
● Dunder methods
dundermeansdouble underscore.
Syntax
h al
hc
Explanation is
.
1 pecial methods allow objects to work with Python’s built-in operations.
S
N
2. They are called automatically by Python.
3. They usually start and end with double underscores.
4. We normally do not call them directly.
ith
Example Idea
eW
al
__add__ obj1 + obj2 Addition
h
__call__ obj() Makes object callable
hc
__enter__ with obj: Starts context manager
Syntax
eW
od
C
Explanation
.
1 _str__is called bystr(obj).
_
2. It is also called byprint(obj).
3. It should return a string.
4. It is mainly for users.
5. It should be readable and simple.
Example 1
PYTHON CODE
class Student:
def __init__(self, name, course):
[Link] = name
[Link] = course
def __str__(self):
return f"{[Link]} is studying {[Link]}"
al
Output:Aman is studying Python
14.3.2__repr__
h
hc
__repr__returns a developer-friendly string representationof an object.
Syntax is
N
ith
. _
1 _repr__is called byrepr(obj). It is mainly usedfor debugging.
eW
2. It should return a string. A good__repr__often lookslike valid Python code.
3. If__str__is not defined, Python may use__repr__while printing.
PYTHON CODE
class Student:
od
def __repr__(self):
return f"Student(name={[Link]!r}, course={[Link]!r})"
student = Student("Aman", "Python")
print(repr(student))
Output:Student(name='Aman', course='Python')
14.3.3__len__
__len__defines the behavior oflen(obj).
Syntax
al
Explanation
h
.
1 _len__is called bylen(obj).
_
hc
2. It must return a non-negative integer.
3. It is useful for custom container-like classes.
4. If__bool__is not defined, Python may use__len__to decide truthiness.
5. If__len__returns0, the object is consideredFalsein Boolean context.
is
Example 1
N
PYTHON CODE
ith
class Team:
def __init__(self, members):
[Link] = members
eW
def __len__(self):
return len([Link])
od
Output:3
14.3.4__getitem__
__getitem__defines indexing and slicing behavior.
Syntax
def __getitem__(self, index):
return value
.
1 _getitem__is called when we useobj[index].
_
2. It allows custom objects to support indexing.
3. It can also support slicing. It is useful for custom sequence-like classes.
4. If implemented carefully, it can also help an object work in loops.
PYTHON CODE
class Team:
al
def __init__(self, members):
[Link] = members
h
hc
def __getitem__(self, index):
return [Link][index]
team = Team(["Aman", "Riya", "Kabir"])
print(team[0])
print(team[1])
is
N
print(team[0:2])
utput:
O
ith
Aman
Riya
['Aman', 'Riya']
eW
14.3.5__add__
od
Syntax
C
.
1 _add__is called whenobj1 + obj2is used.
_
2. It is used for operator overloading.
3. It should return a new result.
4. If the other object type is not supported, returnNotImplemented.
5. It should be used only when addition makes logical sense.
Example 1
PYTHON CODE
class Money:
def __init__(self, amount):
[Link] = amount
al
def __str__(self):
return f"Amount: {[Link]}"
h
hc
money1 = Money(100)
money2 = Money(50)
result = money1 + money2 is
print(result)
N
ith
14.3.6__sub__
__sub__defines custom behavior for the-operator.
od
Syntax
def __sub__(self, other):
C
return result
.
1 _sub__is called whenobj1 - obj2is used.
_
2. It is also part of operator overloading.
3. It should return a meaningful result.
4. ReturnNotImplementedif the other type is unsupported.
Example 1
PYTHON CODE
class Money:
def __init__(self, amount):
[Link] = amount
al
def __str__(self):
return f"Amount: {[Link]}"
h
hc
money1 = Money(100)
money2 = Money(40)
result = money1 - money2 is
print(result)
N
Output: Amount: 60
ith
14.3.7__call__
eW
Syntax
od
def __call__(self):
C
statement
Explanation
.
1 _call__runs when an object is called using parentheses.
_
2. It makes an object callable.
3. It is useful when an object stores data and also performs an action.
4. It is commonly used in decorators, callbacks, and callable classes.
Example 1
PYTHON CODE
class Greeter:
def __init__(self, name):
[Link] = name
def __call__(self):
print("Hello", [Link])
al
greet_aman = Greeter("Aman")
greet_aman()
h
Output: Hello Aman
hc
14.3.8__enter__and__exit__ is
_enter__and__exit__are used to create context[Link] managers work with
_
N
thewithstatement.
ith
Syntax
PYTHON CODE
eW
def __enter__(self):
return self
statement
C
Explanation
.
1 _enter__runs at the start of thewithblock.
_
2. __exit__runs when thewithblock ends.
3. __exit__runs even if an error occurs inside thewithblock.
4. __exit__receives exception details if an error occurs.
5. If__exit__returnsTrue, the exception is suppressed.
6. If__exit__returnsFalseorNone, the exception continues.
PYTHON CODE
class SimpleContext:
def __enter__(self):
print("Entering")
return self
al
with SimpleContext():
print("Inside with block")
h
utput:
O
hc
Entering
Inside with block
Exiting
is
14.3.9 Context Manager Real Use
N
ith
Example 1
eW
od
C
Explanation
.
1 pen()returns a file object.
o
2. The file object works as a context manager.
3. The file opens at the start of thewithblock.
4. The file closes automatically at the end.
5. This is safer than manually closing the file.
14.3.10 Operator Overloading
Operator overloading means giving custom behavior to operators for user-defined classes.
Explanation
.
1 perators like+,-,*,==,<, and[]can be customized.
O
2. This is done using special methods.
3. Operator overloading should be logical.
4. Do not overload operators in a confusing way.
5. Operators internally call matching dunder methods.
al
Operator Overloading Table
h
Operator / Operation Special Example
hc
ethod
M
+ __add__ obj1 + obj2
-
*
__sub__
__mul__
is obj1 - obj2
obj1 * obj2
N
/ __truediv__ obj1 / obj2
ith
Syntax
h al
Explanation
hc
.
1 _eq__defines equality using==.
_
2. __lt__defines less than using<.
3. Other comparison methods work similarly.
is
4. These methods should returnTrueorFalse.
5. ReturnNotImplementedif comparison with the othertype is unsupported.
N
Example 1
ith
PYTHON CODE
class Student:
eW
Output: True
Here, two students are considered equal because their marks are equal.
Comparison Methods Table
Method Operator
__eq__ ==
__ne__ !=
__lt__ <
__le__ <=
al
__gt__ >
__ge__ >=
h
hc
14.3.12 Reverse and In-place Operator Methods
is
Python also supports reverse and in-place operator methods.
Explanation
N
. R
1 everse methods are used when the left object does not support the operation.
ith
Table
Type Example Operator Method
Syntax
h al
Explanation
hc
.
1 _bool__is called bybool(obj).
_
2. It is also used inif obj:conditions.
3.
4.
It must returnTrueorFalse.
is
If__bool__is not defined, Python may use__len__.
5. If both are missing, most objects are consideredTrue.
N
Example 1
ith
PYTHON CODE
class Cart:
eW
def __bool__(self):
od
cart = Cart(["Book"])
C
if cart:
print("Cart has items")
def __next__(self):
al
return next_value
h
. _
1 _iter__returns an iterator object.__next__returnsthe next value.
2. When no value is left,__next__should raiseStopIteration.
hc
3. These methods are used by loops. They are part of the iterator protocol.
PYTHON CODE
class CountUpTo:
def __init__(self, limit):
is
N
[Link] = 1
[Link] = limit
ith
def __iter__(self):
return self
eW
def __next__(self):
if [Link] > [Link]:
raise StopIteration
od
value = [Link]
C
[Link] += 1
return value
counter = CountUpTo(3)
for number in counter:
print(number)
utput:
O
1
2
3
14.3.15__contains__
__contains__defines behavior for theinoperator.
Syntax
return True_or_False
al
Explanation
h
. _
1 _contains__is called byitem in obj.
2. It should returnTrueorFalse.
hc
3. It is useful for custom container-like classes.
Example 1 is
PYTHON CODE
N
class Team:
def __init__(self, members):
ith
[Link] = members
print("Aman" in team)
print("Neha" in team)
C
Output:
True
False
Important Rules for Special Methods
Rule Explanation
al
Do not call directly Uselen(obj), notobj.__len__()
h
hc
Method Meaning Common Use
__repr__
__len__
Developer-friendly string
Defines length
is repr(obj)
len(obj)
N
__getitem__ Defines indexing obj[index]
ith
.
1 classmethod
@
2. @staticmethod
3. @property
4. Abstract base classes
5. Mixins
al
6. Metaclasses
7. Data classes
h
hc
15.1@classmethod
is
Aclass methodis a method that receives the classas its first argument.
class ClassName:
@classmethod
eW
def method_name(cls):
statement
Explanation
od
.
1 classmethodis used to create a class method.
@
2. A class method receives the class automatically ascls.
3. It can access class variables.
C
Example 1
PYTHON CODE
class Student:
school_name = "ABC School"
@classmethod
def change_school(cls, new_school):
cls.school_name = new_school
al
Student.change_school("XYZ School")
h
hc
student1 = Student("Aman")
print(student1.school_name) is
print(Student.school_name)
N
Output:
ith
XYZ School
XYZ School
eW
Important Points
Point Explanation
od
Receives Class
C
Syntax
h al
.
1 class normally creates objects using__init__.
A
2. Sometimes data comes in a different format.
hc
3. A class method can convert that data and return an object.
4. cls(...)creates an object of the current class.
5. This is useful for flexible object creation.
Example 1
is
N
PYTHON CODE
class Student:
ith
classmethod
@
def from_string(cls, data):
name, age = [Link]("-")
return cls(name, int(age))
od
tudent = Student.from_string("Aman-21")
s
print([Link])
C
print([Link])
Output:Aman
21
15.3@staticmethod
Astatic methodis a method inside a class that doesnot receiveselforcls.
Syntax
class ClassName:
@staticmethod
def method_name():
statement
al
.
1 staticmethodcreates a static method.
@
2. It does not receive the object asself.
3. It does not receive the class ascls.
h
4. It behaves like a normal function placed inside a class.
hc
5. It is used when the method is logically related to the class but does not need object
or class data.
Example 1 is
PYTHON CODE
N
class MathHelper:
@staticmethod
ith
Output: 30
Important Points
od
Point Explanation
Access instance data Yes No direct access No
al
Access class data Yes Yes No direct access
h
Common use Object behavior Class-level behavior Helper logic
hc
Call style [Link]() [Link]() [Link]()
15.5@property
is
N
@propertyallows a method to be accessed like an attribute.
ith
Syntax
class ClassName:
eW
@property
def attribute_name(self):
return value
Explanation
od
.
1 propertyis used to create managed attributes.
@
2. It allows method logic to run when accessing an attribute.
C
@property
def marks(self):
return self._marks
al
student = Student(85)
h
print([Link])
hc
Output: 85
Important point: is
[Link] looks like an attribute, but internally it calls the marks() method.
N
15.6@propertySetter
ith
Syntax
property
@
def name(self):
return self._name
od
[Link]
@
def name(self, value):
C
self._name = value
Explanation
.
1 getter returns the value.
A
2. A setter updates the value.
3. The setter can validate the value before saving it.
4. This protects objects from invalid data.
5. The property name and setter name must match.
Example 1
PYTHON CODE
class Student:
def __init__(self, marks):
[Link] = marks
@property
def marks(self):
return self._marks
al
@[Link]
h
def marks(self, value):
if value < 0:
hc
raise ValueError("Marks cannot be
negative")
self._marks = value is
N
student = Student(80)
[Link] = 95
ith
print([Link])
Output: 95
eW
Syntax
@property
def property_name(self):
return value
al
Explanation
h
. If no setter is defined, the property cannot be assigned directly.
1
hc
2. This is useful for calculated values.
3. It protects values from direct modification.
PYTHON CODE
class Rectangle:
is
N
def __init__(self, length, width):
[Link] = length
ith
[Link] = width
@property
eW
def area(self):
return [Link] * [Link]
print([Link])
C
Output:
50
Invalid update:
[Link] = 100
Output:
al
.
1 bstract base classes are created usingABC.
A
2. Abstract methods are created using@abstractmethod.
h
3. A class with abstract methods cannot be instantiated directly.
hc
4. Child classes must implement all abstract methods.
5. Abstract base classes are useful when many classes should follow the same
structure.
Abstract class
|
v
is
N
Defines required method
|
v
ith
PYTHON CODE
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
od
def area(self):
pass
class Square(Shape):
C
def area(self):
return [Link] * [Link]
square = Square(5)
print([Link]())
Output: 25
15.9Why Abstract Base Classes Are Used
bstract base classes are used when we want to force child classes to implement required
A
methods.
Benefit Explanation
al
Common structure All child classes follow same design
h
Prevents incomplete classes Child must implement abstract methods
hc
Improves readability Required methods are clear
15.10 Mixins
eW
Syntax
class MixinName:
od
def method_name(self):
statement
class MainClass(MixinName):
C
pass
.
1 mixin is used to add extra features.
A
2. A mixin is usually not meant to be used alone.
3. Mixins are commonly used with multiple inheritance.
4. A mixin should be small and focused.
5. Mixin class names often end withMixin.
Example 1
PYTHON CODE
class JsonMixin:
def to_json(self):
return self.__dict__
class Student(JsonMixin):
def __init__(self, name, age):
[Link] = name
[Link] = age
student = Student("Aman", 21)
al
print(student.to_json())
h
Output: {'name': 'Aman', 'age': 21}
hc
Important Points
Point Explanation
is
Purpose Add reusable behavior
N
Usually used alone? No
ith
.
1 In Python, classes are also objects.
2. The default metaclass in Python istype.
3. A metaclass controls how a class is created.
4. Metaclasses are advanced.
5. Most normal Python programs do not need custom metaclasses.
al
6. For Core Python, understanding the basic idea is enough.
h
hc
is
N
Output: <class '__main__.Student'>
ith
<class 'type'>
Code Meaning
eW
Syntax
PYTHON CODE
from dataclasses import dataclass
@dataclass
class ClassName:
field_name: type
Explanation
.
1 ata classes are created using@dataclass.
D
2. They are useful for classes that mainly store data.
3. Fields are declared using type annotations.
4. Python automatically creates__init__.
5. Python automatically creates useful__repr__.
6. Data classes were introduced in Python 3.7.
Example 1
al
PYTHON CODE
from dataclasses import dataclass
h
@dataclass
hc
class Student:
name: str
age: int is
course: str
N
student = Student("Aman", 21, "Python")
print(student)
ith
Comparison Table
od
. F
1 ields can have default values.
al
2. Fields without default values must come before fields with default values.
3. This rule is similar to function parameters.
h
15.16 Mutable Defaults in Data Classes
hc
Do not directly use mutable default values like lists in data classes.
Wrong Style is
N
ith
eW
Output: ['Python']
[]
1. Mutable defaults can accidentally be shared.
2. default_factory=listcreates a new list for each object.
3. This avoids shared mutable data problems.
15.17 Frozen Data Classes
A frozen data class creates objects that cannot be modified after creation.
Syntax
h al
Explanation
hc
. frozen=Truemakes data class objects immutable-like.
1
2. After object creation, fields cannot be reassigned normally. It is useful for fixed data.
3. It is similar in idea to immutability, but internal mutable fields can still be modified if
is
they exist.
N
Example 1
ith
PYTHON CODE
from dataclasses import dataclass
eW
@dataclass(frozen=True)
class Point:
x: int
y: int
od
utput:
O
Point(x=10, y=20)
Invalid update:
point.x = 50
Output: [Link]: cannot assign to field 'x'
Chapter 16. File Handling and Error Management
This chapter has three main parts:
. F
1 ile Operations
2. Exception Handling
3. File Formats
al
16.1 File Operations
h
16.1.1 File Handling
hc
File handling means working with files using Python.
Python can:
.
1
2.
pen files
O
Read files
is
N
3. Write files
4. Append data
ith
Syntax
od
Explanation
1. open()opens a file.
.
2 he first argument is the file name or path.
T
3. The second argument is the file mode.
4. Encoding is commonly used for text files.
5. utf-8is a common and recommended encoding.
Example 1
file = open("[Link]", "r", encoding="utf-8")
This opens[Link]in read mode.
1. C losing a file releases system resources. If a file is not closed, data may not be
al
saved properly.
2. Thewithstatement is preferred because it closesthe file automatically.
h
Example 1
hc
file = open("[Link]", "r", encoding="utf-8")
[Link]()
Method Meaning
Example 1
file = open("[Link]", "r", encoding="utf-8")
C
content = [Link]()
print(content)
[Link]()
Output:Hello Python
Welcome to file handling
16.1.5 Reading Line by Line
Reading line by line is useful for large files.
Syntax
for line in file:
statement
. T
1 his reads one line at a time.
2. It is memory-friendly.
al
3. It is better than reading a very large file at once.
Example 1
h
with open("[Link]", "r", encoding="utf-8") as file:
hc
for line in file:
print([Link]())
Syntax
od
open("file_name", "w")
. " w"means write [Link] the file does not exist, Pythoncreates it.
1
2. If the file already exists, old content is removed.
C
Example 1
with open("[Link]", "w", encoding="utf-8") as file:
[Link]("Hello Python")
Syntax
open("file_name", "a")
Explanation
al
. " a"means append mode. New data is added at the end.
1
2. Old content is not removed. If the file does not exist, Python creates it.
h
Example 1
hc
with open("[Link]", "a", encoding="utf-8") as file:
[Link]("\nNew line added")
is
16.1.8 File Modes
N
ith
al
"wb" Write binary file
h
"w+" Write and read, overwrites file
hc
"a+" Append and read
is
Important point:Default mode is "rt", which meansread text.
N
16.1.9withStatement
ith
Syntax
eW
. w
1 ithautomatically closes the file. It is safer thanmanually usingclose().
od
2. It works even if an error happens inside the block. It makes file handling cleaner.
Example 1
C
[Link]()
16.1.10 File Object Methods
Method Meaning
al
readlines() Reads all lines into a list
h
writelines(list) Writes multiple strings
hc
seek(position) Moves file pointer
● Images
● Videos
od
Syntax
pen("file_name", "rb")
o
open("file_name", "wb")
Explanation
. " rb"means read binary."wb"means write binary.
1
2. Binary mode works with bytes, not normal strings.
3. Encoding is not used in binary [Link] files are useful for non-text data.
16.1.12 File Paths
Type Meaning Example
Parent folder path File in parent folder "../[Link]"
al
16.1.13 BasicosModule
h
hc
Theosmodule helps work with the operating system.
Syntax is
N
import os
ith
CommonosFunctions
Function Meaning
eW
16.1.14 BasicpathlibModule
pathlibis a modern way to work with file paths.
Syntax
from pathlib import Path
. p
1 athlibworks with paths as [Link] is cleanerthan manually joining strings.
2. It is recommended for modern Python [Link] works across operating systems.
CommonpathlibMethods
Code Meaning
al
Path("[Link]") Creates path object
h
[Link]() Checks if path exists
path.is_file() Checks if path is file
hc
path.is_dir() Checks if path is folder
path.read_text() Reads text file
path.write_text()
[Link]()
Writes text file
Creates folder
is
N
[Link]() Deletes file
16.1.15 Encoding
ith
.
1 ext files store text using an encoding.
T
2. utf-8supports most common characters.
3. Always mention encoding when working with text files.
od
Example 1
C
.
1 o prevent sudden program crashes.
T
al
2. To handle risky code safely.
3. To clean up resources properly.
4. To continue program execution when possible.
h
hc
16.2.1try-except
try-exceptis used to handle exceptions. is
Syntax
N
try:
ith
risky_code
except ExceptionType:
handling_code
eW
.
1 ode that may cause an error is written insidetry.
C
2. Error handling code is written insideexcept.
3. If an exception occurs, Python jumps to the matchingexceptblock.
4. If no exception occurs, theexceptblock is skipped.
od
Flow Chart
try block runs
|
C
v
Error occurs?
|
├── Yes -> except block runs
|
└── No -> except block skipped
Example 1
PYTHON CODE
try:
number = int("abc")
except ValueError:
print("Invalid number")
Output:Invalid number
We can store the exception object usingas.
al
Syntax
h
except ExceptionType as error:
statement
hc
Example 1
PYTHON CODE
try:
is
number = int("abc")
N
except ValueError as error:
print(error)
ith
16.2.3 MultipleexceptBlocks
od
PYTHON CODE
try:
risky_code
except ErrorType1:
handling_code
except ErrorType2:
handling_code
Explanation
.
1 ifferent exceptions can need different handling.
D
2. Specific exceptions should come before general exceptions.
3. Python runs only the first matchingexceptblock.
4. Exceptionshould usually come last.
Example 1
PYTHON CODE
try:
al
umbers = [10, 20, 30]
n
print(numbers[5])
h
except IndexError:
print("Invalid index")
hc
except ValueError:
print("Invalid value")
except Exception:
print("Some other error occurred") is
N
Output:Invalid index
ith
Syntax
PYTHON CODE
od
Example 1
C
PYTHON CODE
try:
value = int("abc")
except (ValueError, TypeError):
print("Invalid conversion")
Output:Invalid conversion
16.2.5elsein Exception Handling
Theelseblock runs only when no exception occurs.
Syntax
PYTHON CODE
try:
risky_code
except ExceptionType:
handling_code
al
else:
code_if_no_error
h
. e
1 lseruns only if thetryblock has no exception.It is useful for success logic.
hc
2. It keeps error handling separate from normal code.
PYTHON CODE
try: is
number = int("100")
except ValueError:
print("Invalid number")
N
else:
print("Conversion successful:", number)
ith
16.2.6finally
eW
PYTHON CODE
try:
risky_code
except ExceptionType:
C
handling_code
finally:
cleanup_code
Explanation
.
1 finallyruns whether an exception occurs or not.
2. It is used for cleanup operations.
3. It is useful for closing files, network connections, or database connections.
4. With file handling,withis usually cleaner than manually usingfinally.
Example 1
PYTHON CODE
try:
file = open("[Link]", "r", encoding="utf-8")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Finally block executed")
al
utput:Finally block executed
O
The file output depends on whether the file exists.
h
16.2.7try-except-else-finallyFlow
hc
try
| is
v
Error occurs?
N
|
├── Yes -> except -> finally
ith
|
└── No -> else -> finally
Structure
eW
PYTHON CODE
try:
risky_code
except ExceptionType:
od
error_handling
else:
success_code
C
finally:
cleanup_code
Syntax
raise ExceptionType("message")
.
1 r aiseis used to manually trigger an exception.
2. It is useful for validation.
3. It stops normal flow and sends control to exception handling.
4. We can raise built-in or custom exceptions.
Example 1
PYTHON CODE
ge = -5
a
if age < 0:
raise ValueError("Age cannot be negative")
al
Output: ValueError: Age cannot be negative
h
16.2.9 Re-raising Exceptions
hc
Re-raising means raising the same exception again after catching it.
Syntax
is
N
raise
. P
1 lainraiseis used inside anexceptblock.
ith
Example 1
PYTHON CODE
try:
number = int("abc")
od
except ValueError:
print("Logging error")
raise
C
utput:Logging error
O
ValueError: invalid literal for int() with base 10: 'abc'
16.2.10 Custom Exceptions
A custom exception is a user-defined exception class.
Syntax
PYTHON CODE
class CustomError(Exception):
pass
al
Explanation
h
.
1 ustom exceptions are created by inheriting fromException.
C
2. They make errors more meaningful.
hc
3. They are useful in larger projects.
4. Custom exception names usually end withError.
Example 1
PYTHON CODE
is
N
class InsufficientBalanceError(Exception):
pass
ith
alance = 500
b
withdraw_amount = 1000
eW
|
v
Exception
|
├── ArithmeticError
├── LookupError
├── OSError
├── RuntimeError
├── ValueError
└── TypeError
Exception When It Happens
al
ImportError Import fails
ModuleNotFoundError Module not found
h
PermissionError No permission for file operation
UnicodeDecodeError Text decoding fails
hc
16.2.12 BareexceptWarning
is
A bareexceptcatches almost everything and shouldusually be avoided.
Bad Style
N
PYTHON CODE
try:
number = int("abc")
ith
except:
print("Error")
Better Style
eW
PYTHON CODE
try:
number = int("abc")
except ValueError:
od
print("Invalid number")
Problem Explanation
Can catch system-exit style errors Not safe for normal use
16.2.13File Handling with Exception Handling
Error Meaning
al
OSError General operating system error
h
Example 1
hc
PYTHON CODE
try:
with open("[Link]", "r", encoding="utf-8")
as file:
content = [Link]()
except FileNotFoundError:
is
N
print("File not found")
else:
ith
print(content)
Examples:
od
● .txt
● .log
● .md
C
● .csv
● .json
● .xml
Explanation
.
1 ext files store characters.
T
2. Text files should be opened with encoding.
3. Common modes are"r","w", and"a".
4. Text mode is default in Python.
16.3.2 CSV Files
CSV meansComma-Separated Values. CSV files store table-like data.
Example CSV Data
ame,age,course
n
Aman,21,Python
. C
1 SV files store rows and columns. Values are commonly separated by commas.
2. Python provides the built-incsvmodule. CSV is commonlyused for spreadsheets
and data export. Usenewline=""when opening CSV files for writing.
al
Reading CSV File
PYTHON CODE
h
import csv
hc
ith open("[Link]", "r",
w
encoding="utf-8") as file:
reader = [Link](file)
16.3.3[Link]vs[Link]
Tool Output Type Best Use
"age": 21,
al
"course": "Python"
}
h
Explanation
hc
. J
1 SON stores data in key-value format. It looks similar to Python dictionaries.
2. Python provides the built-injsonmodule.
3. JSON is very common in web development and APIs. JSON keys must be strings.
is
Python and JSON Conversion
N
Python JSON
ith
dict object
list array
eW
str string
int,float number
od
True true
False false
C
None null
student = {
"name": "Aman",
"age": 21,
"course": "Python"
}
encoding="utf-8") as file:
al
[Link](student, file, indent=4)
h
16.3.5[Link]()vs[Link]()
hc
Function Meaning Input
.
1 ecorators
D
2. Generators and Iterators
3. Context Managers
4. Regular Expressions
al
17.1 Decorators
h
17.1.1 Decorators
hc
decoratoris a function that takes another function and adds extra behavior to it without
A
changing the original function code.
Basic Idea
is
N
Decorator = function that modifies/enhances another function
ith
Syntax
eW
od
This=>
C
Flow Chart
Original function
|
v
Decorator receives function
|
v
al
Wrapper adds extra behavior
|
v
h
Decorated function is returned
hc
17.1.2 Function Decorators
A function decorator is used to add extra behavior to a function.
is
Syntax
N
ith
eW
PYTHON CODE
def my_decorator(func):
def wrapper():
print("Before function")
od
func()
print("After function")
return wrapper
C
my_decorator
@
def greet():
print("Hello")
greet()
Output: Before function
Hello
After function
. m
1 y_decoratorreceivesgreet.wrapperadds extra behavior.
2. greet()now actually callswrapper(). Insidewrapper,the originalgreet()is called.
17.1.3 Decorators with Function Arguments
If the decorated function has arguments, the wrapper should accept*argsand**kwargs.
Syntax
PYTHON CODE
def decorator_name(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
al
Example 1
h
PYTHON CODE
def show_call(func):
hc
def wrapper(*args, **kwargs):
print("Function is being called")
return func(*args, **kwargs)
return wrapper is
show_call
@
N
def add(a, b):
return a + b
ith
print(add(10, 20))
Output: Function is being called
30
eW
17.1.4[Link]
od
Syntax
C
.
1 ecorators replace the original function with a wrapper.
D
2. Because of this, metadata like function name and docstring can be lost.
3. @wraps(func)copies metadata from the original functionto the wrapper.
4. Professional decorators should usually use[Link].
PYTHON CODE
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
al
my_decorator
@
h
def greet():
"""This function greets the user."""
hc
print("Hello")
rint(greet.__name__)
p
print(greet.__doc__) is
Output:greet
N
This function greets the user.
ith
Decorators can also accept their own arguments. This requires one extra outer function.
Syntax
PYTHON CODE
def decorator_with_args(value):
od
def actual_decorator(func):
def wrapper(*args, **kwargs):
statement
C
1. T he outer function receives decorator arguments. The middle function receives the
original function.
2. The inner wrapper runs extra [Link] is useful when decorator behavior needs
customization.
PYTHON CODE
from functools import wraps
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
al
@repeat(3)
h
def greet():
hc
print("Hello")
greet()
Output:Hello
Hello
is
N
Hello
PYTHON CODE
@decorator1
decorator2
@
def function_name():
od
statement
PYTHON CODE
decorator1
@
@decorator2
def greet():
pass
PYTHON CODE
greet = decorator1(decorator2(greet))
17.1.7 Class Decorators
A class decorator modifies or enhances a class.
Syntax
PYTHON CODE
@decorator_name
class ClassName:
statement
al
. A
1 class decorator receives a class as input. It can add or modify class behavior.
2. It returns the modified class. Class decorators are less common than function
h
decorators.
hc
3. They are useful for logging, registration, validation, and configuration.
Iterable Can be looped over list, tuple, string, dictionary, set, range
al
Iterator Gives next value usingnext() object fromiter()
h
Example 1
hc
PYTHON CODE
numbers = [10, 20, 30]
iterator = iter(numbers)
is
N
print(next(iterator))
print(next(iterator))
ith
print(next(iterator))
utput:
O
eW
10
20
30
. _
1 _iter__()
2. __next__()
Syntax
PYTHON CODE
def __iter__(self):
return self
def __next__(self):
return next_value
Explanation
.
1 _iter__()returns an iterator object.
_
2. __next__()returns the next value.
3. When no values are left,__next__()raisesStopIteration.
4. forloops use this protocol internally.
Example 1
PYTHON CODE
class CountUpTo:
al
def __init__(self, limit):
[Link] = 1
h
[Link] = limit
hc
def __iter__(self):
return self
def __next__(self):
is
N
if [Link] > [Link]:
raise StopIteration
ith
value = [Link]
[Link] += 1
eW
return value
counter = CountUpTo(3)
od
utput:
O
1
2
3
17.2.3__iter__
__iter__returns an iterator object.
Syntax
PYTHON CODE
def __iter__(self):
return self
Explanation
.
1 _iter__()is called byiter(object).
_
al
2. It is also used automatically for loops.
3. If the object itself is the iterator, it returnsself.
h
4. If the object is only iterable, it can return a separate iterator object.
hc
Example 1
PYTHON CODE
numbers = [10, 20, 30]
is
N
iterator = iter(numbers)
print(iterator)
ith
17.2.4__next__
__next__returns the next value from an iterator.
od
Syntax
PYTHON CODE
C
def __next__(self):
return value
.
1 _next__()is called bynext(iterator).
_
2. It returns one value at a time.
3. It should raiseStopIterationwhen there are no valuesleft.
4. WithoutStopIteration, the iteration may not stopcorrectly.
Example 1
PYTHON CODE
numbers = iter([10, 20])
print(next(numbers))
print(next(numbers))
print(next(numbers))
utput:
O
10
20
StopIteration
al
The thirdnext()raisesStopIterationbecause no valuesare left.
h
17.2.5 Generator Functions
hc
A generator function is a function that usesyield.
Syntax
is
N
PYTHON CODE
def generator_name():
yield value
ith
Explanation
eW
.
1 generator function returns a generator object.
A
2. It does not run fully at once.
3. It pauses atyield.
4. Whennext()is called again, it continues from whereit paused.
od
Example 1
C
PYTHON CODE
def count_up_to_three:
yield 1
yield 2
yield 3
Correct code:
PYTHON CODE
def count_up_to_three():
yield 1
yield 2
yield 3
counter = count_up_to_three()
print(next(counter))
print(next(counter))
al
print(next(counter))
h
utput:
O
1
hc
2
3
17.2.6yield
is
N
yieldis used to return a value from a generator withoutending the function permanently.
ith
Syntax
yield value
eW
.
1 ieldgives one value at a time. It pauses the function.
y
2. The function state is saved.
3. On the next call, execution continues after the previousyield.
4. When the function finishes, Python raisesStopIteration.
od
returnvsyield
Point return yield
C
Syntax
(expression for item in iterable)
Explanation
al
.
1 enerator expressions look like list comprehensions.
G
2. They use parentheses().
h
3. They produce values lazily.
4. They do not create a full list in memory.
hc
5. They are useful for large data.
Example 1 is
PYTHON CODE
quares = (number * number for number in
s
N
range(1, 5))
print(value)
utput:
O
1
eW
4
9
16
od
17.2.8yield from
yield fromis used to yield values from another iterableor generator.
C
Syntax
yield from iterable
1. y ield fromsimplifies nested loops in generators It passes values from another iterable
directly.
2. It is useful when one generator uses another generator.
3. It makes generator code cleaner.
17.2.9 One-time Consumption of Iterators
Iterators and generators are usually consumed once.
Explanation
. O
1 nce a value is taken from an iterator, it is not repeated.
2. After all values are consumed, the iterator is exhausted.
3. To iterate again, create a new iterator or generator.
al
Example 1
h
values = (x for x in range(3))
print(list(values))
hc
print(list(values))
Output:
[0, 1, 2]
is
N
[]
ith
The second list is empty because the generator was already consumed.
eW
17.2.10itertools
itertoolsis a standard library module for workingwith iterators.
od
Syntax
C
import itertools
Explanation
.
1 itertoolsprovides memory-efficient iterator tools.
2. It is useful for combinations, permutations, counting, grouping, and chaining.
3. Manyitertoolsfunctions return iterators.
4. Results may need to be converted usinglist()fordisplay.
CommonitertoolsTools
Tool Meaning
al
islice() Slices an iterator
h
permutations() All possible arrangements
hc
product() Cartesian product
groupby() is
roups consecutive matching
G
items
N
17.2.11 Memory Efficiency
ith
Generators are memory-efficient because they produce values only when needed.
eW
.
1 ists store all values in memory.
L
2. Generators produce one value at a time.
3. This is called lazy evaluation.
4. Generators are useful for large files, large ranges, and data streams.
od
Example 1
PYTHON CODE
C
utput:
O
0
1
Only needed values are produced.
17.3 Context Managers
A context manager is an object that manages setup and cleanup automatically.
Syntax
with resource as name:
statement
al
.
1 ontext managers are used with thewithstatement.
C
2. They handle setup before the block starts.
h
3. They handle cleanup after the block ends.
hc
4. Cleanup happens even if an error occurs.
5. They are useful for files, database connections, locks, and network connections.
Flow Chart is
with block starts
N
|
v
ith
__enter__ runs
|
v
Block code runs
eW
|
v
__exit__ runs
od
Example 1
PYTHON CODE
ith open("[Link]", "w", encoding="utf-8") as
w
C
file:
[Link]("Hello Python")
Syntax
al
1. _ _enter__()is called when thewithblock starts.It usually prepares or opens a
h
resource.
2. The value returned by__enter__()is stored afteras. It is part of the context manager
hc
protocol.
17.3.2__exit__ is
__exit__runs when thewithblock ends.
N
Syntax
ith
eW
. _
1 _exit__()is called at the end of thewithblock.It is used for cleanup.
2. It receives exception details if an error occurs. If it returnsTrue, the exception is
suppressed.
od
__exit__Parameters
C
Parameter Meaning
traceback):
al
cleanup_code
h
Example 1
hc
PYTHON CODE
class SimpleContext:
def __enter__(self):
print("Entering") is
return self
N
def __exit__(self, exc_type, exc_value,
traceback):
print("Exiting")
ith
with SimpleContext():
print("Inside block")
eW
Output:Entering
Inside block
Exiting
od
17.3.4contextlib
contextlibis a standard library module for creatingand working with context managers.
C
Syntax
from contextlib import contextmanager
. c
1 ontextlibprovides utilities for context managers.
2. It helps create context managers without writing a full class.
3. The most common tool is@contextmanager. It is usefulfor simple setup-cleanup
logic.
17.3.5@contextmanager
@contextmanagerconverts a generator function intoa context manager.
Syntax
from contextlib import contextmanager
contextmanager
@
def manager_name():
setup_code
al
yield value
cleanup_code
h
Explanation
hc
. C
1 ode beforeyieldworks like__enter__. The yieldedvalue is used afteras.
2. Code afteryieldworks like__exit__. Cleanup shouldbe placed infinallyfor safety.
is
3. This is useful for simple context managers.
Basic Idea
Regex = pattern matching for text
Example Uses
al
.
1 alidate email format.
V
2. Extract phone numbers.
h
3. Find dates in text.
4. Replace unwanted characters.
hc
5. Split text using complex patterns.
is
17.4.1reModule
N
Python provides the built-inremodule for regularexpressions.
ith
Syntax
eW
import re
Explanation
.
1 r eis Python’s regular expression module.
od
PYTHON CODE
import re
print([Link]())
al
Output: 21
h
hc
17.4.3 Regex Metacharacters
Metacharacters are special characters with special meaning in regex.
is
Pattern Meaning Example Match
N
. Any character except newline a,1,@
ith
\D Non-digit
\w ord character: letters, digits,
W
al
underscore
h
\s Whitespace
hc
\S Non-whitespace
Syntax
(pattern)
C
Explanation
.
1 arentheses create groups.
P
2. Capturing groups store matched parts.
3. group(0)gives the full match.
4. group(1)gives the first captured group.
5. group(2)gives the second captured group.
17.4.6 Non-capturing Groups
A non-capturing group groups a pattern without storing it.
Syntax
(?:pattern)
Explanation
al
. N
1 on-capturing groups are used for grouping only.
2. They do not create a captured group number.
3. They are useful when we need grouping but do not need to extract that part.
h
hc
17.4.7search()
search()looks for the first match anywhere in thestring.
is
Syntax
N
[Link](pattern, text)
ith
Explanation
eW
. S
1 earches the entire string. Returns the first match object.
2. ReturnsNoneif no match is found.
3. Use.group()to get matched text.
17.4.8match()
od
Syntax
[Link](pattern, text)
Explanation
1. C hecks only from the start of the string. Returns match object if pattern matches at
the beginning.
2. ReturnsNoneif pattern appears later.
17.4.9fullmatch()
fullmatch()checks whether the whole string matchesthe pattern.
Syntax
[Link](pattern, text)
Explanation
al
. It checks the entire string.
1
2. It returns a match only if the full string matches.
3. It is useful for validation.
h
hc
17.4.10findall()
findall()returns all non-overlapping matches as alist.
is
Syntax
N
[Link](pattern, text)
ith
Explanation
eW
.
1 inds all matches.
F
2. Returns a list.
3. If the pattern has capturing groups, it returns captured groups.
4. If no match is found, it returns an empty list.
od
17.4.11finditer()
finditer()returns an iterator of match objects.
C
Syntax
[Link](pattern, text)
Syntax
[Link](pattern, replacement, text)
Explanation
al
. F
1 inds matches using pattern. Replaces them with replacement text.
2. Returns the modified string. Original string is not changed.
h
17.4.13split()
hc
split()splits a string using a regex pattern.
Syntax
is
N
[Link](pattern, text)
. S
1 plits text wherever the pattern matches.
ith
17.4.14[Link]()
[Link]()creates a reusable regex pattern object.
od
Syntax
pattern = [Link](r"pattern")
C
Explanation
.
1 ompiled patterns can be reused.
C
2. This makes code cleaner when using the same pattern many times.
3. It can be useful for repeated matching.
4. Pattern objects have methods likesearch(),findall(),sub(), andsplit()
Chapter 18. Concurrent and Asynchronous Programming
oncurrent programming means handling multiple tasks during the same time period. It does
C
not always mean tasks are running at the exact same instant.
Basic Terms
Term Meaning
al
Concurrency Managing multiple tasks at once
h
Parallelism Running multiple tasks at the same time
hc
I/O-bound task Task waiting for input/output, like file, network, database
Thread
is
Lightweight unit of execution inside a process
18.1 Multithreading
Multithreading means running multiple threads inside the same process.
.
1 thread is a small unit of execution.
A
2. Multiple threads can run inside one process.
3. Threads share the same memory.
4. Threads are useful for I/O-bound tasks.
5. Threads can cause race conditions when shared data is modified.
6. Locks are used to protect shared data.
Flow Chart
al
Main program
|
h
v
Create threads
hc
|
v
Start threads
|
v
Threads run tasks
|
is
N
v
Join threads
|
ith
v
Program continues
eW
18.1.1threadingModule
Thethreadingmodule provides classes and tools forworking with threads.
od
Tool Purpose
Lock Prevents multiple threads from changing shared data at the same time
Explanation
al
.
1 targetis the function that the thread will run.
h
2. start()starts the thread.
3. join()waits for the thread to finish.
hc
4. Withoutjoin(), the main program may continue whilethe thread is still running.
Example 1 is
PYTHON CODE
N
import threading
ith
def show_message():
print("Thread is running")
eW
thread =
[Link](target=show_message)
[Link]()
od
[Link]()
Output:
Thread is running
is_alive() Checks whether thread is still running
al
name Thread name
h
daemon IfTrue, thread stops when main program exits
hc
18.1.4 Race Conditions is
race condition happens when multiple threads access and modify shared data at the same
A
N
time, causing incorrect results.
ith
Explanation
. T
1 hreads share memory.
2. If two threads change the same variable together, the result can become
eW
unpredictable.
3. This problem is called a race condition.
4. Locks are used to avoid race conditions.
od
Example Idea
Thread 1 reads count = 0
C
Expected result: 2
Actual result: 1
18.1.5 Locks
A lock allows only one thread to access a critical section at a time.
Syntax
lock = [Link]()
with lock:
al
shared_data_update
.
1 lock protects shared data.
A
h
2. Only one thread can hold the lock at a time.
3. Other threads must wait.
hc
4. Usewith lock:because it releases the lock automatically.
Example 1 is
PYTHON CODE
N
import threading
ith
count = 0
lock = [Link]()
eW
def increase():
global count
for _ in range(100000):
od
with lock:
count += 1
C
thread1 = [Link](target=increase)
thread2 = [Link](target=increase)
[Link]()
[Link]()
[Link]()
[Link]()
print(count)
Output: 200000
18.1.6 Synchronization
Synchronization means coordinating threads so they work safely together.
Lock Allows one thread at a time
al
RLock Allows same thread to acquire lock multiple times
h
Semaphore Allows limited number of threads
hc
Event One thread signals another thread
Queue
is
Thread-safe data exchange between threads
N
18.2 Multiprocessing
ith
Syntax
import multiprocessing
C
Explanation
.
1 process has its own Python interpreter and memory space.
A
2. Processes do not share normal memory like threads.
3. Multiprocessing is useful for CPU-bound tasks.
4. It can use multiple CPU cores.
5. Communication between processes needs special tools likeQueue,Pipe,Manager,
or shared memory.
Thread vs Process
Point Thread Process
Best for I/O-bound tasks CPU-bound tasks
al
Communication Easier but risky Needs special tools
h
Race condition risk Higher with shared data Lower by default
hc
18.2.1 Managing Processes is
Method / Attribute Meaning
N
start() Starts process
ith
Syntax
from multiprocessing import Pool
1. A pool reuses worker processes. It is useful when many tasks need to be processed.
. It avoids manually creating many process objects.
2
3. For many cases,ProcessPoolExecutoris simpler andmore modern.
.
1 ormal variables are not automatically shared between processes.
N
2. Each process gets its own memory space.
3. To share data, special multiprocessing tools are needed.
4. Shared memory should be used carefully.
al
Memory Sharing Tools
h
Tool Purpose
hc
[Link] end data between
S
processes
[Link]
is
Two-way communication
Syntax
from [Link] import ThreadPoolExecutor
Explanation
1. [Link]is easier than manually creatingthreads/processes.
. It uses executors to manage workers. It returnsFutureobjects.
2
3. AFuturerepresents a result that may not be readyyet.
4. It is useful for running many tasks concurrently.
18.3.1ThreadPoolExecutor
ThreadPoolExecutorruns tasks using a pool of threads. Best for I/O-bound tasks
Example 1
al
PYTHON CODE
from [Link] import
ThreadPoolExecutor
h
hc
def square(number):
return number * number
18.3.2ProcessPoolExecutor
ProcessPoolExecutorruns tasks using a pool of processes.Best for CPU-bound tasks
od
PYTHON CODE
from [Link] import ProcessPoolExecutor
C
def square(number):
return number * number
18.3.3 Futures
AFuturerepresents a task that may complete later.
Method Meaning
al
done() Checks whether task is completed
h
cancelled() Checks whether task was cancelled
hc
exception() Returns exception if task failed
PYTHON CODE
from [Link] import
ThreadPoolExecutor
eW
def square(number):
return number * number
print([Link]())
Output: 25
18.4.1asyncio
asynciois Python’s standard library module for asynchronousprogramming.
Syntax
import asyncio
al
.
1 syncioruns asynchronous tasks.
a
2. It uses an event loop.
h
3. It is usually single-threaded cooperative concurrency.
hc
4. Tasks pause when they reachawait.
5. While one task is waiting, another task can run.
Flow Chart is
Event loop starts
|
N
v
Task 1 runs
|
ith
v
Task 1 awaits
|
v
eW
Task 2 runs
|
v
Tasks complete
od
18.4.2asyncand Coroutines
A coroutine is created usingasync def.
C
Syntax
async def function_name():
statement
Explanation
. a
1 sync defdefines a coroutine function.
2. Calling a coroutine function returns a coroutine object.
. T
3 he coroutine does not run immediately just because it is called.
4. It must be awaited or run by the event loop.
5. [Link]()is commonly used to start the main coroutine.
Example 1
PYTHON CODE
import asyncio
print("Hello async")
al
[Link](greet())
h
hc
Output: Hello async
18.4.3await is
N
awaitpauses a coroutine until an awaitable finishes.
Syntax
ith
await awaitable
eW
Explanation
. a
1 waitcan be used only insideasync def. It pausesthe current coroutine.
2. It allows the event loop to run other tasks.
od
Example 1
C
PYTHON CODE
import asyncio
End
. T
1 he event loop schedules coroutines. It switches between tasks when they await.
2. [Link]()creates and manages the event loop formost programs.
3. Beginners should usually use[Link]()insteadof manually creating loops.
al
18.4.5 Tasks
h
hc
A task schedules a coroutine to run concurrently.
Syntax is
task = asyncio.create_task(coroutine())
N
. A
1 task wraps a coroutine. It schedules the coroutine to run on the event loop.
2. Multiple tasks can run concurrently.await taskgetsthe final result.
ith
Example 1
eW
PYTHON CODE
import asyncio
await [Link](1)
print(name, "done")
C
await task1
await task2
[Link](main())
Output:
ask 1 done
T
Task 2 done
Both tasks wait concurrently.
18.4.6[Link]()
[Link]()runs multiple awaitables concurrentlyand collects their results.
al
An[Link]represents a result that may beavailable later.
h
.
1 [Link]is a low-level awaitable object.
a
hc
2. It is mainly used inside asyncio libraries and frameworks.
3. In normal application code, prefer coroutines and tasks.
4. Do not confuse[Link]with[Link].
P
is
ython’s docs note that[Link]is usuallyfor low-level callback-based code and
recommend not exposing Future objects in user-facing APIs.
N
Future Comparison
ith
__aenter__
C
__aexit__
not normal__enter__and__exit__.
Syntax
PYTHON CODE
class ClassName:
async def __aenter__(self):
return self
async def __aexit__(self, exc_type,
exc_value, traceback):
pass
Explanation
.
1 sync withis used for async resource management.
a
2. __aenter__runs when the async context starts.
3. __aexit__runs when the async context ends.
4. These methods can useawait.
al
5. They are common in async database connections, HTTP clients, and network
resources.
h
Example 1
hc
PYTHON CODE
import asyncio
class AsyncManager:
is
async def __aenter__(self):
N
print("Entering async context")
ith
return self
exc_value, traceback):
print("Exiting async context")
[Link](main())
utput:
O
Entering async context
Inside async context
Exiting async context
18.4.9 Async vs Threading vs Multiprocessing
Feature Threading Multiprocessing Asyncio
al
Unit Thread Process Coroutine/task
h
Best for I/O-bound blocking CPU-bound work I/O-bound non-blocking work
hc
work
If blocking code runs inside the event loop, it delays other async tasks. Python’s asyncio
od
development docs note that CPU-intensive work can block the event loop and delay other
tasks, and executors can be used to run such work elsewhere.
C