0% found this document useful (0 votes)
2 views365 pages

Python Notes X CodeWithNishchal

The document outlines a comprehensive roadmap for learning Python programming, covering topics from the introduction and environment setup to advanced concepts like decorators and generators. It includes chapters on Python syntax, data types, control flow, functions, object-oriented programming, file handling, and error management. Each chapter is structured to provide a detailed exploration of various Python features and best practices.

Uploaded by

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

Python Notes X CodeWithNishchal

The document outlines a comprehensive roadmap for learning Python programming, covering topics from the introduction and environment setup to advanced concepts like decorators and generators. It includes chapters on Python syntax, data types, control flow, functions, object-oriented programming, file handling, and error management. Each chapter is structured to provide a detailed exploration of various Python features and best practices.

Uploaded by

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

​Python Programming​

​Roadmap:​​Python Roadmap​

​Chapter 1: Introduction to Python​


​ .1 History of Python​
1
​1.2 What is Python?​


​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

​2.5 Python Interpreter​


​2.6 Python REPL​
​2.7 Creating and Running .py Files​
​2.8 Virtual Environments Using venv​
eW

​2.9 Installing Packages Using pip​


​2.10 [Link]​

​Chapter 3: Python Syntax Basics​


od

​ .1 First Python Code​


3
​3.2 Python File Structure​
​3.3 Comments​
​C

​3.4 Indentation Rules​


​3.5 Variables​
​3.6 Naming Conventions​
​3.7 Keywords​
​3.8 Print Statements​
​3.9 Input from Users​
​3.10 Basic Program Structure​
​3.11 Common Syntax Errors​
​3.12 Quick Revision Table​
​Chapter 4: Data Types​
​4.1 Numbers​
​4.1.1​​int​
​4.1.2​​float​
​4.1.3​​complex​
​4.2 Strings​
​4.2.1 String Creation​
​4.2.2 String Indexing​
​4.2.3 String Slicing​
​4.2.4 String Immutability​


​4.3 Boolean Data Type​

al
​4.3.1​​True​
​4.3.2​​False​
​4.4​​None​​Type​

h
​4.5 Type Checking with​​type()​
​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

​5.2 Comparison Operators​


​5.3 Logical Operators​
​5.4 Assignment Operators​
eW

​5.5 Membership Operators​


​5.6 Identity Operators​
​5.7 Bitwise Operators​
​5.8 Operator Precedence​
od

​Chapter 6: String Operations​


​ .1 String Creation​
6
​C

​6.2 String Indexing​


​6.3 String Slicing​
​6.4 String Methods​
​6.5 String Formatting​
​6.5.1 f-strings​
​6.5.2​​format()​​Method​
​6.5.3 Old​​%​​Formatting​
​6.6 String Concatenation​
​6.7 Escape Characters​
​6.8 Raw Strings​
​6.9 String Multiplication​
​Chapter 7: Control Flow​
​ .1 if Statement​
7
​7.2 if-else Statement​
​7.3 elif Statement​
​7.4 Nested Conditions​
​7.5 Ternary Operator​
​7.6 match-case​
​7.7 Truthy and Falsy Values​


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​

​Chapter 9: Data Structures​


eW

​9.1 Lists​
​ .1.1 Creating Lists​
9
​9.1.2 Accessing List Values​
​9.1.3 Updating List Values​
od

​9.1.4 List Methods​


​9.1.5 List Slicing​
​9.1.6 List Comprehensions​
​9.1.7 Nested Lists​
​C

​9.1.8 Sorting and Reversing Lists​


​9.1.9 Copying Lists​
​9.1.10 Shallow Copy vs Deep Copy​

​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.5​​get()​​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.3.14 Dictionary vs List​


​9.3.15 Important Dictionary Operations​

​9.4 Sets​
eW

​ .4.1 Creating Sets​


9
​9.4.2 Unique Values​
​9.4.3 Set Elements Must Be Immutable​
​9.4.4 Accessing Set Values​
od

​9.4.5 Checking Membership​


​9.4.6 Adding Set Items​
​9.4.7 Removing Set Items​
​9.4.8 Set Operations​
​C

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

​9.5 Collections Module​


​ .5.1​​Counter​
9
​9.5.2​​defaultdict​
​9.5.3​​OrderedDict​
​9.5.4​​deque​
​9.5.5​​ChainMap​


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

​10.16 Function Naming Rules​

​Chapter 11: Advanced Functions​


od

​ 1.1 Functions as First-Class Objects​


1
​11.2 Lambda Functions​
​11.3 map()​
​C

​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.8 __name__ == "__main__"​


​13.9 Package Structure​
​13.10 __init__.py​
eW

​13.11 Absolute Imports​


​13.12 Relative Imports​
​13.13 Package Management Basics​
​13.14 pip Basics​
​13.15 Virtual Environment Basics​
od

​13.16 [Link]​
​13.17 Third-Party Packages​
​13.18 Circular Import Warning​
​C

​Chapter 14: Object-Oriented Programming​


​14.1 OOP Fundamentals​
​ 4.1.1 Classes​
1
​14.1.2 Objects​
​14.1.3 Attributes​
​14.1.4 Methods​
​14.1.5​​self​
​14.1.6​​__init__​​Constructor​
​14.1.7 Instance Variables​
​ 4.1.8 Class Variables​
1
​14.1.9 Methods vs Functions​

​14.2 OOP Principles​


​ 4.2.1 Encapsulation​
1
​14.2.2 Inheritance​
​14.2.3 Method Overriding​
​14.2.4 Polymorphism​
​14.2.5 Duck Typing​
​14.2.6 Abstraction​
​14.2.7 Composition​


​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

​Chapter 15: Advanced OOP in Python​


​ 5.1 @classmethod​
1
​15.2 Class Method as Alternate Constructor​
​15.3 @staticmethod​
od

​15.4 Instance Method vs Class Method vs Static Method​


​15.5 @property​
​15.6 @property Setter​
​C

​15.7 Read-only Property​


​15.8 Abstract Base Classes​
​15.9 Why Abstract Base Classes Are Used​
​15.10 Mixins​
​15.11 Mixin vs Normal Parent Class​
​15.12 Metaclasses​
​15.13 Data Classes​
​15.14 Normal Class vs Data Class​
​15.15 Default Values in Data Classes​
​15.16 Mutable Defaults in Data Classes​
​15.17 Frozen Data Classes​
​Chapter 16: File Handling and Error Management​
​16.1 File Operations​
​ 6.1.1 File Handling​
1
​16.1.2 Opening Files​
​16.1.3 Closing Files​
​16.1.4 Reading Files​
​16.1.5 Reading Line by Line​
​16.1.6 Writing Files​


​16.1.7 Appending Files​

al
​16.1.8 File Modes​
​16.1.9​​with​​Statement​

h
​16.1.10 File Object Methods​
​16.1.11 Binary Files​

hc
​16.1.12 File Paths​
​16.1.13 Basic​​os​​Module​
​16.1.14 Basic​​pathlib​​Module​
​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.3 Multiple except Blocks​


​16.2.4 Handling Multiple Exceptions Together​
​16.2.5 else in Exception Handling​
eW

​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

​16.2.11 Exception Hierarchy​


​16.2.12 Bare except Warning​
​16.2.13 File Handling with Exception Handling​
​C

​15.3 File Formats​


​ 6.3.1 Text Files​
1
​16.3.2 CSV Files​
​16.3.3 [Link] vs [Link]​
​16.3.4 JSON Files​
​16.3.5 [Link]() vs [Link]()​
​16.3.6 XML Files​
​Chapter 17: Advanced Python Concepts​
​17.1 Decorators​
​ 7.1.1 Decorators​
1
​17.1.2 Function Decorators​
​17.1.3 Decorators with Function Arguments​
​17.1.4​​[Link]​
​17.1.5 Decorators with Arguments​
​17.1.6 Multiple Decorators​
​17.1.7 Class Decorators​
​17.1.8 Built-in and Standard Decorators​


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.7​​yield​ is
​17.2.8 Generator Expressions​
​17.2.9​​yield from​
N
​17.2.10 One-time Consumption of Iterators​
​17.2.11​​itertools​
ith

​17.2.12 Memory Efficiency​


​16.3 Context Managers​
​ 6.3.1​​__enter__​
1
​16.3.2​​__exit__​
eW

​16.3.3 Custom Context Manager Using Class​


​16.3.4​​contextlib​
​16.3.5​​@contextmanager​
​16.3.6 Resource Management​
​16.4 Regular Expressions​
od

​ 6.4.1​​re​​Module​
1
​16.4.2 Pattern Matching​
​16.4.3 Regex Metacharacters​
​C

​16.4.4 Common Regex Character Classes​


​16.4.5 Groups and Capturing​
​16.4.6 Non-capturing Groups​
​16.4.7​​search()​
​16.4.8​​match()​
​16.4.9​​fullmatch()​
​16.4.10​​findall()​
​16.4.11​​finditer()​
​16.4.12​​sub()​
​16.4.13​​split()​
​16.4.14​​[Link]()​
​ hapter 17: Concurrent and Asynchronous​
C
​Programming​
​17.1 Multithreading​
​ 7.1.1​​threading​​Module​
1
​17.1.2 Creating Threads​
​17.1.3 Managing Threads​
​17.1.4 Race Conditions​


​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 Concurrent Futures​


​ 7.3.1ThreadPoolExecutor​
1
is
N
​17.3.2 ProcessPoolExecutor​
​17.3.3Futures​
ith

​17.3.4Async Programming​

​17.4 Async Programming​


eW

​ 7.4.1​​asyncio​
1
​17.4.2​​async​​and Coroutines​
​17.4.3​​await​
​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 by​​Guido van Rossum​​.​


​He started working on Python in the late 1980s, and Python was first released in​​1991​​.​

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

​●​ ​Machine learning​


​●​ ​Testing​
​●​ ​Scripting​
​●​ ​Backend development​
od

​1.2 What is Python?​


​Python is a high-level, general-purpose programming language.​
​C

I​t 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!")​

​ utput: Hello, World!​


O
​Python files are saved with the​​.py​​extension. Example: [Link], [Link], [Link]​
​1.3 Why Learn Python?​
​Python is easy to start with and powerful enough for real-world projects.​

​Python is useful because:​

​​
● I​t 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​

​We do not need to deal directly with machine-level details​


N
​Interpreted​ ​Python code runs using the Python interpreter​
ith

​Dynamically typed​ ​No need to declare variable type manually​

​Object-oriented​ ​Supports classes and objects​


eW

​Cross-platform​ ​Runs on Windows, macOS, and Linux​

​Large library support​ ​Many built-in and external libraries are available​

​Open-source​ ​Free to use​


od

​1.5 Python Version​


​C

​ or modern learning, use​​Python 3​​. Python 2 is old​​and should not be used for new​
F
​learning.​

​To check Python version, use:​

​python --version or: python3 --version​

​Example output: Python 3.12.5​


​1.6 How Python Code Runs​
​Basic flow:​
​Python Code → Python Interpreter → Output​
​More accurate flow:​
​Source Code → Bytecode → Python Virtual Machine → Output​
​For now, remember:​

​​
● ​ ython code is written in​​.py​​files.​
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 → Run​​Program​
​Examples of compiled languages:​
ith

​​
● ​ ​
C
​●​ ​C++​
eW

​●​ ​Go​
​●​ ​Rust​

​Interpreter​
​An interpreter runs code more directly.​
od

​Flow:​​Source Code → Interpreter → Output​


​Python is commonly called an interpreted language.​
​C

​Compiler vs Interpreter​

​Point​ ​Compiler​ ​Interpreter​

​Translation​ ​Translates full code before running​ ​Runs code more directly​

​Speed​ ​Usually faster after compilation​ ​Usually slower​

​Error checking​ ​Many errors found before running​ ​Errors can appear while running​

​Examples​ ​C, C++, Go, Rust​ ​Python, JavaScript, Ruby​


​Chapter 2: Environment Setup​
​ nvironment setup means preparing your computer so you can write, run, and manage​
E
​Python programs properly.​

​For Python development, we mainly need:​

​ .​
1 ​ ython installed on the system​
P
​2.​ ​A code editor like VS Code​
​3.​ ​Terminal/Command Prompt basics​
​4.​ ​Package manager​​pip​


al
​5.​ ​Virtual environment setup using​​venv​

​Basic setup flow:​

h
​Install Python​

hc
​↓​
​Check Python Version​
​↓​
​Install VS Code​ is
​↓​
​Write Python Code​
N
​↓​
​Run Python File​
​↓​
ith

​Use venv and pip for Projects​

​2.1 Installing Python​


eW

​ 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

​2.​ ​Download the latest stable Python 3 installer.​


​3.​ ​Open the installer.​
​4.​ ​Select​​Add [Link] to PATH​​.​
​5.​ ​Click​​Install Now​​.​
​6.​ ​Wait for installation to complete.​
​7.​ ​Open Command Prompt and check the version.​

​Important:​​Always tick: Add [Link] to PATH​

​This option allows you to run Python from the terminal.​


​For macOS​

​Steps:​

​ .​
1 ​ ownload the macOS installer from the official Python website.​
D
​2.​ ​Open the​​.pkg​​file.​
​3.​ ​Follow the installation steps.​
​4.​ ​Open Terminal.​
​5.​ ​Check Python version.​

​Command: python3 --version​


al
​For Linux​

​Many Linux systems already come with Python installed.​

h
​Check version: python3 --version​

hc
​For Ubuntu/Debian-based systems, Python can usually be installed with:​

​ udo apt update​


s is
​sudo apt install python3 python3-pip python3-venv​
N
​2.2 Checking Python Version​
ith

​Windows​
​python --version or: py --version​
​macOS/Linux​
eW

​python3 --version​

​2.3 Installing VS Code​


​ S Code is a code editor used to write and run Python code. Python itself runs the code, but​
V
od

​VS Code helps us write code easily.​

​Steps to Install VS Code​


​C

​ .​
1 ​ ownload VS Code from the official website.​
D
​2.​ ​Install it.​
​3.​ ​Open VS Code.​
​4.​ ​Go to Extensions.​
​5.​ ​Search for​​Python​​.​
​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​

​Ways to Run Python in VS Code​

​You can run Python code by:​


al
​ .​ C
1 ​ licking the​​Run​​button.​
​2.​ ​Right-clicking and selecting​​Run 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.​

​ ad file names:​​[Link], [Link], [Link]​


B
is
​Better file names:​​number_game.py, student_report.py,​​[Link]​
N
​2.4 Terminal and Command Line Basics​
ith

​ he terminal / command prompt is a place where we type commands to interact with the​
T
​computer.​
eW

​Task​ ​Windows​ ​macOS/Linux​ ​Meaning​


​ ommand​
C ​Command​

​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

​Change folder​ ​cd folder_name​ ​cd folder_name​ ​Moves into a folder​

​Go back one folder​ ​cd ..​ ​cd ..​ ​Moves one level back​

​Create folder​ ​ kdir​


m ​ kdir​
m ​ reates a new folder named​
C
​python-notes​ ​python-notes​ ​python-notes​

​Clear terminal​ ​cls​ ​clear​ ​Clears the terminal screen​


​Running a Python File from Terminal​

​Suppose your file name is:​

​[Link]​

​Run it using: python [Link] or: python3 [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.​

​When we write: print("Hello")​


is
N
​the computer does not understand this directly.​
ith

​The Python interpreter reads this code and executes it.​

​Basic flow:​​Python Code → Python Interpreter → Output​


eW

​2.6 Python REPL​


​REPL stands for:​

​​
● ​ ead​
R
od

​●​ ​Evaluate​
​●​ ​Print​
​●​ ​Loop​
​C

​Python REPL allows us to run Python code line by line. It is useful for quick testing.​

​Opening Python REPL​

​Windows: python or: py​

​macOS/Linux: python3​

​You may see something like:​​>>>​

​This means Python REPL is ready.​


​REPL Example​
​ >> 10 + 20​
>
​30​
​>>> print("Hello")​
​Hello​
​>>> name = "Aman"​
​>>> name​
​'Aman'​

​Exiting Python REPL​


al
​Use: exit()​

​or press:​

h
​ trl + Z then Enter on Windows​
C

hc
​Ctrl + D on macOS/Linux​

​REPL vs Python File​


​REPL​
is ​Python File​

​Used for quick testing​ ​Used for complete programs​


N
​Code is not saved automatically​ ​Code is saved in​​.py​​file​
ith

​Runs line by line​ ​Runs full file​

​Good for experiments​ ​Good for projects​


eW

​When to Use REPL​

​Use REPL for:​


od

​​
● ​ esting small calculations​
T
​●​ ​Checking syntax​
​●​ ​Trying functions​
​C

​●​ ​Quick experiments​

​2.7 Creating and Running​​.py​​Files​


​A Python file is a file that contains Python code. Python files use the​​.py​​extension.​

​Examples:​

​[Link], [Link], [Link], student_app.py​


​Creating a Python File​

​Steps:​

​ .​
1 ​ reate a project folder.​
C
​2.​ ​Open it in VS Code.​
​3.​ ​Create a new file.​
​4.​ ​Save it with the​​.py​​extension.​
​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:​

​python [Link] OR python3 [Link]​


ith

​Output:​
eW

​ ello, Python​
H
​This is my first Python file​

​Python Runs File Top to Bottom​


​PYTHON CODE​
od

​ 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​​.py​​extension.​
​●​ ​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 Using​​venv​
ith

​ virtual environment is an isolated environment for a Python project. It keeps project​


A
​packages separate from other projects.​
eW

​ ython’s official documentation says​​venv​​is the standard tool for creating virtual​
P
​environments, and each virtual environment has its own independent set of installed Python​
​packages.​

​Why Virtual Environment is Needed​


od

​Suppose you have two projects:​

​ roject A needs package version 1.0​


P
​C

​Project B needs package version 2.0​

​If both projects use the same global Python environment, package conflicts can happen.​

​Virtual environments solve this problem.​

​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 Using​​pip​
​pip​​is Python’s package installer. It is used to install external libraries.​

​ ython’s official installing guide describes PyPI as a public repository of open-source​


P
​packages, and​​pip​​is used to install packages from​​it.​

​What is a Package?​

​ package is reusable code created by someone [Link] of writing everything from​


A
​scratch, we can install packages.​


al
​Example packages:​

h
​Package​ ​Use​

hc
​requests​ ​Working with APIs​

​pandas​ ​Data analysis​

​numpy​

​flask​
​Numerical computing​

​Web development​
is
N
​django​ ​Web development​
ith

​pytest​ ​Testing​

​Check pip Version​


eW

​pip --version or: python -m pip --version​

​On macOS/Linux: python3 -m pip --version​


od

​Install a Package​

​Example:​​pip install requests​


​C

​Better command: python -m pip install requests​

​On macOS/Linux: python3 -m pip install requests​

​Why​​python -m pip​​is Better​

​ his makes sure​​pip​​installs the package for the same Python interpreter you are using. This​
T
​is helpful when multiple Python versions are installed.​

​List Installed Packages​


​pip list or: python -m pip list​
​2.10​​[Link]​
​[Link]​​is a file that stores the list of packages used in a Python project.​

​It helps other people install the same packages easily.​

​ 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 using​​one command.​

​Create​​[Link]​

​After installing packages, run:​


is
N
​pip freeze > [Link]​

​or:​
ith

​python -m pip freeze > [Link]​

​This creates a file like:​


eW

r​ equests==2.32.3​
​urllib3==2.2.2​
​certifi==2024.7.4​
od

​Install Packages from​​[Link]​

​Use: pip install -r [Link]​


​C

​or:​

​python -m pip install -r [Link]​

​Example Project Structure​


​ eather_app/​
w
​│​
​├── [Link]​
​├── [Link]​
​└── venv/​
​Chapter 3. Python Syntax Basics​
​Python syntax means the set of rules used to write Python programs.​

​ 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!​

​3.1 First Python Code​ is


​The first Python program usually starts with printing a message on the screen.​
N
ith

​Output:​​Hello, World!​

​Part​ ​Meaning​
eW

​print​ ​Built-in Python function used to display output​

​()​ ​Parentheses used to pass data to the function​

​"Hello, World!"​ ​Text value, also called a string​


od

​Diagram:​
​C
​Another example:​

​Output:​

​ elcome to Python​
W
​Python is easy to learn​


​Each​​print()​​statement displays output on a new line​​by default.​

h al
​3.2 Python File Structure​

hc
​Python programs are usually saved with the​​.py​​extension.​

​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

​Basic file structure:​


od
​C
​Diagram:​


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

​Output: Hello Python​

​The line starting with​​#​​is ignored by Python.​


od

​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

​Best practice for beginners: use​​#​​for comments.​

​3.4 Indentation Rules​


eW

I​ndentation means spaces at the beginning of a line. Python uses indentation to define code​
​blocks. In many languages, curly braces​​{}​​are used​​to define blocks. Python uses​
​indentation instead.​

​Example:​
od
​C

​ utput: 10 is greater than 5​


O
​Here, the​​print()​​line is indented because it belongs​​to the​​if​​block.​
​Output:​

​ ou are eligible to vote​


Y


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 the​​if​​block.​
N
​print("Program finished") :​​This line is not indented,​​so it is outside the​​if​​block.​

​Wrong Indentation​
ith
eW

​Error:​​IndentationError: expected an indented block​

​Correct code:​
od

​Important Indentation Rules​


​C

​Use 4 spaces for indentation.​

​ void mixing tabs and spaces.​


A
​Wrong style:​

​Python may give an error if tabs and spaces are mixed.​


​3.5 Variables​
​A variable is a name used to store data.​

​Example:​


al
h
hc
​Output:​
is
N
​ ahul​
R
​21​
​5.8​
ith

​ ariable Name
V Value​
​name ------> "Rahul"​
eW

​age ------> 21​


​height ------> 5.8​

​Basic syntax:​​variable_name = value​


od

​Example:​
​C

​Variable​ ​Value​ ​Type​

​city​ ​"Delhi"​ ​String​

​marks​ ​85​ ​Integer​


​is_passed​ ​True​ ​Boolean​

​Python Variables Do Not Need Type Declaration​


​In Python, we do not need to write the data type before the variable name.​


​Output: 10​

al
​Python​
​In the first line,​​x​​stores an integer. Later,​​x​​stores 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

​3.6 Naming Conventions​


​ ariable names should be meaningful and easy to understand.​
V
​Good variable names:​

​Bad variable names:​


​These names are not always wrong, but they are less clear.​

​Rules for Naming Variables​


​Rule​ ​Valid Example​ ​Invalid Example​

​Can contain letters​ ​name​ ​—​


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

​Case-sensitive​ ​name​​,​​Name​ ​—​


​Valid variable names:​ is
N
ith

​Invalid variable names:​


eW
od

​Python Naming Convention​


​C

​Python commonly uses​​snake_case​​for variable names.​

​Naming Style​ ​Example 1​ ​Example 2​ ​Example 3​


​snake_case​ ​student_name​ ​total_marks​ ​user_email​

​camelCase​ ​studentName​ ​totalMarks​ ​userEmail​

​PascalCase​ ​StudentName​ ​TotalMarks​ ​UserEmail​

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

​This gives an error because​​class​​is a keyword.​


od

​Correct example:​
​C

​Checking Python Keywords​


​Python provides a built-in module called​​keyword​​.​

​This prints the list of Python keywords. To check whether a word is a keyword:​
​Output: True​
​False​

​3.8 Print Statements​


​The​​print()​​function is used to display output on​​the screen.​


​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

​Printing Text with Variables​

​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:​​The price of Laptop is ₹55000.​

​Print with Separator​


eW

​The​​sep​​parameter controls how multiple values are separated.​


od

​Output:​​Python | Java | C++​


​Default separator is a space.​
​C

​Output:​​Python Java C++​

​Print with End Parameter​


​By default,​​print()​​moves to a new line after printing.​
​Output:​
​Hello​
​Python​
​Using​​end​​:​

​Output:​​Hello Python​
​Another example:​


h al
​Output:​

hc
​A-B-C​

​3.9 Input from Users​


is
N
​The​​input()​​function is used to take input from the​​user.​
ith

​Example:​
eW

​Example output:​​Enter your name: Aman​


​Hello Aman​
od

​Important Point​
​The​​input()​​function always returns data as a string.​
​C

​ xample output:​
E
​Enter your age: 21​
​21​
​<class 'str'>​
​Even though the user entered​​21​​, Python stores it​​as​​"21"​​.​
​Taking Integer Input​
​To convert input into an integer, use​​int()​​.​

​ xample output:​
E
​Enter your age: 21​


​Your age is: 21​

al
​<class 'int'>​
​Taking Float Input​

h
​To convert input into decimal number, use​​float()​​.​

hc
​ xample output:​
E
is
N
​Enter product price: 99.50​
​Price is: 99.5​
ith

​<class 'float'>​
​Example: Add Two Numbers​
eW
od

​Example output:​​Enter first number: 10​


​Enter second number: 20​
​Sum is: 30​
​C

​What Happens Without​​int()​​?​

​ xample output:​
E
​Enter first number: 10​
​Enter second number: 20​
​1020​
​ ere, Python joins the two strings.​​It does not perform​​mathematical addition because​
H
​both values are strings.​
​Correct version:​

​Output: 30​

​3.10 Basic Program Structure​


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

​Example: Student Marks Program​


​C
​ xample output:​
E
​Enter student name: Ravi​
​Enter math marks: 80​
​Enter science marks: 90​
​Enter English marks: 85​
​Student Name: Ravi​
​Total Marks: 255​
​Average Marks: 85.0​

​3.11 Common Syntax Errors​


al
​ yntax errors happen when Python cannot understand the code because syntax rules are​
S
​broken.​

h
hc
​1. Missing Parentheses in​​print()​
​Wrong:​
​PYTHON CODE​
​print "Hello"​
is
N
​ rror:​​SyntaxError: Missing parentheses in call to​​'print'​
E
​Correct:​
ith

​PYTHON CODE​
​print("Hello")​
eW

​2. Missing Colon​


​Wrong:​
​PYTHON CODE​
od

​age = 20​

​if age >= 18​


​C

​print("Eligible")​

​Correct:​
​PYTHON CODE​

​age = 20​

​if age >= 18:​


​print("Eligible")​

​A colon​​:​​is required after statements like: if, else,​​elif, for, while, def, class, try, except, finally​
​3. Wrong Indentation​
​Wrong:​
​PYTHON CODE​

i​f 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

​5. Variable Used Before Assignment​


eW

​Wrong:​
​PYTHON CODE​

​ rint(name)​
p
od

​name = "Aman"​

​ rror:​​NameError: name 'name' is not defined​


E
​Correct:​
​C

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

​ ython thinks​​Aman​​is a variable.​


P
​Correct:​
​PYTHON CODE​

​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

​8. Invalid Variable Name​


eW

​Wrong:​
​PYTHON CODE​
​student-name = "Nishchal"​

​Correct:​
od

​PYTHON CODE​
​student_name = "Nishchal"​
​C

​9. Type Conversion Error​


​Code:​
​PYTHON CODE​
​age = int(input("Enter your age: "))​

I​f the user enters:​


​twenty​
​Python gives:​​ValueError: invalid literal for int()​
​Correct input should be numeric: 20​
​10. Unclosed Parentheses​
​Wrong:​
​PYTHON CODE​
​print("Hello Python"​

​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

​Topic​ ​Key Point​

​First Python code​ ​Usually starts with​​print("Hello, World!")​


eW

​Python file​ ​Saved with​​.py​​extension​

​Comments​ ​Written using​​#​

​Indentation​ ​Defines code blocks in Python​


od

​Variables​ ​Used to store data​

​Naming convention​ ​Prefer meaningful​​snake_case​​names​


​C

​Keywords​ ​Reserved words that cannot be used as variable names​

​print()​ ​Displays output​

​input()​ ​Takes user input as string​

​int()​ ​Converts value to integer​

​float()​ ​Converts value to decimal number​

​Syntax errors​ ​Occur when Python rules are broken​


​Chapter 4. Data Types in Python​
​A​​data type​​tells Python what kind of value a variable​​is storing.​

​Example:​


h al
hc
​Variable​ ​Value​ ​Data Type​

​name​ ​"Rahul"​ ​String​


is
N
​age​ ​21​ ​Integer​

​price​ ​99.50​ ​Float​


ith

​is_active​ ​True​ ​Boolean​


eW

​Simple meaning: Data type = Type/category of data stored in a variable​


od
​C

​Example:​

​Output: <class 'int'>​

​This means​​x​​is storing an integer value.​


​4.1 Numbers​
​Numbers are used to store numeric values. Python mainly has three number types:​


h al
​4.1.1​​int​

hc
​int​​means​​integer​​. Integers are whole numbers. They​​do not have decimal points.​

​Examples:​ is
N
ith
eW

​ utput:​
O
od

​21​
​95​
​-5​
​0​
​C

​All these values are integers.​

​Output: <class 'int'>​


​Examples of​​int​


I​mportant 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.2​​float​
eW

​float​​means​​floating-point number​​. Float values contain​​decimal points.​


od
​C

​ utput:​
O
​99.5​
​5.8​
​-2.5​
​85.75​

​Checking type:​

​Output: <class 'float'>​


​Examples of​​float​

h al
hc
is
N
ith
eW

​Important point:​

​Python may display​​99.50​​as​​99.5​​.​


od

​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.3​​complex​
​complex​​numbers are numbers with two parts:​
​Real part + Imaginary part​
​In mathematics, complex numbers are usually written like this:​
​3 + 4i​
​But in Python, we use​​j​​instead of​​i​.​


al
​Python complex number:​

h
hc
​ utput:​
O
is
N
​(3+4j)​
​<class 'complex'>​
ith

​Here:​​3 = real part and 4j = imaginary part​


eW
od

​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

​ ​​string​​is a sequence of characters.​


A
​Characters can be:​​Letters, Numbers, Symbols, Spaces​
eW

​Examples:​
od

​Even though the phone contains numbers, it is inside quotes, so it is a string.​


​C

​Output: <class 'str'>​



al
​4.2.1 String Creation​

h
​Strings can be created using quotes.​

hc
​Using Double Quotes​

is
N
​Output: Aman​
ith

​Using Single Quotes​


eW

​ 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

​You can also use triple single quotes:​


od
​C

​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
I​ndexing means accessing a single character from a string. Every character in a string has a​
​position number. This position number is called an​​index​​.​

​ ython indexing starts from 0.​


P is
​Example:​
N
​Index diagram:​
ith
eW

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

​-1 means last character and -2 means second last character​

​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?​

​"Python" has indexes from 0 to 5 only. Index 10 does not exist.​


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​

​Leaving Start Empty​

hc
​If start is empty, Python starts from the beginning.​

is
N
​Output:​
ith

​Pyt​
​Meaning:​
​Start from beginning​
eW

​Stop before index 3​

​Leaving End Empty​


​If end is empty, Python goes till the end.​
od

​Output: thon​
​C

​Meaning: Start from index 2 and Go till the end​

​Full Slice​

​Output: Python​
​This returns the full string.​

​Slicing with Negative Index​


​Output: hon​


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​

​Reverse string using slicing:​


od
​C

​ utput: nohtyP​
O
​Explanation:​​[::-1] means read the string from right to left​

​4.2.4 String Immutability​


​ trings in Python are​​immutable​​.​
S
​Immutable means:​​Once created, it cannot be changed directly.​
​name = "Ravi"​
​Index diagram:​
​Suppose we want to change​​R​​to​​K​. This will not work:​

​ rror:​​TypeError: 'str' object does not support item assignment​​Why?​​Because strings​


E


​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

​Output: <class 'bool'>​

​Diagram:​
eW
od
​C

​4.3.1​​True​
​True​​represents 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 understand​​true​​because Python uses​​True​​.​

​4.3.2​​False​
is
N
​False​​represents no, incorrect, inactive, unavailable, or disabled.​
ith
eW

​ utput:​
O
od

​False​
​False​
​False​
​C

​Important:​​False must start with capital F.​


​Correct:​​is_active = False​
​Wrong:​ ​is_active = false​
​Python uses​​False​​, not​​false​​.​

​4.4 None Type​


​ one​​means​​no value​​or​​empty value​​. It is used when a variable exists, but it does not​
N
​currently store any actual value.​
​Output:None​
​<class 'NoneType'>​
​●​ ​None is not 0. None is not an empty string.​
​●​ ​None is not False.​​None means no value.​

​Value​ ​Meaning​


al
​0​ ​A number​

h
​""​ ​Empty string​

hc
​False​ ​Boolean false​

​None​ ​No value​


is
N
ith

​Output:​
eW

​0​
​False​
​None​
​There is a blank line after​​0​​because​​name​​is 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

​4.5 Type Checking with​​type()​


​The​​type()​​function is used to check the data type​​of a value or variable.​
eW

​Syntax:​

​Example:​
od

​PYTHON CODE​

​ ge = 21​
a
​print(type(age))​
​C

​Output: <class 'int'>​

​Checking Different Data Types​



​ utput:​
O

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,​​100​​is 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"​

​Python provides built-in functions for type conversion.​


​Function​ ​Converts Into​

al
​int()​ ​Integer​

h
​float()​ ​Float​

hc
​str()​ ​String​

​bool()​ ​Boolean​

​complex()​ ​Complex number​


is
N
ith

​4.6.1 Converting to​​int​


eW

i​nt()​​converts a value into an integer.​


​Example:​
od
​C

​ utput:​
O
​100​
​<class 'int'>​
​Before conversion:​​x = "100" type is str​
​After conversion:​​y = 100 type is int​
​Invalid​​int()​​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)​

​ rror: ValueError: invalid literal for int()​


E
​Why? Because​​"10.5"​​is a decimal number written as a string. It cannot be converted directly​
eW

​into​​int​​.​

​4.6.2 Converting to​​float​


​float()​​converts a value into a decimal number.​
od
​C

​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 to​​str​
ith

​ tr()​​converts a value into a string.​


s
​Example:​
eW
od

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

​4.6.4 Converting to​​bool​


N
​ ool()​​converts a value into​​True​​or​​False​​.​
b
ith

​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 in​​Truthy and Falsy​​Values​​in the Control Flow section.​

​4.6.5 Converting to​​complex​


​complex()​​converts a value into a complex number.​
​Example:​


h al
hc
​Output:​
​(10+0j)​
​<class 'complex'>​
​String to complex:​
is
N
ith
eW

​Output:​
(​ 5+0j)​
​<class 'complex'>​
od
​C

​4.7 Mutable vs Immutable Data Types​


​This is a very important concept in Python. First understand these two words:​

​Mutable = Can be changed after creation​


​Immutable = Cannot be changed after creation​

​Immutable Data Types​


I​mmutable data types cannot be changed directly after they are created. Examples of​
​immutable data types:​

​​
● i​nt​
​●​ ​float​
​●​ ​complex​
​●​ ​str​
​●​ ​bool​
​●​ ​NoneType​

​We have already studied these types in this chapter.​


h al
​Example with string:​

hc
​PYTHON CODE​
​ ame = "Ravi"​
n
is
N
​name[0] = "K"​
ith

​ rror: TypeError: 'str' object does not support item assignment​


E
​Because string is immutable.​
​Correct idea:​
eW

​PYTHON CODE​
​name = "Ravi"​
​name = "Kavi"​
​print(name)​
od

​Output: Kavi​

​ ere, Python does not change​​"Ravi"​​directly. It creates a new string​​"Kavi"​​and makes​


H
​C

​name​​refer to that new string.​


​Immutable Number Example​
​ umbers are also immutable.​
N
​Example:​

​Output: 21​


al
​Mutable Data Types​

h
​Mutable data types can be changed after creation. Some mutable data types in Python are:​

hc
​ ​ l​ist​

​●​ ​dictionary​
​●​ ​set​
is
​These will be studied in detail later in the​​Data​​Structures​​[Link] now, only remember:​
N
​ .​ ​Mutable objects can be modified.​
1
​2.​ ​Immutable objects cannot be modified directly.​
ith

​Type​ ​Mutable or Immutable​

​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 name​​x​​now points to​​20​​. It does not mean​​10​​changed into​​20​​.​
​This idea is very useful for understanding mutable and immutable data later.​

​4.9 Quick Revision​


al
​Topic​ ​Meaning​

h
​Data type​ ​Type/category of value​

hc
​int​ ​Whole numbers​

​float​ ​Decimal numbers​


is
N
​complex​ ​Number with real and imaginary parts​
ith

​str​ ​Text / sequence of characters​

​Indexing​ ​Accessing one character from a string​


eW

​Slicing​ ​Accessing a part of a string​

​ tring​
S ​Strings cannot be changed directly​
​immutability​
od

​bool​ ​Stores​​True​​or​​False​
​C

​None​ ​Represents no value​

​type()​ ​Checks data type​

​Type conversion​ ​Converts one data type into another​

​Mutable​ ​Can be changed after creation​

​Immutable​ ​Cannot be changed after creation​


​Chapter 5. Operators in Python​
​Operators are special symbols or words used to perform operations on values and variables.​

​Simple meaning:​

​Operator = Symbol or keyword that performs an operation​

​Example:​


​PYTHON CODE​

al
​a = 10​
​b = 5​

h
​print(a + b)​

hc
​Output:​
​15​
​Here,​​+​​is an operator. It adds​​a​​and​​b​.​
​Diagram:​ is
N
ith
eW

​Python operators are mainly divided into these types:​

​Operators​
​│​
​├── Arithmetic operators​
od

​├── Comparison operators​


​├── Logical operators​
​├── Assignment operators​
​C

​├── Membership operators​


​├── Identity operators​
​├── Bitwise operators​
​└── Operator precedence​
​5.1 Arithmetic Operators​
​Arithmetic operators are used to perform mathematical operations.​

​ .​
1 ​ ddition​
A
​2.​ ​Subtraction​
​3.​ ​Multiplication​
​4.​ ​Division​
​5.​ ​Power​
​6.​ ​Remainder​


al
​Arithmetic operators work mostly with numbers.​

​List of Arithmetic Operators​

h
hc
​Operator​ ​Name​ ​Example​

​+​ ​Addition​ ​10 + 5​

​-​

​*​
​Subtraction​

​Multiplication​
​10 - 5​

​10 * 5​
is
N
​/​ ​Division​ ​10 / 5​
ith

​//​ ​Floor division​ ​10 // 3​

​%​ ​Modulus​ ​10 % 3​


eW

​**​ ​Exponent / Power​ ​2 ** 3​

​Addition​​+​
od

​The​​+​​operator adds two numbers.​

​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. Division​​using / 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 though​​10 / 5​​is mathematically​​2​, Python gives​​2.0​​.​
​That means the result is a float.​
​Floor Division​​//​
​ he​​//​​operator divides and gives the whole-number​​part.​
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​

I​mportant 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

​ he​​%​​operator gives the remainder after division.​


T
​Example:​
​PYTHON CODE​
​C

​ = 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

​5.2 Comparison Operators​


​ omparison operators are used to compare two values. The result of a comparison is​
C
​C

​always a Boolean value:​


​●​ ​True​
​●​ ​False​
​Example:​
​print(10 > 5)​
​Output: True​
​Because​​10​​is greater than​​5​.​
​List of Comparison Operators​
​Operator​ ​Meaning​ ​Example​

​==​ ​Equal to​ ​10 == 10​

​!=​ ​Not equal to​ ​10 != 5​

​>​ ​Greater than​ ​10 > 5​

​<​ ​Less than​ ​5 < 10​


al
​>=​ ​Greater than or equal to​ ​10 >= 10​

​<=​ ​Less than or equal to​ ​5 <= 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​

​Not Equal To​​!=​


​The​​!=​​operator checks whether two values are not equal.​
od

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

​print(10 > 5)​


​print(5 > 10)​

​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

​Greater Than or Equal To​​>=​


​The​​>=​​operator checks whether the left value is greater​​than or equal to the right value.​
eW

​PYTHON CODE​

​print(10 >= 5)​


​print(10 >= 10)​
od

​print(5 >= 10)​

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

​print(5 <= 10)​


​print(10 <= 10)​
​print(20 <= 10)​

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

​Comparison with Variables​


is
N
​PYTHON CODE​

​a = 15​
ith

​b = 20​
​print(a == b)​
​print(a != b)​
eW

​print(a > b)​


​print(a < b)​
​print(a >= b)​
​print(a <= b)​
od

​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 with​​True​​and​​False​​.​

​List of Logical Operators​


al
​Operator​ ​Meaning​

​and​ ​True when both sides are True​

h
​or​ ​True when at least one side is True​

hc
​not​ ​Reverses True/False​

​and​​Operator​ is
​The​​and​​operator gives​​True​​only when both values​​are​​True​​.​
N
​PYTHON CODE​

​print(True and True)​


ith

​print(True and False)​


​print(False and True)​
eW

​print(False and False)​

​Output:​
​True​
​False​
od

​False​
​False​
​Truth table:​
​C

​Left Value​ ​Right Value​ ​Result​

​True​ ​True​ ​True​

​True​ ​False​ ​False​

​False​ ​True​ ​False​

​False​ ​False​ ​False​


​Simple meaning: and means both conditions must be True.​
​Example:​

​PYTHON CODE​
​age_valid = True​
​id_available = True​
​print(age_valid and id_available)​

​Output:​
​True​


al
​or​​Operator​
​The​​or​​operator gives​​True​​when at least one value is​​True​​.​

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

​Left Value​ ​Right Value​ ​Result​

​True​ ​True​ ​True​

​True​ ​False​ ​True​


od

​False​ ​True​ ​True​

​False​ ​False​ ​False​


​C

​or means at least one value must be True.​


​Example:​

​PYTHON CODE​
​has_email = True​
​has_phone = False​
​print(has_email or has_phone)​

​Output: True​
​not​​Operator​
​The​​not​​operator 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

​Logical Operators with Comparisons​


​Comparison operators return Boolean values. So they can be used with logical operators.​
eW

​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,​​10​​is assigned to​​x​.​

h
​List of Assignment Operators​

hc
​Operator​ ​Example​ ​Same As​

​=​ ​x = 10​ is ​x = 10​

​+=​ ​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​

​Multiply and Assign​​*=​


od

​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

​Modulus and Assign​​%=​


​PYTHON CODE​
​x = 10​
eW

​x %= 3​
​print(x)​

​Output: 1​
od

​Explanation: x %= 3​
​Same as: x = x % 3​

​Power and Assign​​**=​


​C

​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:​
​ .​ i​n​
1
​2.​ ​not in​
​ or now, we will use membership operators with strings because strings are already​
F
​covered.​

​in​​Operator​


al
​The​​in​​operator 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

​"Py" exists in "Python" True​


​"Java" does not exist False​

​not in​​Operator​
​The​​not in​​operator 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.​

​5.6 Identity Operators​ is


I​dentity operators are used to check whether two variables refer to the same object in​
N
​memory.​
​Python has two identity operators:​
ith

​ .​ i​s​
1
​2.​ ​is not​
​Important:​
eW

​== checks value​


​is checks identity/memory object​

​is​​Operator​
od

​The​​is​​operator checks whether two variables point to the same object.​


​Example:​
​C

​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 not​​Operator​
​The​​is not​​operator checks whether two variables do​​not 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​​==​​and​​is​ 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

​<<​ ​Left shift​

​>>​ ​Right shift​


eW

​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 gives​​1​​when 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

​Bitwise NOT flips bits. In Python, the result of​​~x​​is:​


od

​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 is​​20​​.​
is
N
​Why Operator Precedence Matters​
ith

​Without precedence, Python would not know which operation to do first.​


​Example:​
​10 + 5 * 2​
eW

​There are two possible ways:​


​Way 1:​​(10 + 5) * 2 = 30​

​Way 2:​​10 + (5 * 2) = 20​


od

​Python follows fixed precedence rules. So: 10 + 5 * 2 = 20​

​and​​Happens Before​​or​
​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​

​1​ ​()​ ​Parentheses​


​2​ ​**​ ​Power​
​3​ ​+x​​,​​-x​​,​​~x​ ​Unary plus, unary minus, bitwise NOT​
​4​ ​*​,​​/​,​​//​​,​​%​ ​Multiplication, division, floor division, modulus​
​5​ ​+​,​​-​ ​Addition, subtraction​


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

​Parentheses are used to control the order manually.​

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

​Power Has Higher Priority Than Multiplication​


​PYTHON CODE​
​result = 2 * 3 ** 2​
​print(result)​

​Output: 18​
​Chapter 6. String Operations​
​A​​string​​is 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.​

​6.1 String Creation​


​Strings can be created using single quotes, double quotes, or triple quotes.​


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​

​message = """Python is simple.​


ith

​Python is powerful.​
​Python is widely used."""​
eW

​6.2 String Indexing​


​Indexing means accessing one character from a string. Python starts counting from​​0​.​
od

​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: the​​start index is included​​, and the​​end 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​

​text = " Python "​


od

​print([Link]())​

​Output:​
​C

​Python​
​replace()​
​Replaces one part of a string with another.​

​PYTHON CODE​

​text = "I like Java"​


​print([Link]("Java", "Python"))​

​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()​​and​​endswith()​
​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.​
​Write​​f​​before 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.2​​format()​
​The​​format()​​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))​

​Output:​​My name is Aman and I am 20 years old.​


​Here:​


​●​ ​%s​​is used for string​

al
​●​ ​%d​​is 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

​print(first + " " + second)​

​Output:​
eW

​Python Programming​
​Important point:​​only strings can be joined directly.​

​6.7 Escape Characters​


​Escape characters start with a backslash​​\​​and help​​insert special characters inside strings.​
od

​Common escape characters:​

​Escape Character​ ​Meaning​


​C

​\n​ ​New line​

​\t​ ​Tab space​

​\\​ ​Backslash​

​\'​ ​Single quote​

​\"​ ​Double quote​


​Common Escape Characters​
​Escape​ ​Meaning​ ​Example​ ​Output​
​Character​

​\n​ ​New Line​ ​print("Hello\nPython")​ ​ pre>Hello​


<
​Python</pre>​

​\t​ ​Horizontal Tab​ ​print("Name\tAge")​ ​<pre>Name Age</pre>​

​\\​ ​Prints a Backslash​ ​print("C:\\Users\\Admin")​ ​C:\Users\Admin​


​\'​ ​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)​

​\r​ ​ arriage Return​


C ​print("Hello\rHi")​ ​ illo​​(behavior may vary by​
H
​(moves cursor to​ ​terminal)​

​\f​
​beginning of line)​

​Form Feed​
is
​print("Hello\fPython")​ I​nserts a form-feed​
N
​character​
ith

​\v​ ​Vertical Tab​ ​print("Hello\vPython")​ ​Inserts a vertical tab​

​\a​ ​Alert/Bell​ ​print("\a")​ ​Produces a system beep​


eW

​6.8 Raw Strings​


​Raw strings treat backslashes as normal characters.​
​Write​​r​​before the string.​
od

​PYTHON CODE​
​path = r"C:\new_folder\test"​
​print(path)​
​C

​Output: C:\new_folder\test​

​6.9 String Multiplication​


​A string can be repeated using the​​*​​operator.​

​PYTHON CODE​

​text = "Hi"​
​print(text * 3)​

​Output: HiHiHi​
​Common String Methods​
​Method​ ​Description​ ​Example​ ​Result​

​lower()​ ​Converts all characters to lowercase​ ​"Python".lower()​ ​"python"​

​upper()​ ​Converts all characters to uppercase​ ​"Python".upper()​ ​"PYTHON"​


​title()​ ​ onverts first letter of every word to​
C ​"python programming".title()​ "​ Python​
​uppercase​ ​Programming"​
​capitalize()​ ​ apitalizes only the first letter of the​
C ​"python".capitalize()​ ​"Python"​
​string​


​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

​startswith()​ ​ hecks whether a string starts with a​


C ​"Python".startswith("Py")​ ​True​
​substring​
​endswith()​ ​ hecks whether a string ends with a​
C ​"Python".endswith("on")​ ​True​
eW

​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()​ ​ eturns​​True​​if all characters are​
R ​"Python".isalpha()​ ​True​
od

​alphabets​
​isdigit()​ ​ eturns​​True​​if all characters are​
R ​"12345".isdigit()​ ​True​
​digits​
​isalnum()​ ​ eturns​​True​​if all characters are​
R ​"Python3".isalnum()​ ​True​
​C

​letters or digits​

​isspace()​ ​ eturns​​True​​if all characters are​


R ​" ".isspace()​ ​True​
​whitespace​

​center(width)​ C
​ enters the string within the specified​ ​"Python".center(12)​ ​" Python "​
​width​

​zfill(width)​ ​Pads the string with leading zeros​ ​"25".zfill(5)​ ​"00025"​


​Chapter 7. Control Flow​

​7.1​​if​​Statement​
​Syntax​


h al
​ he​​if​​statement is used when we want to run some​​code only when a condition is​​True​​.​
T
​If the condition is​​True​​, Python executes the indented block.​

hc
​If the condition is​​False​​, Python skips the indented​​block.​

​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.2​​if-else​​Statement​
​Syntax​


al
​Explanation​

h
​ he​​if-else​​statement is used when we want to run​​one block if the condition is True​​and​
T

hc
​another block if the condition is False​​.​
​Only one block runs.​
​If the condition is​​True​​, the​​if​​block runs.​is
​If the condition is​​False​​, the​​else​​block 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")​

​Output:​​Not eligible to vote​


​7.3​​elif​​Statement​
​Syntax​


h al
hc
is
N
​Explanation​
ith

​elif​​means​​else if​​.​
I​t is used when we need to check​​multiple conditions​​.​​Python checks conditions from top​
eW

​to bottom. The first condition that becomes​​True​​gets​​executed. After that, Python skips the​
​remaining conditions.​
​The​​else​​block runs only when all previous conditions​​are​​False​​.​
​Example​
od

​PYTHON CODE​

​ arks = 75​
m
​if marks >= 90:​
​print("Grade A")​
​C

​elif marks >= 75:​


​print("Grade B")​
​elif marks >= 40:​
​print("Grade C")​
​else:​
​print("Fail")​

​Output:​​Grade B​
​7.4 Nested Conditions​
​Syntax​

​With​​else​​:​


h al
hc
N
is
​ ested condition means writing one condition inside another condition. The inner condition is​
​checked only when the outer condition is​​True​​. This​​is useful when one decision depends on​
N
​another decision.​

​Flow Chart​
ith
eW
od

​Example​
​C

​Output: Entry allowed​


​7.5 Ternary Operator​
​Syntax​

​Common usage:​


al
​ he ternary operator is a short way to write a simple​​if-else​​statement 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, normal​​if-else​​is better.​

hc
​Flow Chart​
is
N
ith
eW

​Normal​​if-else​​:​
​PYTHON CODE​
​ ge = 20​
a
od

​if age >= 18:​


​status = "Adult"​
​else:​
​status = "Minor"​
​C

​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.6​​match-case​
​Syntax​


h al
hc
​Explanation​
​ atch-case​​is used to compare one value with multiple​​possible cases. It is similar to​
m
​checking many fixed options.​
is
​ he​​_​​case works like a default case. It runs when​​no other case matches.​​match-case​​was​
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

​7.7 Truthy and Falsy Values​


​Syntax​
od
​C

​Explanation​
I​n Python, conditions do not always need direct comparison like: if age >= 18:​
​Python can also treat values as​​True​​or​​False​​. These​​are called​​truthy​​and​​falsy​​values.​
​A​​truthy value​​behaves like​​True​​.​​A falsy value behaves​​like​​False​​.​
​Common falsy values:​

​Value​ ​Meaning​

​False​ ​Boolean false​

​0​ ​Zero number​

​0.0​ ​Zero float​

​""​ ​Empty string​


al
​None​ ​No value​

h
​Common truthy values:​

hc
​Value​ ​Meaning​

​True​ ​Boolean true​

​10​ ​Non-zero number​


is
N
​-5​ ​Non-zero number​

​"Python"​ ​Non-empty string​


ith

​" "​ ​ tring with a​


S
​space​
eW

​Important:​​" "​​is truthy because it contains a space.​​It is not empty.​

​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

​Output: Amount is zero​


​C
​Chapter 8. Loops and Iteration​
​Loops are used when we want to run the same code multiple times.​

​Q: Print numbers from 1 to 5​

​ ithout a loop, we write many​​print()​​statements.​​With loop, we write the logic once and​
W
​Python repeats it.​

​8.1​​for​​Loop​


al
​Syntax​

h
hc
​Explanation​
​ .​
1 ​ ​​for​​loop 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

​Example 1: Loop through a string​


​C

​ utput:​
O
​P​
​y​
​t​
​h​
​o​
​n​
​Example 2: Loop with​​range()​

​ utput:​
O
​1​
​2​
​3​
​4​
​5​


​8.2 while Loop​

al
​Syntax​

h
​Explanation​
hc
​ .​
1
is
​ ​​while​​loop runs as long as the condition is​​True​​.​
A
N
​2.​ ​Before every round, Python checks the condition.​
​3.​ ​If the condition is​​True​​, the loop block runs.​
ith

​4.​ ​If the condition becomes​​False​​, the loop stops.​

​Flow Chart​
eW
od
​C
​Example 1:​​Print numbers from 1 to 5​
​PYTHON CODE​
​number = 1​

​while number <= 5:​


​print(number)​
​number += 1​

​ utput:​
O
​1​
​2​


​3​

al
​4​
​5​

h
​for​​Loop vs​​while​​Loop​

hc
​Point​ ​for​​Loop​ ​while​​Loop​

​Main use​ ​Used to loop over a sequence​ is ​Used to repeat while a condition is​​True​

​Best when​ ​Number of iterations is known​ ​Number of iterations is not fixed​


N
​Works with​ ​ tring,​​range()​​, and other iterable​
S ​Conditions​
​values​
ith

​Stops when​ ​Sequence ends​ ​Condition becomes​​False​

​Risk​ ​Usually safer​ ​ an create infinite loop if condition never​


C
eW

​becomes​​False​

​When to Use​​for​​and​​while​

​Situation​ ​Better Loop​


od

​Loop through characters in a string​ ​for​​loop​

​Loop through numbers using​​range()​ ​for​​loop​


​C

​Repeat until password is correct​ ​while​​loop​

​Repeat while balance is available​ ​while​​loop​

​Repeat fixed number of times​ ​for​​loop​

​Repeat based on condition​ ​while​​loop​


​8.3​​break​
​Syntax:​

​Explanation​
​ .​ b
1 ​ reak​​is used to stop a loop immediately.​
​2.​ ​When Python sees​​break​​, it exits the loop.​


​3.​ ​Code after the loop continues normally.​

al
​Flow Chart:​

h
hc
is
N
ith

​Example 1: Stop loop when number is 4​


​PYTHON CODE​
​for number in range(1, 8):​
eW

​if number == 4:​


​break​
​print(number)​
od

​Output:​
​1​
​2​
​C

​3​
​Explanation:​
​1.​ ​The loop starts from​​1​.​
​2.​ ​When​​number​​becomes​​4​,​​break​​runs.​
​3.​ ​The loop stops before printing​​4​.​
​8.4​​continue​
​Syntax​

​Explanation​
​1.​ ​continue​​skips the current round of the loop.​


​2.​ ​It does not stop the full loop.​

al
​3.​ ​After​​continue​​, Python moves to the next round.​

​Flow Chart​

h
hc
is
N
ith

​Example 1: Skip number 3​

​PYTHON CODE​
​for number in range(1, 6):​
eW

​if number == 3:​


​continue​
​print(number)​
od

​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.5​​pass​
​Syntax​

​1.​ p
​ ass​​means “do nothing”. It is used when Python needs​​a statement, but we do not​
​want to write logic yet. It does not stop or skip the loop like​​break​​or​​continue​​.​

​Flow Chart​


h al
​Example 1: Empty loop block​

hc
​PYTHON CODE​
is
N
​for number in range(1, 4):​
​pass​
ith

​Output:​​No output appears because​​pass​​does nothing.​


​Example 2: Placeholder inside condition​
eW

​PYTHON CODE​
​for number in range(1, 4):​
​if number == 2:​
​pass​
od

​print(number)​

​ utput:​
O
​1​
​C

​2​
​3​

​Loop Control Statements Comparison​


​Statement​ ​Meaning​ ​Effect on Loop​ ​Common Use​

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

​pass​ ​Do nothing​ ​No effect on loop​ ​Temporary placeholder​


​8.6​​else​​with Loops​
​Syntax​

​Explanation​


al
​ .​ A
1 ​ loop can have an​​else​​block. The​​else​​block runs​​when the loop finishes normally.​
​2.​ ​If the loop stops because of​​break​​, the​​else​​block​​does 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 with​​break​

​PYTHON CODE​
​C

​for number in range(1, 5):​


​if number == 3:​
​break​
​print(number)​
​else:​
​print("Loop finished")​

​ 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

​Example 1: Row and column output​


od

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

​for row in range(1, 4):​


​print("*" * row)​

​Output:​
​*​
​**​


​***​

h al
​8.8​​range()​

hc
​Syntax​
is
N
​Explanation​
ith

​ .​
1 r​ ange()​​creates a sequence of numbers.​
​2.​ ​It is commonly used with​​for​​loops.​
eW

​3.​ ​The stop value is excluded.​


​4.​ ​step​​controls the gap between numbers.​

​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 from​​0​.​
​2.​ ​It stops before​​5​.​


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

​Example 3:​​range(start, stop, step)​


​PYTHON CODE​
​for number in range(2, 11, 2):​
eW

​print(number)​

​ utput:​
O
​2​
​4​
od

​6​
​8​
​10​
​C

​range()​​Forms​
​Syntax​ ​Meaning​ ​Example​ ​Output Values​

​range(stop)​ ​Starts from​​0​, stops before​​stop​ ​range(5)​ ​0, 1, 2, 3, 4​

​range(start, stop)​ ​Starts from​​start​​, stops before​​stop​ ​range(1, 5)​ ​1, 2, 3, 4​

​range(start, stop, step)​ ​Uses step/gap between values​ ​range(2, 10, 2)​ ​2, 4, 6, 8​
​Positive and Negative Step in​​range()​
​Example​ ​Meaning​ ​Output Values​

​range(1, 6, 1)​ ​Increase by​​1​ ​1, 2, 3, 4, 5​

​range(1, 6, 2)​ ​Increase by​​2​ ​1, 3, 5​

​range(5, 0, -1)​ ​Decrease by​​1​ ​5, 4, 3, 2, 1​


​range(10, 0, -2)​ ​Decrease by​​2​ ​10, 8, 6, 4, 2​

h al
​8.9​​enumerate()​

hc
​Syntax​
is
N
ith

​Explanation​
​1.​ ​enumerate()​​gives both index and value while looping.​
eW

​2.​ ​It is useful when we need the position of each item.​


​3.​ ​The index starts from​​0​​by default.​

​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
f​or 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

​enumerate()​​vs Normal Loop​


​Normal Loop​ ​enumerate()​

​Gives only value​ ​Gives index and value​

​ ood when index is not​


G ​Good when index is needed​
​needed​

​Simple for direct looping​ ​Better for position-based output​


​8.10​​zip()​
​Syntax​

​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

​Example 1: Zip two strings​


eW

​PYTHON CODE​

​letters = "ABC"​
​numbers = "123"​
od

f​or letter, number in zip(letters,​


​numbers):​
​print(letter, number)​
​C

​Output:​
​A 1​
​B 2​
​C 3​
​Example 2: Different length sequences​
​PYTHON CODE​
​letters = "ABCD"​
​numbers = "12"​
f​or letter, number in zip(letters,​
​numbers):​
​print(letter, number)​

​Output:​


​A 1​

al
​B 2​
​Explanation:​

h
​1.​ ​letters​​has 4 characters.​

hc
​2.​ ​numbers​​has 2 characters.​
​3.​ ​zip()​​stops after the shorter sequence ends.​

​8.11 Iterator Protocol Basics​ is


​Syntax​
N
ith
eW

​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

​Iterable​ ​Something that can be looped over​

​Iterator​ ​Object that gives values one by one​

​iter()​ ​Creates an iterator​

​next()​ ​Gets the next value​


​Flow Chart​


al
h
hc
​Example 1: Using​​iter()​​and​​next()​
is
N
ith
eW

​ utput:​
O
​A​
​B​
​C​
od

​Example 2:​​How for loop thinks internally​


​This loop:​
​C

​PYTHON CODE​

​for letter in "ABC":​


​print(letter)​

​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()​ ​Creates an iterator​


is
​Iterator​ ​Object that gives values one by one​ ​Created using​​iter()​

​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.12​​StopIteration​
​When an iterator has no more values, Python raises​​StopIteration​​.​

​Example 1: Iterator ends​


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 a​​while​
A
N
​loop never becomes​​False​​.​

​Example 1: Infinite loop​


ith
eW

​Problem:​
od

​ umber starts as 1 =>​​condition is number <= 5​​=>​​number is never increased=> condition​


n
​always stays True . loop never stops​
​Correct version:​
​C

​ utput:​
O
​1​
​2​
​3​
​4​
​5​
​Chapter 9. Data Structure in Python​

​9.1 Lists in Python​


​A​​list​​is a data structure used to store multiple​​values in one variable.​

​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

​Output:​​['Rahul', 21, 'Python', 85.5]​

​List Properties Table​


od

​Property​ ​Meaning​ ​Example​


​C

​Ordered​ ​Items have fixed positions​ ​items[0]​

​Mutable​ ​Items can be changed​ ​items[1] = "new"​

​Allows duplicates​ ​Same value can appear multiple times​ ​[10, 10, 20]​

​Mixed data allowed​ ​Can store different data types​ ​["Aman", 20, True]​

​Indexed​ ​Every item has position number​ ​0, 1, 2...​


​Flow Chart​


h al
​9.1.1 Creating Lists​

hc
​Syntax​
is
N
​ .​ A
1 ​ list can store numbers, strings, Boolean values, or mixed values.​
ith

​2.​ ​An empty list can also be created.​


​3.​ ​Lists are useful when many related values need to be stored together.​

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

​Empty list​ ​items = []​

​Number list​ ​marks = [80, 90, 75]​

​String list​ ​names = ["Aman", "Riya"]​

​Mixed list​ ​data = ["Aman", 20, True]​


​Nested list​ ​matrix = [[1, 2], [3, 4]]​

al
​Using​​list()​ ​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 from​​0​.​
​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​

​students[0]​ ​First item​ ​"Aman"​

​students[1]​ ​Second item​ ​"Riya"​

​students[-1]​ ​Last item​ ​"Neha"​

​students[-2]​ ​Second last item​ ​"Kabir"​


​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

​Output: [70, 85, 90]​

​Updating Multiple Values​


od
​C

​Output:​​[70, 88, 95, 60]​


​9.1.4 List Methods​
​Method​ ​Purpose​ ​Example​ ​Result​

​append()​ ​Adds one item at the end​ ​[Link](40)​ ​Adds​​40​

​extend()​ ​Adds multiple items​ ​[Link]([50, 60])​ ​Adds​​50, 60​


​insert()​ ​Adds item at specific index​ ​[Link](1, 15)​ ​Adds​​15​​at index​​1​
​remove()​ ​Removes first matching value​ ​[Link](20)​ ​Removes​​20​
​pop()​ ​Removes item by index​ ​[Link](1)​ ​Removes item at index​​1​


​clear()​ ​Removes all items​ ​[Link]()​ ​Empty list​

al
​index()​ ​Returns index of value​ ​[Link](30)​ ​Gives position​
​count()​ ​Counts occurrences​ ​[Link](10)​ ​Count of​​10​

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

​Output:​​[10, 15, 30, 40]​

​Useful Functions with Lists​


​C

​Function​ ​Purpose​ ​Example​

​len()​ ​Counts items​ ​len(numbers)​

​sum()​ ​Adds numeric items​ ​sum(numbers)​

​min()​ ​Smallest value​ ​min(numbers)​

​max()​ ​Largest value​ ​max(numbers)​

​sorted()​ ​Returns sorted copy​ ​sorted(numbers)​


​9.1.5 Slicing​
​Syntax​
​list_name[start:end:step]​

​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

​[20, 30, 40]​


​[10, 20, 30]​
​[40, 50, 60]​
eW

​[10, 30, 50]​


​[60, 50, 40, 30, 20, 10]​

​Slicing Table​
od

​Code​ ​Meaning​ ​Result​

​numbers[1:4]​ ​Index​​1​​to before​​4​ ​[20, 30, 40]​


​C

​numbers[:3]​ ​Start to before index​​3​ ​[10, 20, 30]​

​numbers[3:]​ ​Index​​3​​to end​ ​[40, 50, 60]​

​numbers[::2]​ ​Every second item​ ​[10, 30, 50]​

​numbers[::-1]​ ​Reverse list​ ​[60, 50, 40, 30, 20, 10]​


​9.1.6 List Comprehensions​
​Syntax​
​new_list = [expression for item in sequence]​

​With condition:​

​new_list = [expression for item in sequence if 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 using​​if​​.​

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

​Output:​​[1, 4, 9, 16, 25]​

​Example 2: With Condition​


eW

​PYTHON CODE​
​numbers = [1, 2, 3, 4, 5, 6]​

​even_numbers = [number for number in numbers if number % 2 == 0]​


​print(even_numbers)​
od

​Output:​​[2, 4, 6]​

​9.1.7 Nested Lists​


​C

​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

​Updating Nested List Value​


eW

​PYTHON CODE​

​matrix = [​
​[1, 2, 3],​
od

​[4, 5, 6]​
​]​
​C

​ atrix[1][0] = 40​
m
​print(matrix)​

​Output: [[1, 2, 3], [40, 5, 6]]​


​9.1.8 Sorting and Reversing​
​ orting means arranging values in order. Reversing means changing the order from last to​
S
​first.​

​Sorting and Reversing Table​


​Operation​ ​Code​ ​Changes Original​ ​Result​
​List?​


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

​Reverse copy​ ​numbers[::-1]​ is ​No​ ​Returns reversed copy​

​Example 1​
N
​PYTHON CODE​
ith

​numbers = [40, 10, 30, 20]​


​[Link]()​
eW

​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()​​vs​​sorted()​
​Point​ ​sort()​ ​sorted()​

​Type​ ​List method​ ​Built-in function​

​Original list​ ​Changes original list​ ​Does not change original list​

​Return value​ ​Returns​​None​ ​Returns new sorted list​

​Usage​ ​[Link]()​ ​sorted(numbers)​


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

​[10, 20, 30]​

​9.1.9 Copying Lists​


eW

​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, use​​copy()​​, slicing, or​​list()​​.​
​Direct Assignment​
​PYTHON CODE​

​list1 = [10, 20, 30]​


​list2 = list1​

​[Link](40)​
​print(list1)​
​print(list2)​


al
​Output:​
​[10, 20, 30, 40]​

h
​[10, 20, 30, 40]​

hc
​Explanation:​

​ .​ l​ist2 = list1​​does not create a new list.​


1
​2.​ ​Both variables refer to the same list.​
is
​3.​ ​So changing​​list2​​also affects​​list1​​.​
N
ith
eW

​Real Copy Example​


od
​C

​Output:​

​[10, 20, 30]​

​[10, 20, 30, 40]​


​Copying Methods Table​
​Method​ ​Code​ ​Meaning​

​copy()​ ​new = [Link]()​ ​Creates shallow copy​

​Slicing​ ​new = old[:]​ ​Creates shallow copy​

​list()​ ​new = list(old)​ ​Creates shallow copy​

​Direct assignment​ ​new = old​ ​Not a real copy​


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

​Example 1: Shallow Copy​


​PYTHON CODE​

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


od

​list2 = [Link]()​
​list2[0][0] = 99​
​print(list1)​
​C

​print(list2)​

​Output:​
​[[99, 20], [30, 40]]​
​[[99, 20], [30, 40]]​

​ .​ l​[Link]()​​creates a new outer list.​


1
​2.​ ​But the inner lists are still shared.​
​3.​ ​So changing an inner list affects both lists.​
​Shallow Copy Diagram​


​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

​Output: [[10, 20], [30, 40]]​


​[[99, 20], [30, 40]]​
​Explanation:​
​1.​ ​[Link]()​​creates a fully independent copy.​
​2.​ ​Inner lists are also copied separately.​
od

​3.​ ​Changing​​list2​​does not affect​​list1​​.​

​Shallow Copy vs Deep Copy Table​


​C

​Point​ ​Shallow Copy​ ​Deep Copy​

​Outer list​ ​New copy​ ​New copy​

​Inner nested lists​ ​Shared​ ​New copy​

​Affects original nested data?​ ​Yes​ ​No​

​Common method​ ​copy()​ ​[Link]()​

​Useful for​ ​Simple lists​ ​Nested lists​


​Important List Operations Table​
​Operation​ ​Code​ ​Meaning​

​Create list​ ​items = [10, 20, 30]​ ​Creates list​

​Access item​ ​items[0]​ ​Gets first item​

​Update item​ ​items[1] = 25​ ​Changes second item​

​Add item​ ​[Link](40)​ ​Adds at end​


al
​Insert item​ ​[Link](1, 15)​ ​Adds at index​

​Remove item​ ​[Link](20)​ ​Removes value​

h
​Remove by index​ ​[Link](0)​ ​Removes by index​

hc
​Slice list​ ​items[1:3]​ ​Gets part of list​

​Sort list​ ​[Link]()​ is ​Sorts original list​

​Reverse list​ ​[Link]()​ ​Reverses original list​


N
​Copy list​ ​[Link]()​ ​Creates shallow copy​
ith

​Length​ ​len(items)​ ​Counts items​

​List Method Return Behavior​


eW

​Method​ ​Changes Original List?​ ​Returns​

​append()​ ​Yes​ ​None​


od

​extend()​ ​Yes​ ​None​

​insert()​ ​Yes​ ​None​


​C

​remove()​ ​Yes​ ​None​

​pop()​ ​Yes​ ​Removed item​

​clear()​ ​Yes​ ​None​

​sort()​ ​Yes​ ​None​

​reverse()​ ​Yes​ ​None​

​copy()​ ​No​ ​New list​


​9.2 Tuples in Python​
​A​​tuple​​is a data structure used to store multiple​​values in one variable.​

​Tuples are similar to lists, but the main difference is:​

​List -> mutable -> can be changed​

​Tuple -> immutable -> cannot be changed​

​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

​Output:​​('Rahul', 21, 'Python', 85.5)​

​Tuple Properties Table​


od

​Property​ ​Meaning​ ​Example​

​Ordered​ ​Items have fixed positions​ ​items[0]​


​C

​Immutable​ ​Items cannot be changed​ ​items[1] = 50​​not allowed​

​Allows duplicates​ ​Same value can appear more than once​ ​(10, 10, 20)​

​Mixed data allowed​ ​Can store different data types​ ​("Aman", 20, True)​

​Indexed​ ​Every item has position number​ ​0, 1, 2...​


​Flow Chart​


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

(​ 10, 20, 30)​


​('Aman', 'Riya', 'Kabir')​
​('Python', 100, 99.5, True)​
​()​
​Different Ways to Create Tuples​
​Type​ ​Example​

​Empty tuple​ ​items = ()​

​Number tuple​ ​marks = (80, 90, 75)​

​String tuple​ ​names = ("Aman", "Riya")​

​Mixed tuple​ ​data = ("Aman", 20, True)​


​Nested tuple​ ​matrix = ((1, 2), (3, 4))​

al
​Without parentheses​ ​items = 10, 20, 30​

h
​Using​​tuple()​ ​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 from​​0​.​
​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

​9.2.4 Tuple Slicing​


​Syntax​
​C

​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]​ ​Index​​1​​to before​​4​ ​(20, 30, 40)​
ith

​numbers[:3]​ ​Start to before index​​3​ ​(10, 20, 30)​

​numbers[3:]​ ​Index​​3​​to end​ ​(40, 50, 60)​


eW

​numbers[::2]​ ​Every second item​ ​(10, 30, 50)​

​numbers[::-1]​ ​Reverse tuple​ ​(60, 50, 40, 30, 20, 10)​


od

​9.2.5 Tuple Immutability​


​Syntax​
​C

​tuple_name[index] = new_value​
​This syntax is​​not allowed​​for 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​

​numbers = (10, 20, 30)​


​numbers[1] = 25​

​Output:​​TypeError: 'tuple' object does not support​​item assignment​

​Correct Way​
​Create a new tuple:​


al
​PYTHON CODE​

​numbers = (10, 20, 30)​

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

​9.2.6 Tuple with Mutable Items​


eW

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

​Output: ([10, 99], 'Python')​


​Explanation Table​
​Part​ ​Mutable or Immutable?​

​Outer tuple​ ​Immutable​

​Inner list​ ​Mutable​

​data[0] = [1, 2]​ ​Not allowed​

​data[0][1] = 99​ ​Allowed​


​9.2.7 Tuple Methods​

al
​Method​ ​Purpose​ ​Example​ ​Result​

h
​count()​ ​Counts how many times a value appears​ ​[Link](10)​ ​Count of​​10​

hc
​index()​ ​Returns index of first matching value​ ​[Link](20)​ ​Position of​​20​

​Useful Functions with Tuples​ is


​Function​ ​Purpose​ ​Example​
N
​len()​ ​Counts items​ ​len(numbers)​
ith

​sum()​ ​Adds numeric items​ ​sum(numbers)​

​min()​ ​Smallest value​ ​min(numbers)​


eW

​max()​ ​Largest value​ ​max(numbers)​

​sorted()​ ​Returns sorted list​ ​sorted(numbers)​

​9.2.8 Tuple Operations​


od

​Operation​ ​Code​ ​Meaning​


​C

​Concatenation​ ​tuple1 + tuple2​ ​Joins tuples​

​Repetition​ ​tuple1 * 3​ ​Repeats tuple​

​Membership​ ​value in tuple1​ ​Checks value exists​

​Length​ ​len(tuple1)​ ​Counts items​

​Slicing​ ​tuple1[1:4]​ ​Gets part of tuple​


​9.2.9 Tuple Packing​
​Syntax​
​tuple_name = value1, value2, value3​

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

​Output:​​('Aman', 21, 'Python')​


​<class 'tuple'>​
is
N
ith
eW

​9.2.10 Tuple Unpacking​


​Syntax​
od

​var1, var2, var3 = tuple_name​


​C

​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

​Output:​​ValueError: too many values to unpack​


eW

​Because the tuple has 3 values, but only 2 variables are given.​
od

​9.2.11 Extended Tuple Unpacking​


​Syntax​
​C

​first, *middle, last = tuple_name​

​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 values​​in a list, not a tuple.​

hc
​9.2.12 Named Tuples​
​Syntax​
is
N
​from collections import namedtuple​
​TupleName = namedtuple("TupleName", ["field1", "field2"])​
ith

​object_name = TupleName(value1, value2)​

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

​Access by index​ ​Access by name​


​student[0]​ ​[Link]​
​Less readable​ ​More readable​
​Immutable​ ​Immutable​

​9.2.13 Tuple vs List​


al
​Point​ ​List​ ​Tuple​

​Brackets​ ​Uses​​[]​ ​Uses​​()​

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

​Operation​ ​Code​ ​Meaning​

​Create tuple​ ​items = (10, 20, 30)​ ​Creates tuple​


eW

​Single-item tuple​ ​item = (10,)​ ​Creates tuple with one item​


​Access item​ ​items[0]​ ​Gets first item​
​Slice tuple​ ​items[1:3]​ ​Gets part of tuple​
​Count item​ ​[Link](10)​ ​Counts value​
od

​Find index​ ​[Link](20)​ ​Finds position​


​Pack tuple​ ​data = "Aman", 21​ ​Packs values​
​Unpack tuple​ ​name, age = data​ ​Extracts values​
​C

​Concatenate​ ​a + b​ ​Joins tuples​


​Repeat​ ​a * 2​ ​Repeats tuple​
​Check membership​ ​10 in items​ ​Returns​​True​​or​​False​
​Convert list to tuple​ ​tuple(my_list)​ ​Creates tuple​
​Convert tuple to list​ ​list(my_tuple)​ ​Creates list​
​9.3 Dictionaries in Python​
​A​​dictionary​​is a data structure used to store data in​​key-value pairs​​.​

​Syntax​


h al
​ .​
1 ​ dictionary stores data using​​keys​​and​​values​​.​
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)​

​Output:​​{'name': 'Aman', 'age': 21, 'course': 'Python'}​


​Dictionary Structure​


al
​Dictionary Properties Table​

h
​Property​ ​Meaning​ ​Example​

hc
​Key-value based​ ​Stores data as pairs​ ​"name": "Aman"​

​Mutable​ ​Can be changed​ ​student["age"] = 22​

​Ordered​
is
​Keeps insertion order​ ​Python 3.7+​
N
​Unique keys​ ​Duplicate keys are not allowed​ ​Last value replaces old value​

​Fast lookup​ ​Values are accessed using keys​ ​student["name"]​


ith

​Mixed values allowed​ ​Values can be any data type​ ​string, int, list, tuple, dict​
eW

​9.3.1 Creating Dictionaries​


​Syntax​
od
​C

​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
​Using​​dict()​ ​student = dict(name="Aman", age=21)​
​Nested dictionary​ ​students = {"s1": {"name": "Aman"}}​
N
​Dictionary with list value​ ​data = {"marks": [80, 90, 85]}​
ith

​Dictionary with tuple key​ ​points = {(10, 20): "A"}​

​9.3.2 Dictionary Keys and Values​


eW

​Syntax​
od
​C

​Explanation​
​ .​
1 ​ ​​key​​is used to identify a value.​
A
​2.​ ​A​​value​​is 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"​

​Number key​ ​Yes​ ​1: "One"​

​Tuple key​ ​Yes​


is
​(10, 20): "Point"​
N
​List key​ ​No​ ​[1, 2]: "Value"​

​Duplicate keys​ ​Not useful​ ​Last value is kept​


ith

​Duplicate Key Example​


eW
od
​C

​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 gives​​KeyError​​.​

h
hc
is
N
ith
eW

​Example 1​
od
​C

​ utput:​
O
​Aman​
​21​
​Accessing Table​
​Code​ ​Meaning​ ​Result​

​student["name"]​ ​Access name​ ​"Aman"​

​student["age"]​ ​Access age​ ​21​

​student["course"]​ ​Access course​ ​"Python"​

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

​9.3.4 Updating Values​


ith

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

​Output: {'name': 'Aman', 'age': 22, 'course': 'Python'}​


​9.3.5 Dictionary Methods​
​ ictionary methods are built-in operations used to access, update, remove, copy, and​
D
​manage dictionary data.​

​Assume this dictionary:​

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

​values()​ ​Returns all values​ ​[Link]()​ ​dict_values(['Aman', 21, 'Python'])​


ith

​items()​ ​ eturns key-value​


R ​[Link]()​ ​dict_items([('name','Aman'),...])​
​pairs​
eW

​get()​ ​Returns value safely​ ​[Link]("name")​ ​"Aman"​

​update()​ ​ dds or updates​


A ​ [Link]({"age":​
s ​Updates age​
​data​ ​22})​
od

​pop()​ ​ emoves key and​


R ​[Link]("age")​ ​Returns​​21​
​returns value​

​popitem()​ ​ emoves last​


R ​[Link]()​ ​Removes last pair​
​C

​inserted pair​

​clear()​ ​Removes all items​ ​[Link]()​ ​{}​

​copy()​ ​ reates shallow​


C ​new = [Link]()​ ​New dictionary​
​copy​

​setdefault()​ G
​ ets value or adds​ ​ [Link]("city",​
s ​Adds city if missing​
​default​ ​"Delhi")​

​fromkeys()​ ​ reates dictionary​


C ​[Link](["a","b"], 0)​ ​{'a': 0, 'b': 0}​
​from keys​
​Method Behavior Table​
​Method​ ​Changes Original​ ​Returns​
​Dictionary?​

​keys()​ ​No​ ​View of keys​

​values()​ ​No​ ​View of values​

​items()​ ​No​ ​View of key-value pairs​

​get()​ ​No​ ​Value or default​


al
​update()​ ​Yes​ ​None​

​pop()​ ​Yes​ ​Removed value​

h
​popitem()​ ​Yes​ ​Removed key-value pair​

hc
​clear()​ ​Yes​ ​None​

​copy()​ ​No​ is ​New shallow copy​

​setdefault()​ ​May change​ ​Existing/default value​


N
​fromkeys()​ ​Creates new dictionary​ ​New dictionary​
ith

​9.3.6​​get()​​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 returns​​None​​by default.​
​4.​ ​We can also provide our own default value.​
​5.​ ​get()​​avoids​​KeyError​​.​
​Flow Chart​


al
​Example 1​

h
​PYTHON CODE​

hc
​student = {​
​"name": "Aman",​
​"age": 21​ is
​}​
N
​print([Link]("name"))​
​print([Link]("marks"))​
ith

​print([Link]("marks", "Not available"))​

​ utput:​
O
​Aman​
eW

​None​
​Not available​

​[]​​vs​​get()​​Table​
od

​Access Method​ ​If Key Exists​ ​If Key Missing​

​student["name"]​ ​ eturns​
R ​Gives​​KeyError​
​value​
​C

​[Link]("name")​ ​ eturns​
R ​Returns​​None​
​value​

​[Link]("marks", 0)​ ​ eturns​


R ​ eturns default​
R
​value​ ​value​
​9.3.7 Removing Dictionary Items​
​Syntax​
​ [Link](key)​
d
​[Link]()​
​del dictionary[key]​
​[Link]()​

​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.​ ​del​​removes a specific key.​

hc
​4.​ ​clear()​​removes all items.​

​Removing Items Table​


​Method / Keyword​ ​Purpose​
is ​Example​
N
​pop(key)​ ​Removes specific key​ ​[Link]("age")​
ith

​popitem()​ ​Removes last pair​ ​[Link]()​

​del​ ​Deletes specific key​ ​del student["age"]​


eW

​clear()​ ​Empties dictionary​ ​[Link]()​

​Example 1​
od

​PYTHON CODE​
​student = {​
​"name": "Aman",​
​C

​"age": 21,​
​"course": "Python"​
​}​
​[Link]("age")​
​print(student)​

​Output: {'name': 'Aman', 'course': 'Python'}​


​9.3.8 Looping Through Dictionaries​
​Syntax​


​Explanation​

al
​ .​
1 ​ dictionary can be looped through using​​for​​.​
A

h
​2.​ ​By default, looping over a dictionary gives keys.​
​3.​ ​Use​​values()​​to loop through values.​

hc
​4.​ ​Use​​items()​​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
​ .​ i​n​​checks whether a key exists in the dictionary.​
1
​2.​ ​It checks keys, not values.​

hc
​3.​ ​It returns​​True​​or​​False​​.​

​Example 1​ is
N
ith
eW

​ utput:​
O
od

​True​
​False​

​Membership Table​
​C

​Code​ ​Meaning​

​"name" in student​ ​Checks if key exists​

​"marks" not in student​ ​Checks if key does not exist​

​"Aman" in student​ ​Checks key, not value​


​9.3.10 Nested Dictionaries​
​Syntax​


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

​Updating Nested Dictionary​


od
​C

​Output: {'student1': {'name': 'Aman', 'age': 22}}​


​9.3.11 Dictionary Comprehensions​
​Syntax​

​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

​Store in new dictionary​

​Example 1​
​C

​PYTHON CODE​

​numbers = [1, 2, 3, 4]​


​squares = {number: number * number for number in numbers}​
​print(squares)​

​Output:​

​{1: 1, 2: 4, 3: 9, 4: 16}​
​Example 2: With Condition​
​PYTHON CODE​

​numbers = [1, 2, 3, 4, 5, 6]​


​even_squares = {number: number * number for number in numbers if number % 2 == 0}​
​print(even_squares)​

​Output: {2: 4, 4: 16, 6: 36}​


​Dictionary Comprehension Parts​

al
​Part​ ​Meaning​

h
​number​​before​​:​ ​Key​

hc
​number * number​ ​Value​

​for number in numbers​ ​Loop​

​if number % 2 == 0​
is
​Optional condition​
N
​9.3.12 Merging Dictionaries​
ith

​Merging means combining two or more dictionaries.​


eW

​Example 1: Using​​update()​
​PYTHON CODE​

​student = {​
od

​"name": "Aman",​
​"age": 21​
​}​
​C

​extra = {​
​"course": "Python",​
​"city": "Delhi"​
​}​
​[Link](extra)​
​print(student)​

​Output: {'name': 'Aman', 'age': 21, 'course': 'Python', 'city': 'Delhi'}​


​Example 2: Using​​|​
​PYTHON CODE​

​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'}​

​Same Key During Merge​


is
N
​If both dictionaries have the same key, the second dictionary value wins.​
ith

​PYTHON CODE​

​a = {"name": "Aman", "age": 21}​


eW

​b = {"age": 22, "course": "Python"}​


​result = a | b​
​print(result)​
od

​Output: {'name': 'Aman', 'age': 22, 'course': 'Python'}​

​9.3.13 Copying Dictionaries​


​C

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

​student1 = {"name": "Aman", "age": 21}​


​student2 = student1​

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

​student1 = {"name": "Aman", "age": 21}​


is
​student2 = [Link]()​
N
ith

​student2["age"] = 22​
​print(student1)​
​print(student2)​
eW

​Output:​

​{'name': 'Aman', 'age': 21}​


od

​{'name': 'Aman', 'age': 22}​

​Copying Table​
​C

​Method​ ​ reates New​


C ​Notes​
​Dictionary?​

​dict2 = dict1​ ​No​ ​ ame dictionary​


S
​reference​

​dict2 = [Link]()​ ​Yes​ ​Shallow copy​

​dict2 = dict(dict1)​ ​Yes​ ​Shallow copy​


​9.3.14 Dictionary vs List​
​Point​ ​List​ ​Dictionary​

​Data storage​ ​Stores values​ ​Stores key-value pairs​

​Access by​ ​Index​ ​Key​

​Brackets​ ​[]​ ​{}​

​Best for​ ​Ordered collection of values​ ​Labeled/structured data​


al
​Example​ ​["Aman", 21]​ ​{"name": "Aman", "age": 21}​

h
​9.3.15 Important Dictionary Operations​

hc
​Operation​ ​Code​ ​Meaning​

​Create dictionary​

​Access value​ ​data["name"]​


is
​data = {"name": "Aman"}​ ​Creates dictionary​

​Gets value by key​


N
​Safe access​ ​[Link]("name")​ ​Avoids​​KeyError​
ith

​Update value​ ​data["name"] = "Rahul"​ ​Changes value​

​Add new pair​ ​data["age"] = 21​ ​Adds key-value pair​


eW

​Remove key​ ​[Link]("age")​ ​Removes key​

​Check key​ ​"name" in data​ ​Returns​​True​​or​​False​

​Get keys​ ​[Link]()​ ​Returns all keys​


od

​Get values​ ​[Link]()​ ​Returns all values​

​Get pairs​ ​[Link]()​ ​ eturns key-value​


R
​C

​pairs​

​Merge dictionaries​ ​`dict1​ ​dict2`​

​Copy dictionary​ ​[Link]()​ ​Creates shallow copy​

​Empty dictionary​ ​[Link]()​ ​Removes all items​


​9.4 Sets in Python​
​A​​set​​is a data structure used to store multiple​​unique​​values.​

​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

​numbers = {10, 20, 30, 40}​


​print(numbers)​
eW

​{40, 10, 20, 30} : The output order may look different because sets are unordered.​

​Set Properties Table​


od

​Property​ ​Meaning​ ​Example​

​Unordered​ ​Items have no fixed index​ ​Cannot use​​items[0]​


​C

​Unique values​ ​Duplicate values are removed​ ​{10, 10, 20}​​becomes​​{10, 20}​

​Mutable​ ​Items can be added/removed​ ​[Link](50)​

​Unindexed​ ​No indexing/slicing​ ​items[1]​​not allowed​

​Mixed data allowed​ ​Can store different immutable types​ ​{10, "Aman", True}​

​Fast membership check​ ​Good for checking existence​ ​10 in numbers​


​9.4.1 Creating Sets​
​Syntax​
​set_name = {item1, item2, item3}​

​ .​ 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 using​​set()​​.​​{}​​creates​​an 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

​{10, 20, 30}​


​{'Aman', 'Kabir', 'Riya'}​
​{True, 99.5, 100, 'Python'}​
​set()​
​Order may differ in output.​
od

​Different Ways to Create Sets​


​Type​ ​Example​
​C

​Empty set​ ​items = set()​


​Number set​ ​marks = {80, 90, 75}​
​String set​ ​names = {"Aman", "Riya"}​
​Mixed set​ ​data = {"Aman", 20, True}​
​From list​ ​items = set([10, 20, 10])​
​From string​ ​letters = set("ABC")​

​From tuple​ ​items = set((10, 20, 30))​


​Empty Set Important Point​
​PYTHON CODE​

​a = {}​
​b = set()​
​print(type(a))​
​print(type(b))​

​ utput:​
O
​<class 'dict'>​


al
​<class 'set'>​

​9.4.2 Unique Values​

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

​Output:​​{40, 10, 20, 30} => Duplicate​​10​​and​​20​​are removed.​

​Removing Duplicates from a List​


​C

​PYTHON CODE​
​numbers = [10, 20, 10, 30, 20, 40]​
​unique_numbers = set(numbers)​
​print(unique_numbers)​

​Output:​​{40, 10, 20, 30}​


​9.4.3 Set Elements Must Be Immutable​
​Syntax​
​set_name = {immutable_value1, immutable_value2}​

​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

​invalid_set = {[1, 2], [3, 4]}​

​Output: TypeError: unhashable type: 'list'​

​Allowed vs Not Allowed Table​


od

​Value Type​ ​Allowed in Set?​ ​Example​

​Integer​ ​Yes​ ​{10, 20}​


​C

​Float​ ​Yes​ ​{10.5, 20.5}​


​String​ ​Yes​ ​{"A", "B"}​
​Boolean​ ​Yes​ ​{True, False}​
​Tuple​ ​Yes, if tuple contains immutable items​ ​{(1, 2)}​
​List​ ​No​ ​{[1, 2]}​
​Dictionary​ ​No​ ​{{"a": 1}}​

​Set​ ​No​ ​{{1, 2}}​


​9.4.4 Accessing Set Values​
​Syntax​

​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 using​​in​​.​
​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

​Output:​​TypeError: 'set' object is not subscriptable​

​Accessing Table​
​C

​Operation​ ​Allowed?​ ​Example​

​Looping​ ​Yes​ ​for item in items:​


​Membership check​ ​Yes​ ​"Python" in items​
​Indexing​ ​No​ ​items[0]​
​Slicing​ ​No​ ​items[1:3]​
​9.4.5 Checking Membership​
​Syntax​

​Explanation​


​ .​
1 ​ ets are very useful for checking whether a value exists.​
S

al
​2.​ ​in​​returns​​True​​if value exists.​
​3.​ ​not in​​returns​​True​​if 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

​9.4.6 Adding Set Items​


​Syntax​
od
​C

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

​Output:​​{40, 10, 50, 20, 60, 30}​


​20​​was already present, so it is not duplicated.​

al
​add()​​vs​​update()​

h
​Method​ ​Adds​ ​Example​

hc
​add()​ ​One item​ ​[Link](10)​

​update()​ ​Multiple items​ ​[Link]([10, 20])​


is
​9.4.7 Removing Set Items​
N
​PYTHON CODE​
ith

​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

​3.​ ​pop()​​removes a random item because sets are unordered.​


​4.​ ​clear()​​removes all items.​

​Example:​
​C

​PYTHON CODE​
​numbers = {10, 20, 30, 40}​
​[Link](20)​
​[Link](50)​
​print(numbers)​

​Output:​​{40, 10, 30}​

​discard(50)​​does not give an error even though​​50​​is missing.​


​Removing Methods Table​
​Method​ ​Purpose​ ​If Value Missing​

​remove(value)​ ​Removes specific value​ ​Gives​​KeyError​

​discard(value)​ ​Removes specific value​ ​No error​

​pop()​ ​Removes random item​ ​Gives error if set is empty​

​clear()​ ​Removes all items​ ​No error​


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

​Union​ ​`a​ ​b`​ ​[Link](b)​ ​ ll unique values​


A
​from both sets​
​Intersection​ ​a & b​ ​[Link](b)​ ​Common values​ ​{3}​
​C

​Difference​ ​a - b​ ​[Link](b)​ ​Values in​​a​​but not in​​b​ ​{1, 2}​


​ ymmetric​
S ​a ^ b​ ​a.symmetric_difference(b)​ ​Values not common in both​ ​{1, 2, 4, 5}​
​difference​

​Subset​ ​a <= b​ ​[Link](b)​ ​ hecks if all items of​​a​​are​


C ​False​
​in​​b​
​Superset​ ​a >= b​ ​[Link](b)​ ​ hecks if​​a​​contains all​
C ​False​
​items of​​b​
​Disjoint​ ​ o​
N ​[Link](b)​ ​ hecks if no common​
C ​False​
​symbol​ ​items exist​
​Example 1​
​PYTHON CODE​
​a = {1, 2, 3}​
​b = {3, 4, 5}​
​print(a | b)​
​print(a & b)​
​print(a - b)​
​print(a ^ b)​


​ 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

​2.​ ​It returns all unique values from both sets.​


​3.​ ​Duplicate/common values appear only once.​

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

​ .​ I​ntersection returns only common values.​


1
​2.​ ​Values must exist in both sets.​


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 - b​​and​​b - a​​can 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)​

​Output: {1, 2, 4, 5}​

​9.4.13 Subset, Superset, & Disjoint Sets​


is
N
​Syntax​
ith

​ [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 of​​a​​are in​​b​ ​{1, 2} <= {1, 2, 3}​ ​True​

​Superset​ ​b​​contains all items of​​a​ ​{1, 2, 3} >= {1, 2}​ ​True​

​Disjoint​ ​No common items​ ​{1, 2}.isdisjoint({3, 4})​ ​True​

​9.4.14 Set Methods​


al
​Method​ ​Purpose​ ​Example​ ​Result / Effect​

​add()​ ​Adds one item​ ​[Link](10)​ ​Adds​​10​

h
​update()​ ​Adds multiple items​ ​[Link]([10, 20])​ ​Adds all items​

hc
​remove()​ ​Removes item​ ​[Link](10)​ ​Error if missing​

​discard()​ ​Removes item safely​ is ​[Link](10)​ ​No error if missing​

​pop()​ ​Removes random item​ ​[Link]()​ ​Returns removed item​


N
​clear()​ ​Removes all items​ ​[Link]()​ ​Empty set​
ith

​copy()​ ​Creates shallow copy​ ​new = [Link]()​ ​New set​

​union()​ ​Combines sets​ ​[Link](b)​ ​New set​


eW

​intersection()​ ​Common items​ ​[Link](b)​ ​New set​

​difference()​ ​Items in first but not second​ ​[Link](b)​ ​New set​

​ ymmetric_differe​
s ​Items not common​ ​a.symmetric_difference(b)​ ​New set​
​nce()​
od

i​ntersection_updat​ ​Keeps only common items​ ​a.intersection_update(b)​ ​Changes​​a​


​e()​
​C

​ ifference_update(​ R
d ​ emoves items found in other​ ​a.difference_update(b)​ ​Changes​​a​
​)​ ​set​

​ ymmetric_differe​
s ​Keeps non-common items​ ​ .symmetric_difference_u​ ​Changes​​a​
a
​nce_update()​ ​pdate(b)​

​issubset()​ ​Checks subset​ ​[Link](b)​ ​True​​/​False​

​issuperset()​ ​Checks superset​ ​[Link](b)​ ​True​​/​False​

​isdisjoint()​ ​Checks no common items​ ​[Link](b)​ ​True​​/​False​


​9.4.15 Set Operators​
​Set operations can also be done using operators.​

​Operator​ ​Meaning​ ​Same As​

​`​ ​`​ ​Union​

​&​ ​Intersection​ ​[Link](b)​


​-​ ​Difference​ ​[Link](b)​

al
​^​ ​Symmetric difference​ ​a.symmetric_difference(b)​

h
​<=​ ​Subset check​ ​[Link](b)​

hc
​<​ ​Proper subset check​ ​a < b​

​>=​ ​Superset check​ ​[Link](b)​

​>​ ​Proper superset check​


is ​a > b​
N
​9.4.16 Updating Sets with Operations​
ith

​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 assignment​​does 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​

​b = a​ ​No​ ​Same set reference​


ith

​b = [Link]()​ ​Yes​ ​Shallow copy​


​b = set(a)​ ​Yes​ ​New set​

​9.4.18 Frozen Sets​


eW

​A​​frozenset​​is an immutable version of a set.​


​Syntax​
od

​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

​dictionary keys or set elements.​


​3.​ ​Frozensets support read-only set operations like union, intersection, and difference.​

​PYTHON CODE​
​numbers = frozenset([10, 20, 30])​
​print(numbers)​
​print(type(numbers))​

​Output:​​frozenset({10, 20, 30})​


​<class 'frozenset'>​
​Invalid Operation​
​PYTHON CODE​
​numbers = frozenset([10, 20, 30])​
​[Link](40)​

​Output:​​AttributeError: 'frozenset' object has no​​attribute 'add'​


​Set vs Frozen Set Table​
​Point​ ​Set​ ​Frozenset​


​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

​Method​ ​Available in Frozenset?​ ​Reason​

​union()​ ​Yes​ ​Does not modify original​


eW

​intersection()​ ​Yes​ ​Does not modify original​


​difference()​ ​Yes​ ​Does not modify original​
​symmetric_difference()​ ​Yes​ ​Does not modify original​
​issubset()​ ​Yes​ ​Only checks​
od

​issuperset()​ ​Yes​ ​Only checks​


​isdisjoint()​ ​Yes​ ​Only checks​
​add()​ ​No​ ​Modifies set​
​C

​remove()​ ​No​ ​Modifies set​


​discard()​ ​No​ ​Modifies set​
​clear()​ ​No​ ​Modifies set​
​update()​ ​No​ ​Modifies set​
​9.4.19 Set Comprehensions​
​Syntax​
​new_set = {expression for item in sequence}​
​With condition:​
​new_set = {expression for item in sequence if condition}​

​ .​
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 do​​not create duplicate set values.​
ith

​Example 2: With Condition​


eW

​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

​Output: {2, 4, 6}​


​List Comprehension vs Set Comprehension​
​C

​Point​ ​List Comprehension​ ​Set Comprehension​

​Brackets​ ​[]​ ​{}​

​Allows duplicates​ ​Yes​ ​No​

​Ordered​ ​Yes​ ​No fixed order​

​Result type​ ​List​ ​Set​

​Example​ ​[x for x in data]​ ​{x for x in data}​


​9.4.20 Set Conversion​
​Syntax​
​set(iterable)​

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

​numbers = [10, 20, 10, 30, 20]​


is
​unique_numbers = set(numbers)​
N
​print(unique_numbers)​
ith

​print(list(unique_numbers))​

​ utput:​
O
​{10, 20, 30}​
eW

​[10, 20, 30]​


​Order may differ.​

​Conversion Table​
od

​Conversion​ ​Code​ ​Result Type​

​List to set​ ​set([1, 2, 2])​ ​Set​


​C

​Tuple to set​ ​set((1, 2, 2))​ ​Set​

​String to set​ ​set("banana")​ ​ et of unique​


S
​characters​

​Set to list​ ​list({1, 2, 3})​ ​List​

​Set to tuple​ ​tuple({1, 2, 3})​ ​Tuple​


​9.4.21 Set vs List vs Tuple​
​Point​ ​List​ ​Tuple​ ​Set​

​Brackets​ ​[]​ ​()​ ​{}​

​Ordered​ ​Yes​ ​Yes​ ​No fixed order​

​Mutable​ ​Yes​ ​No​ ​Yes​

​Allows duplicates​ ​Yes​ ​Yes​ ​No​

​Indexing​ ​Yes​ ​Yes​ ​No​


al
​Slicing​ ​Yes​ ​Yes​ ​No​

​Best for​ ​ hangeable​


C ​Fixed ordered data​ ​ nique unordered​
U
​ordered data​ ​data​

h
​Example​ ​[10, 20]​ ​(10, 20)​ ​{10, 20}​

hc
​Important Set Operations Table​
​Operation​ ​Code​
is ​Meaning​

​Create set​ ​items = {10, 20, 30}​ ​Creates set​


N
​Empty set​ ​items = set()​ ​Creates empty set​
ith

​Add one item​ ​[Link](40)​ ​Adds one value​

​Add multiple items​ ​[Link]([40, 50])​ ​Adds many values​

​Remove safely​ ​[Link](20)​ ​Removes without error​


eW

​Remove with error​ ​[Link](20)​ ​Error if missing​

​Random remove​ ​[Link]()​ ​Removes random item​

​Empty set​ ​[Link]()​ ​Removes all items​


od

​Check value​ ​10 in items​ ​Membership check​

​Union​ ​`a​ ​b`​


​C

​Intersection​ ​a & b​ ​Common values​

​Difference​ ​a - b​ ​Values in​​a​, not in​​b​

​Symmetric difference​ ​a ^ b​ ​Non-common values​

​Subset​ ​a <= b​ ​Checks subset​

​Superset​ ​a >= b​ ​Checks superset​

​Copy set​ ​[Link]()​ ​Creates shallow copy​

​Frozen set​ ​frozenset(items)​ ​Immutable set​


​9.5 Collections Module in Python​
​ he​​collections​​module provides special data structures​​that are more powerful than normal​
T
​lists, tuples, dictionaries, and sets.​

​Syntax​


h al
hc
​ .​
1 ​ ollections​​is 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

​Counter​ ​Counting frequency​

​defaultdict​ ​Dictionary with default values​


eW

​OrderedDict​ ​Dictionary that manages order​

​deque​ ​Fast queue and stack operations​

​ChainMap​ ​Combines multiple dictionaries as one view​


od

​9.5.1​​Counter​
​C

​Counter​​is used to count how many times each value​​appears.​

​Syntax​
​Explanation​
​ .​
1 ​ ounter​​counts 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

​from collections import Counter​


​letters = "banana"​
​count = Counter(letters)​
eW

​print(count)​

​Output:​​Counter({'a': 3, 'n': 2, 'b': 1})​


od

​Example 2​
​PYTHON CODE​
​C

​from collections import Counter​


​items = ["apple", "banana", "apple", "mango", "banana", "apple"]​
​count = Counter(items)​
​print(count)​

​Output:​​Counter({'apple': 3, 'banana': 2, 'mango': 1})​


​Common​​Counter​​Methods​
​Method​ ​Meaning​ ​Example​

​most_common()​ ​Returns most frequent items​ ​count.most_common()​

​most_common(n)​ ​Returns top​​n​​frequent items​ ​count.most_common(2)​

​elements()​ ​ eturns items repeated by​


R ​[Link]()​
​count​


​update()​ ​Adds more counts​ ​[Link](data)​

al
​subtract()​ ​Subtracts counts​ ​[Link](data)​

h
hc
​9.5.2​​defaultdict​
​defaultdict​​is a dictionary that gives a default value​​when a key does not exist.​

​Syntax​
is
N
f​rom collections import defaultdict​
​dictionary_name = defaultdict(default_type)​
ith

​Explanation​
eW

​ .​
1 ​ ormal dictionaries give​​KeyError​​if a key does not​​exist.​
N
​2.​ ​defaultdict​​avoids this problem.​
​3.​ ​It automatically creates a default value for missing keys.​
​4.​ ​Common default types are​​int​​,​​list​​, and​​set​​.​
od

​Flow Chart​
​C
​Example 1: Using​​int​
​PYTHON CODE​
​from collections import defaultdict​
​marks = defaultdict(int)​
​marks["math"] += 10​
​marks["science"] += 20​
​print(marks)​

​ utput:​​defaultdict(<class 'int'>, {'math': 10, 'science':​​20})​


O


​Here, missing keys start with default value​​0​.​

al
​Common Default Types​

h
​Default Type​ ​Default Value​ ​Common Use​

hc
​int​ ​0​ ​Counting​

​list​ ​[]​ ​Grouping values​

​set​ ​set()​
is
​Grouping unique values​

​str​ ​""​ ​Empty text​


N
ith

​Example 2: Using​​list​
​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

​Output:​​defaultdict(<class 'list'>, {'Python': ['Aman',​​'Riya'], 'Java': ['Kabir']})​

​Normal Dictionary vs​​defaultdict​


​Point​ ​Normal Dictionary​ ​defaultdict​

​Missing key​ ​Gives​​KeyError​ ​Creates default value​


​Best for​ ​Simple key-value data​ ​Grouping/counting​

​Needs manual checking​ ​Yes​ ​No​


​9.5.3​​OrderedDict​
​OrderedDict​​is a dictionary that remembers and manages​​the order of items.​

​Syntax​
​PYTHON CODE​
​from collections import OrderedDict​
​dictionary_name = OrderedDict()​


al
​Explanation​

h
​ .​
1 ​ rderedDict​​stores key-value pairs in order.​
O
​2.​ ​Normal dictionaries also preserve insertion order in modern Python.​

hc
​3.​ ​OrderedDict​​is still useful because it has extra order-related​​methods.​
​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

​Output:​​OrderedDict([('name', 'Aman'), ('age', 21),​​('course', 'Python')])​

​Useful​​OrderedDict​​Methods​
​C

​Method​ ​Meaning​ ​Example​

​move_to_end(key)​ ​Moves key to the end​ ​data.move_to_end("name")​

​ ove_to_end(key,​
m ​ oves key to the​
M ​ ata.move_to_end("name",​
d
​last=False)​ ​beginning​ ​last=False)​

​popitem()​ ​Removes last item​ ​[Link]()​

​popitem(last=False)​ ​Removes first item​ ​[Link](last=False)​


​Normal Dictionary vs​​OrderedDict​
​Point​ ​Normal Dictionary​ ​OrderedDict​

​ reserves insertion​
P ​Yes, in modern Python​ ​Yes​
​order​

​Move key to end​ ​Not directly​ ​Yes​

​Remove first item easily​ ​Not directly​ ​Yes​

​Best for​ ​General dictionary use​ ​Order-sensitive dictionary logic​


al
​9.5.4​​deque​

h
hc
​deque​​means​​double-ended queue​​.​

​It allows fast adding and removing from both ends.​

​Syntax​
is
N
​from collections import deque​
ith

​deque_name = deque(iterable)​

​ .​
1 ​ eque​​is used when we need fast insert/remove from​​left and right.​
d
​2.​ ​It works like a queue and stack.​
eW

​3.​ ​Lists are slower when removing from the beginning.​


​4.​ ​deque​​is useful for queues, recent history, undo operations,​​and sliding windows.​

​Example 1​
od

​PYTHON CODE​
​from collections import deque​
​numbers = deque([10, 20, 30])​
​C

​[Link](40)​
​[Link](5)​
​print(numbers)​

​Output:​​deque([5, 10, 20, 30, 40])​

​Common​​deque​​Methods​
​Method​ ​Meaning​ ​Example​

​append()​ ​Adds item at right end​ ​[Link](10)​


​appendleft()​ ​Adds item at left end​ ​[Link](10)​
​pop()​ ​Removes item from right end​ ​[Link]()​
​popleft()​ ​Removes item from left end​ ​[Link]()​
​extend()​ ​Adds multiple items at right​ ​[Link]([1, 2])​
​extendleft()​ ​Adds multiple items at left​ ​[Link]([1, 2])​
​rotate(n)​ ​Rotates items​ ​[Link](1)​


al
​clear()​ ​Removes all items​ ​[Link]()​

​List vs​​deque​

h
​Point​ ​List​ ​deque​

hc
​Add at end​ ​Fast​ ​Fast​

​Remove from end​ ​Fast​ is ​Fast​

​Add at beginning​ ​Slower​ ​Fast​


N
​Remove from beginning​ ​Slower​ ​Fast​
ith

​Best for​ ​General storage​ ​Queue operations​

​9.5.5​​ChainMap​
eW

​ChainMap​​combines multiple dictionaries into one view.​

​Syntax​
od

f​rom collections import ChainMap​


​chain_name = ChainMap(dict1, dict2, dict3)​
​C

​ .​
1 ​ hainMap​​groups 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 in​​user_settings​​, so​​"dark"​​is used.​
1
​2.​ ​"language"​​is not in​​user_settings​​, so Python checks​​defaults​​.​
ith
eW

​Useful​​ChainMap​​Features​
​Feature​ ​Meaning​ ​Example​

​maps​ ​Shows all dictionaries​ ​[Link]​


od

​new_child()​ ​Adds new dictionary in front​ ​settings.new_child({...})​

​parents​ ​Removes first dictionary from view​ ​[Link]​


​C
​Chapter 10. Functions in Python​
​ ​​function​​is a reusable block of code that performs​​a specific task. Instead of writing the​
A
​same code again and again, we write it once inside a function and call it whenever needed.​

​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

​5.​ ​Python has built-in functions and user-defined functions.​

​Built-in vs User-defined Functions​


​Type​ ​Meaning​ ​Example​

​Built-in function​ ​Already provided by Python​ ​print()​​,​​len()​​,​​type()​

​User-defined function​ ​Created by programmer​ ​def greet():​


​Flow Chart​
​Start​
​|​
​v​
​Function is defined​
​|​
​v​
​Function is called​
​|​
​v​


​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

​10.2 Defining Functions​


​Syntax​
eW
od

​ .​
1 ​ ef​​is used to define a function.​
d
​2.​ ​The function name comes after​​def​​.​
​C

​3.​ ​Parentheses​​()​​are required.​


​4.​ ​A colon​​:​​marks the start of the function body.​
​5.​ ​The function body must be indented.​
​PYTHON CODE​
​def say_hello():​
​print("Hello")​

​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, use​​pass​​.​

h
​PYTHON CODE​

hc
​def future_function():​
​pass​

​10.3 Calling Functions​


is
N
​Syntax​
ith

​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​
​ ​​parameter​​is a variable written inside the function​​definition. 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,​​name​​is a parameter.​
​10.5 Arguments​
​An​​argument​​is the actual value passed to a function​​during 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​

​Parameter​ ​Function definition​ ​Variable that receives value​

​Argument​ ​Function call​


is
​Actual value passed​

​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

​10.6 Positional Arguments​


​Positional arguments are matched based on their position.​

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

​10.7 Return Values​


od

​A​​return value​​is the result sent back by a function.​


​C

​Syntax​
​def function_name():​

​return value​

​ .​
1 r​ eturn​​sends a value back to the place where the function was called.​
​2.​ ​A function can return one value or multiple values.​
​3.​ ​After​​return​​, the function stops executing.​
​4.​ ​If there is no​​return​​, Python returns​​None​​automatically.​
​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​

​Example 2: Function without​​return​


od

​PYTHON CODE​
​def greet():​
​print("Hello")​
​C

​result = greet()​
​print(result)​

​Output:​​Hello​
​None​

​Because​​greet()​​does not return any value, Python returns​​None​​.​


​10.8 Returning Multiple Values​
​ ython functions can return multiple values.​
P
​Syntax:​

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

​10.9 Default Parameters​


​ default parameter has a predefined value. If no argument is passed, the default value is​
A
​used.​
od

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

​def show(name="Guest", age=18):​ ​Yes​ ​Both have defaults​

​def show(name="Guest", age):​


is
​No​ ​ on-default parameter cannot come after​
N
​default parameter​
N
​Important Warning:​​Avoid Mutable Default Values​
​ o not use mutable objects like list or dictionary as default values.​
D
ith

​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

​Type​ ​Example​ ​Order Matters?​

​Positional argument​ ​student_info("Aman", 21, "Python")​ ​Yes​


od

​Keyword argument​ ​ tudent_info(age=21, name="Aman",​


s ​No​
​course="Python")​

​Important Rule​
​C

​Correct:​

​Incorrect:​

​Positional arguments cannot come after keyword arguments.​


​10.11​​*args​
​*args​​is used when we do not know how many positional arguments will be passed.​

​Syntax​

​ .​
1 *​ args​​collects extra positional arguments.​


​2.​ ​The collected values are stored as a tuple.​

al
​3.​ ​The name​​args​​is a convention; the​​*​​is important.​
​4.​ ​Use​​*args​​when 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,​​numbers​​behaves like a tuple.​
​10.12​​**kwargs​
​**kwargs​​is used when we do not know how many keyword​​arguments will be passed.​

​Syntax​


al
​Explanation​

h
​ .​
1 *​ *kwargs​​collects 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 name​​kwargs​​is a convention; the​​**​​is important.​

​Flow Chart​
is
N
​Function call has many keyword arguments​
​|​
ith

​v​
​**kwargs collects them​
​|​
​v​
eW

​Values are stored as a dictionary​

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

​Here,​​details​​behaves like a dictionary.​


​10.13​​*args​​vs​​**kwargs​
​Point​ ​*args​ ​**kwargs​

​Collects​ ​Positional arguments​ ​Keyword arguments​

​Stored as​ ​Tuple​ ​Dictionary​

​Symbol​ ​Single star​​*​ ​Double star​​**​

​Example call​ ​func(10, 20, 30)​ ​func(name="Aman", age=21)​


al
​Example 1​

h
​PYTHON CODE​
​def show_data(*args, **kwargs):​

hc
​print(args)​
​print(kwargs)​

​show_data(10, 20, name="Aman", age=21)​


is
N
​ utput:​
O
​(10, 20)​
ith

​{'name': 'Aman', 'age': 21}​

​10.14 Function Parameter Order​


eW

​When using different types of parameters together, the order matters.​


od

​Syntax​
​C

​Explanation​
​ .​
1 ​ ormal parameters come first.​
N
​2.​ ​Default parameters come after normal parameters.​
​3.​ ​*args​​comes after normal/default parameters.​
​4.​ ​**kwargs​​comes last.​
​5.​ ​This order keeps function calls clear and valid.​
​Parameter Order Table​
​Order​ ​Parameter Type​ ​Example​

​1​ ​Normal parameter​ ​name​

​2​ ​Default parameter​ ​age=18​

​3​ ​*args​ ​*marks​

​4​ ​**kwargs​ ​**details​

​Example 1​


h al
hc
​Output:​
is
​ ame: Aman​
N
N
​Age: 21​
​Marks: (80, 90, 85)​
ith

​Details: {'course': 'Python', 'city': 'Delhi'}​


eW

​10.15 Docstrings​
​A​​docstring​​is 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 using​​help()​​or​​.__doc__​​.​
​Example 1​

​Output:​​30​


al
​Return the sum of two numbers.​

​Good Docstring Style​

h
hc
is
N
ith
eW

​10.16 Function Naming Rules​


​Function names follow the same basic rules as variable names.​
od

​Syntax​
​def function_name():​
​C

​statement​

​ .​
1 ​ unction names should be meaningful.​
F
​2.​ ​Use​​snake_case​​for function names.​
​3.​ ​Function names should usually describe an action.​
​4.​ ​Avoid using Python keywords as function names.​
​5.​ ​Avoid unclear names like​​x()​​,​​abc()​​, or​​test1()​​.​
​Chapter 11. Advanced Functions​
​Advanced functions help us write more flexible, reusable, and compact code.​

​Before starting, remember:​

​In Python, functions are objects. This means:​

​ .​
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
I​n 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

​Call function using new variable​

​Example 1​
​C

​PYTHON CODE​
​def greet():​
​print("Hello Python")​
​message = greet​
​message()​

​ utput:​
O
​Hello Python​
​Here,​​message​​refers to the same function as​​greet​​.​
​11.2 Lambda Functions​
​ ​​lambda function​​is a small anonymous function. Anonymous​​means 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 with​​map()​​,​​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.3​​map()​
​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 is​​an iterator.​

h
​4.​ ​To display all results at once, convert it using​​list()​​.​

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

​names = ["aman", "riya", "kabir"]​


​upper_names = map([Link], names)​
​print(list(upper_names))​
od

​Output:​​['AMAN', 'RIYA', 'KABIR']​

​map()​​Table​
​C

​Part​ ​Meaning​

​lambda number: number * number​ ​Function to apply​

​numbers​ ​Iterable​

​map()​ ​Applies function to every item​

​list()​ ​Converts result into a list​


​11.4​​filter()​
​filter()​​is used to select items from an iterable​​based on a condition.​

​Syntax​
​filter(function, iterable)​

​Explanation​
​ .​
1 f​ilter()​​takes a function and an iterable.​
​2.​ ​The function must return​​True​​or​​False​​.​


​3.​ ​Items that return​​True​​are kept.​

al
​4.​ ​Items that return​​False​​are removed.​
​5.​ ​In Python 3,​​filter()​​returns a filter object, which​​is 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()​​vs​​filter()​
​C

​Point​ ​map()​ ​filter()​

​Purpose​ ​Transforms every item​ ​Selects matching items​

​Output length​ ​Usually same as input​ ​Can be smaller​

​Function returns​ ​New value​ ​True​​or​​False​

​Example use​ ​Square every number​ ​Keep even numbers​


​11.5​​reduce()​
r​ educe()​​combines all items of an iterable into a​​single final value.​​reduce()​​is not directly​
​available like​​map()​​and​​filter()​​. It must be imported​​from​​functools​​.​

​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

​from functools import reduce​


​numbers = [1, 2, 3, 4]​
​total = reduce(lambda a, b: a + b, numbers)​
eW

​print(total)​

​ utput:​​10​
O
​Working idea:​
​1 + 2 = 3​
od

​3 + 3 = 6​
​6 + 4 = 10​
​C

​map()​​vs​​filter()​​vs​​reduce()​
​Function​ ​Purpose​ ​Final Result​

​map()​ ​Transform items​ ​Iterator of transformed items​

​filter()​ ​Select items​ ​Iterator of selected items​

​reduce()​ ​Combine items​ ​Single value​


​11.6 Recursion​
​Recursion means a function calling itself.​
​Syntax​


​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 raises​​RecursionError​​.​

​Part​

​Base case​
is
​Meaning​

​Condition that stops recursion​


N
​Recursive case​ ​Function calling itself​
ith

​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​
f​actorial(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

​Output:​​Outer function started​


​Inner function executed​
​Important point:​​inner() cannot be called directly outside outer().​

​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

​3.​ ​Python does not automatically enforce these types at runtime.​


​4.​ ​Annotations are stored in the function’s​​__annotations__​​attribute.​

​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 in​​map()​​,​​filter()​​,​​reduce()​​, decorators,​​and callbacks.​
​3.​ ​They make code flexible and reusable.​
ith

​4.​ ​They are common in functional programming.​

​Example 1: Function as Argument​


eW

​PYTHON CODE​
​def shout(text):​
​return [Link]()​
od

​def process_text(function, text):​


​return function(text)​
​C

​result = process_text(shout, "hello")​


​print(result)​

​Output:​​HELLO​

​Here,​​process_text()​​is a higher-order function because it accepts another function.​


​Chapter 12. Scope and Namespaces in Python​
​Scope​​means the area of a program where a variable can be accessed.​
​Namespace​​means a place where names are stored and​​mapped to objects.​
​name -> object/value​
​Example:​​x = 10​
​Here, Python stores the name​​x​​and connects it to​​the value​​10​​.​

​12.1 Local Scope​


al
​ ​​local scope​​is created inside a function. Variables​​created 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

​4.​ ​Local variables are created when the function is called.​


​5.​ ​They are destroyed after the function finishes.​

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

​Output: NameError: name 'name' is not defined.​


​12.2 Global Scope​
​ ​​global scope​​is the main area of the program. Variables​​created outside all functions are​
A
​global variables.​

​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 the​​global​​keyword.​
N
​5.​ ​To modify a global variable inside a function, we need the​​global​​keyword.​
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​

​Created where?​ ​Inside function​ ​Outside functions​

​Accessible where?​ ​Only inside that function​ ​Inside and outside functions​

​Lifetime​ ​Exists during function call​ ​Exists while program runs​

​Example​ ​name = "Aman"​​inside function​ ​course = "Python"​​outside function​


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.​ I​f 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

​name = "Local Aman"​


​print(name)​
​C

​show_name()​
​print(name)​

​Output:​

​ ocal Aman​
L
​Global Aman​

​NOTE:​​Inside the function, the local variable gets priority over the global variable.​
​12.5​​global​​Keyword​
​The​​global​​keyword is used to modify a global variable inside a function.​

​Syntax​
​global variable_name​

​Explanation​


​1.​ U ​ se​​global​​when you want to assign a new value to​​a global variable inside a​

al
​function.​
​2.​ ​Without​​global​​, assignment inside a function creates​​a local variable.​

h
​3.​ ​Reading a global variable does not need​​global​​. Using​​too many global variables is​
​not recommended.​

hc
​Example 1​
​PYTHON CODE​
​count = 0​
is
N
​def increase_count():​
​global count​
ith

​count += 1​

i​ncrease_count()​
eW

​print(count)​

​output:​​1​

​Without​​global​
od

​PYTHON CODE​
​count = 0​
​C

​def increase_count():​
​count += 1​

​increase_count()​

​ utput:​​UnboundLocalError: cannot access local variable 'count' where it is not associated​


O
​with a value​

​ 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
​An​​enclosing scope​​exists when a function is defined​​inside 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)​

i​nner()​
​outer()​

​Output: Hello​
​12.7​​nonlocal​​Keyword​
​ he​​nonlocal​​keyword is used to modify a variable​​from the nearest enclosing function​
T
​scope.​

​Syntax​
​nonlocal variable_name​

​1.​ n ​ onlocal​​is 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.​​nonlocal​​is commonly used​
​in closures.​

h
​Example 1​

hc
​PYTHON CODE​
​def outer():​
​count = 0​
​def inner():​ is
​nonlocal count​
​count += 1​
N
​print(count)​

i​nner()​
ith

​outer()​

​Output:1​
eW

​Without​​nonlocal​
​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​
​global​​vs​​nonlocal​
​Keyword​ ​Used For​ ​Scope Affected​

​global​ ​Modify global variable​ ​Global scope​

​nonlocal​ ​Modify enclosing function variable​ ​Enclosing scope​

​Neither​ ​Normal local variable​ ​Local scope​


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

​12.9 LEGB Rule​


​ EGB is the order Python follows while searching for a variable name.​
L
​L -> Local​
​E -> Enclosing​
​G -> Global​
​B -> Built-in​
​When Python sees a variable name, it searches in this order:​

​ .​
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 finds​​x​​in the local scope​​first, so it does not search further.​
N
​LEGB Search Table​
ith

​Search Order​ ​Scope​ ​Example​


eW

​1​ ​Local​ ​Variable inside current function​


​2​ ​Enclosing​ ​Variable inside outer function​
​3​ ​Global​ ​Variable outside functions​
​4​ ​Built-in​ ​print​​,​​len​​,​​type​
od

​12.10 Namespace Concept​


​A​​namespace​​is a system that stores names and their​​related objects.​
​C

​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 has​​x = 100​​. The local namespace​​inside​​show()​​has​​x = 50​​.​
​2.​ ​Both names are​​x​, 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.11​​locals()​​and​​globals()​
eW

​Python provides two built-in functions to inspect namespaces.​

​Syntax​
od
​C

​ .​
1 l​ocals()​​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​
​NameError​​occurs when Python cannot find a name in​​LEGB search.​

​PYTHON CODE​
​print(age)​
is
N
​Output: NameError: name 'age' is not defined​
ith

​UnboundLocalError​
​ nboundLocalError​​occurs when Python treats a variable​​as local because it is assigned​
U
eW

​inside a function, but it is used before assignment.​


​PYTHON CODE​
​ = 10​
x
​def show():​
od

​print(x)​
​x = 20​

​show()​
​C

​ utput:​​UnboundLocalError: cannot access local variable 'x' where it is not associated with a​
o
​value​

​Error​ ​Meaning​

​NameError​ ​Name not found in any scope​


​UnboundLocalError​ ​Local variable used before assignment​
​12.13 Important Scope Summary Table​
​Concept​ ​Meaning​

​Local scope​ ​Variable inside current function​

​Global scope​ ​Variable outside all functions​

​Enclosing scope​ ​Variable inside outer function​


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

​Namespace​ ​Mapping of names to objects​

​locals()​
is
​Shows local namespace​
N
​globals()​ ​Shows global namespace​

​NameError​ ​Name not found​


ith

​UnboundLocalError​ ​Local variable used before assignment​


eW
od
​C
​Chapter 13. Modules and Packages in Python​
​A​​module​​is a Python file containing reusable code.​

​A​​package​​is a folder that contains multiple modules.​

​Module -> single .py file​

​Package -> folder containing modules​

​Example:​


al
​[Link] -> module​

​my_package/ -> package​

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

​13.1 Importing Modules​


eW

​Importing means using code from another module.​

​Syntax​
​import module_name​
od

​ .​
1 i​mport​​loads 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))​

​Output: 5.0 => Here,​​math​​is a module and​​sqrt()​​is a function inside it.​


​13.2 Different Ways to Import​
​Python provides different import styles.​

​Import Styles Table​


​Import Style​ ​Syntax​ ​Example​ ​How to Use​

​Normal import​ ​import module​ ​import math​ ​[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

​cause name conflicts.​

​13.3 Standard Library Modules​


​C

​ he​​standard library​​is 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​

​math​ ​Mathematical operations​ ​[Link](25)​

​random​ ​Random values​ ​[Link](1, 10)​

​datetime​ ​Date and time​ ​[Link]()​

​os​ ​Operating system tasks​ ​[Link]()​


al
​sys​ ​Python runtime information​ ​[Link]​

​json​ ​Work with JSON data​ ​[Link](data)​

h
​statistics​ ​Basic statistics​ ​[Link](data)​

hc
​collections​ ​Advanced data structures​ ​Counter​​,​​deque​

​itertools​

​pathlib​
​Iterator tools​

​Work with file paths​


is ​[Link]()​

​Path("[Link]")​
N
​Example 1​
ith

​PYTHON CODE​
​import random​
eW

​number = [Link](1, 10)​


​print(number)​

​Output: A random number between 1 and 10​


od

​Actual output changes every time because it is random.​

​13.4 Creating Your Own Modules​


​C

​A Python file can be used as a module.​

​File Structure​
​project/​
​│​
​├── [Link]​
​└── [Link]​

​[Link]​
​PYTHON CODE​
​def add(a, b):​
​return a + b​

​[Link]​
​PYTHON CODE​
​import calculator​

r​ esult = [Link](10, 20)​


​print(result)​


al
​Output: 30​
​Explanation​
​ .​
1 ​ [Link]​​is a module.​
c

h
​2.​ ​[Link]​​imports the​​calculator​​module.​

hc
​3.​ ​The function​​add()​​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
f​rom 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​

​def subtract(a, b):​


​C

​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 in​​PYTHONPATH​​, if set.​


​3.​ ​Standard library directories.​

al
​4.​ ​Installed third-party package directories.​

h
​Syntax​

hc
is
N
​13.7 Exploring a Module with​​dir()​
ith

​dir()​​shows the names available inside a module.​


eW

​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 module​​name.​
​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

​When running​​[Link]​​directly: 30​

​ hen importing​​[Link]​​into another file, the​​function is available, but the test print​
W
od

​does not run automatically.​

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

​Basic Package Structure​


​ roject/​
p
​│​
​├── [Link]​
​│​


​└── mypackage/​

al
​├── __init__.py​
​├── [Link]​
​└── [Link]​

h
hc
​Explanation​
​ .​
1 ​ ypackage​​is a package.​
m
​2.​
​3.​
​4.​
is
​[Link]​​and​​[Link]​​are modules inside the​​package.​
​__init__.py​​marks 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

​from [Link] import add​

​print(add(10, 20))​

​Output: 30​
​13.10​​__init__.py​
​__init__.py​​is a special file used in Python packages.​

​Explanation​
​ .​
1 ​ _init__.py​​is 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]​​:​

​from [Link] import add​

​This means:​
is
N
​ rom package app,​
F
​inside module calculator,​
ith

​import add​

​13.12 Relative Imports​


eW

​A relative imports code based on the current module’s location inside a package.​

​Syntax​
od

​from .module import name​

​from ..package import module​


​C

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

​.​ ​Current package​

​..​ ​Parent package​

​...​ ​Grandparent package​

​Example Structure​
​ roject/​
p
​│​


​└── app/​

al
​├── __init__.py​
​├── [Link]​

h
​└── [Link]​
​Inside​​[Link]​​:​

hc
​from .calculator import add​

​This means:​​Import add from [Link] in the same​​package​


is
​Important Point​
N
​ elative imports work properly when the module is part of a package. They may fail if the file​
R
​is run directly as a script.​
ith

​Better way to run a package module:​


​python -m [Link]​
eW

​13.13 Package Management Basics​


​ ackage management means installing, updating, removing, and tracking external Python​
P
​packages. Python commonly uses​​pip​​for package management.​
od

​Explanation​
​C

​ .​
1 ​ he Python standard library comes with Python.​
T
​2.​ ​Third-party packages must be installed separately.​
​3.​ ​pip​​is 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.14​​pip​​Basics​
​pip​​is Python’s package installer.​

​Common​​pip​​Commands​
​Task​ ​Command​

​Check pip version​ ​python -m pip --version​


​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. This​​makes sure​​pip​​belongs to the​
ith

​Python version you are using.​


eW

​13.15 Virtual Environment Basics​


​A virtual environment is an isolated Python environment for a project.​
od

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

​Create Virtual Environment​


​System​ ​Command​

​Windows​ ​python -m venv venv​

​macOS/Linux​ ​python3 -m venv venv​

​Activate Virtual Environment​


​System​ ​Command​

​Windows PowerShell​ ​venv\Scripts\Activate.ps1​

​Windows CMD​ ​venv\Scripts\[Link]​

​macOS/Linux​ ​source venv/bin/activate​

​Deactivate​


​deactivate​

al
​13.16​​[Link]​

h
hc
​[Link]​​stores a list of packages needed​​for a project.​

​Syntax​ is
​package_name==version​
N
​Example​
ith

​requests==2.32.3​
​numpy==2.0.0​

​Task​ ​Command​
eW

​Save installed packages​ ​python -m pip freeze > [Link]​

​Install from file​ ​python -m pip install -r [Link]​


od

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

​Package​ ​Common Use​

​requests​ ​Sending HTTP requests​

​numpy​ ​Numerical computing​


​pandas​ ​Data analysis​

al
​flask​ ​Web development​

h
​django​ ​Web applications​

hc
​pytest​ ​Testing​

​13.18 Circular Import Warning​


is
​A circular import happens when two modules import each other.​

​Example Structure​
N
​[Link] imports [Link]​
ith

​[Link] imports [Link]​

​ .​
1 ​ ircular imports can cause errors or incomplete imports.​
C
​2.​ ​They usually happen when modules depend on each other too much.​
eW

​3.​ ​Good project structure helps avoid circular imports.​


​4.​ ​Shared code can be moved into a separate module.​

​Example Problem​
od

​[Link] -> imports [Link]​


​[Link] -> imports [Link]​
​Python may not finish loading one module before the other needs it.​
​C

​Better Structure​
​ [Link] -> shared logic​
c
​[Link] imports [Link]​
​[Link] imports [Link]​
​Chapter 14. Object-Oriented Programming in Python​
​ bject-Oriented Programming, or​​OOP​​, is a programming​​style where code is organized​
O
​using​​classes​​and​​objects​​.​

​14.1.1 OOPS Fundamentals​


​Basic idea​


​ lass -> blueprint​
C

al
​Object -> real item created from class​

​Example idea:​

h
​ lass:​​Student;​
C

hc
​Objects:​
​student1​
​student2​
​student3​

​Why OOP is Used​


is
N
​ .​
1 ​ o organize large programs.​
T
​2.​ ​To reuse code.​
ith

​3.​ ​To group data and behavior together.​


​4.​ ​To model real-world entities.​
​5.​ ​To make code easier to maintain.​
eW

​14.1.1 Classes​
​A​​class​​is 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 use​​PascalCase​​.​
​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​

​BankAccount​ ​Uses PascalCase​is


​EmployeeRecord​ ​Meaningful name​
N
​14.1.2 Objects​
ith

​An​​object​​is an instance created from a class.​


​Syntax​
eW

​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

​4.​ ​Objects are also called instances.​

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

​Meaning​ ​Blueprint​ ​Real instance​


al
​Created using​ ​class​​keyword​ ​Class name with​​()​

​Example​ ​Student​ ​student1 = Student()​

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

​3.​ ​Attributes are accessed using dot​​.​​notation.​

​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]​ ​Accesses​​name​​attribute​

​[Link]​ ​Accesses​​age​​attribute​

​[Link] = "Aman"​ ​Creates/updates attribute​


​14.1.4 Methods​

al
​A​​method​​is 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

​3.​ ​Instance methods usually take​​self​​as the first parameter.​


​4.​ ​Methods are called using an object.​

​Example 1​
od

​PYTHON CODE​
​class Student:​
​def greet(self):​
​C

​print("Hello")​

​student1 = Student()​
​[Link]()​

​Output: Hello​

​14.1.5​​self​
​self​​refers to the current object.​
​Syntax​
​def method_name(self):​
​statement​

​ .​
1 ​ elf​​represents the object that is calling the method.​
s
​2.​ ​It is used to access object attributes and methods.​
​3.​ ​Python automatically passes the object as​​self​​.​
​4.​ ​self​​is not a keyword, but it is the standard convention.​
​5.​ ​Always use​​self​​for 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

​__init__​​is a special method used to initialize object​​data.​

​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 after​​it 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​

​ tudent1 = Student("Aman", 21)​


s
​print([Link])​
​print([Link])​

​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 I​nstance 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

​4.​ ​They are accessed using​​object.variable_name​​.​

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

​NOTE:​​[Link] and [Link] are separate​​instance variables.​

​14.1.8 Class Variables​


​Class variables are variables shared by all objects of a class.​

​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

​def __init__(self, name):​


​[Link] = name​
od

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

​Instance Variable vs Class Variable​


​Point​ ​Instance Variable​ ​Class Variable​

​Belongs to​ ​Object​ ​Class​

​Created where​ ​Usually inside​​__init__​ ​Inside class, outside methods​

​Shared?​ ​No​ ​Yes​

​Access​ ​[Link]​ ​[Link]​

​Example​ ​[Link]​ ​school_name​


​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

​Defined where?​ ​Outside class​ ​Inside class​

​Called using​ ​Function name​ ​Object or class​


​C

​First parameter​ ​No automatic​​self​ ​Instance method gets​​self​

​Example​ ​greet()​ ​[Link]()​

​14.2 OOPS Principles​

​14.2.1 Encapsulation​
​ ncapsulation means​​binding data and methods together inside a class​​and 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​

​Here,​​__balance​​is not directly accessed from outside.​​It is accessed using methods.​

​Public, Protected, and Private Members​


​Python uses naming conventions for access control.​

​Access Level Table​


​Type​ ​Syntax​ ​Meaning​ ​Example​

​Public​ ​name​ ​Can be accessed normally​ ​[Link]​

​Protected​ ​_name​ ​Meant for internal use​ ​self._salary​

​Private / Name mangling​ ​__name​ ​Avoid accidental outside access​ ​self.__pin​

​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​​__grade​​will fail:​
​print(student.__grade)​
eW

​Output:​​AttributeError: 'Student' object has no attribute​​'__grade'​

​Important Point​
​ ouble underscore does not make data fully private.​
D
od

​It performs name mangling to avoid accidental access.​


​Internally, Python changes:​
​__grade -> _Student__grade​
​C

​So technically it can still be accessed, but it should not be used directly.​

​Getter and Setter Methods​


​Getter and setter methods are used to read and update private data safely.​
​ .​
1 ​ etter method reads private data.​
G
​2.​ ​Setter method updates private data.​


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​

​def set_marks(self, marks):​


eW

​if marks >= 0:​


​self.__marks = marks​
​else:​
​print("Marks cannot be negative")​
od

​student = Student(80)​
​student.set_marks(90)​
​print(student.get_marks())​
​C

​Output: 90​

​Encapsulation Using​​@property​
​@property​​allows a method to behave like an attribute.​

​Syntax​

​ .​
1 ​ property​​is 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 I​nheritance 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 an​​is-a​​relationship.​
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​

​Why Inheritance is Used​


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

​Polymorphism​ ​Same method can behave differently​


is
​Real-world modeling​ ​Represents​​is-a​​relationship​
N
​ xample:​
E
​Dog is an Animal​
​Car is a Vehicle​
ith

​Student is a Person​

​Types of Inheritance in Python​


eW

​Python supports these major types of inheritance:​


​Type​ ​Meaning​

​Single inheritance​ ​One child inherits from one parent​


od

​Multilevel inheritance​ ​Child inherits from parent, and another child inherits from that child​

​Hierarchical inheritance​ ​Multiple child classes inherit from one parent​


​C

​Multiple inheritance​ ​One child inherits from multiple parents​

​Hybrid inheritance​ ​Combination of two or more inheritance types​

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

​class Child(Parent1, 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

​class Child(Father, Mother):​


​def child_skill(self):​
​print("Coding")​

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

​class TeachingAssistant(Student, Employee):​


eW

​def show_ta(self):​
​print("Teaching Assistant")​

t​a = 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

​2.​ ​It is important in multiple inheritance.​


​3.​ ​Python uses the C3 linearization algorithm for MRO.​
​4.​ ​The search starts from the child class.​
​C

​5.​ ​Then Python checks parent classes according to MRO.​


​6.​ ​Finally, it checks the base​​object​​class.​

​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

[​<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>,​


​<class 'object'>]​
eW

​MRO Flow​
​D -> B -> C -> A -> object​

​Since​​B​​comes before​​C​,​​[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 ​ lass​​B​​and class​​C​​both inherit from​​A​.​
C

al
​2.​ ​Class​​D​​inherits from both​​B​​and​​C​.​
​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")​

​class D(B, C):​


od

​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__​​, Python​​uses the parent class​​__init__​​.​

​Case 1: Child Has No​​__init__​


​PYTHON CODE​
​class Person:​
​def __init__(self, name):​
​[Link] = name​


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

​def __init__(self, course):​


​[Link] = course​
​C

​student = Student("Python")​
​print([Link])​

​Output:​

​Python​

​Here, parent​​__init__​​does not run automatically because​​the 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

​def __init__(self, name, course):​


​super().__init__(name)​
​[Link] = course​
od

​student = Student("Aman", "Python")​

​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

​3.​ ​When called on child object, child method runs.​


​4.​ ​This supports polymorphism.​
​5.​ ​Parent method can still be called using​​super()​​.​
eW

​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 with​​super()​
​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

​3.​ ​Python supports polymorphism through:​


​1.​ ​Method overriding​
​2.​ ​Duck typing​
eW

​3.​ ​Operator overloading​


​PYTHON CODE​
​class Dog:​
​def sound(self):​
od

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

​Method overriding​ ​Child changes parent method​ ​[Link]()​

​Duck typing​ ​Object is accepted if it has required method​ ​[Link]()​

​Operator overloading​ ​Operator works differently by class​ ​obj1 + obj2​


​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 is​​Duck​​or​​Person​​. It only checks whether​​speak()​
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 the​​abc​​module.​


​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

​def pay(self, amount):​


​print("Paid", amount, "using UPI")​

​payment = UpiPayment()​
od

​[Link](500)​
​C

​Output: Paid 500 using UPI​

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

​Meaning​ ​Protecting and controlling data​ ​Hiding implementation details​


​Focus​ ​Data access​ ​Essential behavior​
​Achieved by​ ​Private variables, methods,​​@property​ ​Abstract classes, interfaces​
​Example​ ​Hide​​__balance​ ​Define​​pay()​​without showing payment logic​
​ ncapsulation​​= How data is protected​
E


​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 a​​has-a​​relationship.​
​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​

​Association​ ​One class uses another class​ ​Teacher teaches Student​


​Aggregation​ ​One class has another, but both can exist independently​ ​Department has Teachers​
​Composition​ ​One class owns another strongly​ ​House has Rooms​

​Important Difference​


al
​Point​ ​Aggregation​ ​Composition​

​Relationship​ ​Weak has-a​ ​Strong has-a​

h
​Child object can exist alone?​ ​Yes​ ​Usually no​

hc
​Example​ ​Team has Players​ ​Car has Engine​

​isinstance()​​and​​issubclass()​ is
​These functions are useful when working with inheritance.​
N
​Syntax​
i​sinstance(object, ClassName)​
ith

​issubclass(ChildClass, ParentClass)​

​ .​
1 i​sinstance()​​checks whether an object belongs to a​​class.​
eW

​2.​ ​It also returns​​True​​if the object belongs to a child​​class.​


​3.​ ​issubclass()​​checks whether one class inherits from​​another class.​
​4.​ ​Both return​​True​​or​​False​​.​

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

​Relationship​ ​Is-a​ ​Has-a​

​Code style​ ​Child class extends parent​ ​Class contains another object​

​Example​ ​Dog is an Animal​ ​Car has an Engine​

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

​Use Composition When​


is
N
​One object has or uses another object.​
​Example:​
ith

​Car has an Engine​


​Computer has a Processor​
eW

​Complete Inheritance Types Summary​


​Type​ ​Structure​ ​Example​
od

​Single​ ​A -> B​ ​Animal -> Dog​

​Multilevel​ ​A -> B -> C​ ​Animal -> Dog -> Puppy​


​C

​Hierarchical​ ​A -> B​​,​​A -> C​ ​Animal -> Dog​​,​​Animal -> Cat​

​Multiple​ ​A + B -> C​ ​Father + Mother -> Child​

​Hybrid​ ​Combination​ ​Person -> Student/Employee -> TeachingAssistant​

​OOP Principles Summary​


​Principle​ ​Meaning​ ​Python Feature​

​Encapsulation​ ​Control access to data​ ​ name​​,​​__name​​, getter/setter,​


_
​@property​

​Inheritance​ ​Reuse parent class code​ ​class Child(Parent)​

​Polymorphism​ ​Same method, different behavior​ ​Overriding, duck typing​

​Abstraction​ ​Hide implementation details​ ​ABC​​,​​@abstractmethod​


​Composition​ ​Build one object using another​ ​Object inside object​

h al
​Important OOP Scenario Table​

hc
​Scenario​ ​Use​

​Need to protect data​ is​Encapsulation​

​Need to reuse common code​ ​Inheritance​


N
​ eed same method with different​
N ​Polymorphism​
​behavior​
ith

​Need to force child class method structure​ ​Abstraction​

​Need one object inside another​ ​Composition​


eW

​Need multiple parent classes​ ​Multiple inheritance​

​Need to resolve method search order​ ​MRO​


od

​Need parent constructor logic​ ​super()​

​Need to check object/class relationship​ ​isinstance()​​,​​issubclass()​


​C

​14.3 Special Methods / Magic Methods / Dunder Methods​


​ pecial methods are predefined methods in Python with double underscores before and​
S
​after their names.​

​They are also called:​

​​ S
● ​ pecial methods​
​●​ ​Magic methods​
​●​ ​Dunder methods​

​dunder​​means​​double 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

​5.​ ​Instead, we use operators or built-in functions.​

​Example Idea​
eW

​print(obj) -> calls obj.__str__()​

​len(obj) -> calls obj.__len__()​


od

​obj[0] -> calls obj.__getitem__(0)​

​obj1 + obj2 -> calls obj1.__add__(obj2)​


​C

​Common Special Methods Table​


​Special​ ​Triggered By​ ​Purpose​
​ ethod​
M

​__init__​ ​ClassName()​ ​Initializes object​

​__str__​ ​str(obj)​​,​​print(obj)​ ​User-friendly string​

​__repr__​ ​repr(obj)​ ​Developer-friendly string​

​__len__​ ​len(obj)​ ​Returns length​

​__getitem__​ ​obj[index]​ ​Indexing/slicing​


al
​__add__​ ​obj1 + obj2​ ​Addition​

​__sub__​ ​obj1 - obj2​ ​Subtraction​

h
​__call__​ ​obj()​ ​Makes object callable​

hc
​__enter__​ ​with obj:​ ​Starts context manager​

​__exit__​ ​End of​​with​​block​ ​Exits context manager​


is
N
​14.3.1​​__str__​
ith

​__str__​​returns a user-friendly string representation​​of an object.​

​Syntax​
eW
od
​C

​Explanation​
​ .​
1 ​ _str__​​is called by​​str(obj)​​.​
_
​2.​ ​It is also called by​​print(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]}"​

​ tudent = Student("Aman", "Python")​


s
​print(student)​


al
​Output:​​Aman is studying Python​

​14.3.2​​__repr__​

h
hc
​__repr__​​returns a developer-friendly string representation​​of an object.​

​Syntax​ is
N
ith

​ .​ _
1 ​ _repr__​​is called by​​repr(obj)​​. It is mainly used​​for debugging.​
eW

​2.​ ​It should return a string. A good​​__repr__​​often looks​​like valid Python code.​
​3.​ ​If​​__str__​​is not defined, Python may use​​__repr__​​while printing.​

​PYTHON CODE​
​class Student:​
od

​def __init__(self, name, course):​


​[Link] = name​
​[Link] = course​
​C

​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 of​​len(obj)​​.​

​Syntax​


al
​Explanation​

h
​ .​
1 ​ _len__​​is called by​​len(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__​​returns​​0​, the object is considered​​False​​in 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

​team = Team(["Aman", "Riya", "Kabir"])​


​print(len(team))​
​C

​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 use​​obj[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

​__add__​​defines custom behavior for the​​+​​operator.​

​Syntax​
​C

​def __add__(self, other):​


​return result​

​ .​
1 ​ _add__​​is called when​​obj1 + obj2​​is used.​
_
​2.​ ​It is used for operator overloading.​
​3.​ ​It should return a new result.​
​4.​ ​If the other object type is not supported, return​​NotImplemented​​.​
​5.​ ​It should be used only when addition makes logical sense.​

​Example 1​
​PYTHON CODE​
​class Money:​
​def __init__(self, amount):​
​[Link] = amount​

​def __add__(self, other):​


​if not isinstance(other, Money):​
​return NotImplemented​
​return Money([Link] + [Link])​


al
​def __str__(self):​
​return f"Amount: {[Link]}"​

h
hc
​money1 = Money(100)​
​money2 = Money(50)​
​result = money1 + money2​ is
​print(result)​
N
ith

​Output: Amount: 150​


eW

​14.3.6​​__sub__​
​__sub__​​defines custom behavior for the​​-​​operator.​
od

​Syntax​
​def __sub__(self, other):​
​C

​return result​

​ .​
1 ​ _sub__​​is called when​​obj1 - obj2​​is used.​
_
​2.​ ​It is also part of operator overloading.​
​3.​ ​It should return a meaningful result.​
​4.​ ​Return​​NotImplemented​​if the other type is unsupported.​

​Example 1​
​PYTHON CODE​
​class Money:​
​def __init__(self, amount):​
​[Link] = amount​

​def __sub__(self, other):​


​if not isinstance(other, Money):​
​return NotImplemented​
​return Money([Link] - [Link])​


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

​__call__​​allows an object to be called like a function.​

​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
​the​​with​​statement.​
ith

​Syntax​
​PYTHON CODE​
eW

​def __enter__(self):​
​return self​

​ ef __exit__(self, exc_type, exc_value,​


d
​traceback):​
od

​statement​
​C

​Explanation​
​ .​
1 ​ _enter__​​runs at the start of the​​with​​block.​
_
​2.​ ​__exit__​​runs when the​​with​​block ends.​
​3.​ ​__exit__​​runs even if an error occurs inside the​​with​​block.​
​4.​ ​__exit__​​receives exception details if an error occurs.​
​5.​ ​If​​__exit__​​returns​​True​​, the exception is suppressed.​
​6.​ ​If​​__exit__​​returns​​False​​or​​None​​, the exception continues.​
​PYTHON CODE​
​class SimpleContext:​
​def __enter__(self):​
​print("Entering")​
​return self​

​ ef __exit__(self, exc_type, exc_value,​


d
​traceback):​
​print("Exiting")​


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

​A common real-world example of a context manager is file handling.​

​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 the​​with​​block.​
​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

​//​ ​__floordiv__​ ​obj1 // obj2​

​%​ ​__mod__​ ​obj1 % obj2​

​**​ ​__pow__​ ​obj1 ** obj2​


eW

​==​ ​__eq__​ ​obj1 == obj2​

​!=​ ​__ne__​ ​obj1 != obj2​

​<​ ​__lt__​ ​obj1 < obj2​


od

​<=​ ​__le__​ ​obj1 <= obj2​

​>​ ​__gt__​ ​obj1 > obj2​


​C

​>=​ ​__ge__​ ​obj1 >= obj2​

​[]​ ​__getitem__​ ​obj[index]​

​()​ ​__call__​ ​obj()​

​len()​ ​__len__​ ​len(obj)​

​str()​ ​__str__​ ​str(obj)​

​repr()​ ​__repr__​ ​repr(obj)​


​14.3.11 Comparison Special Methods​
​Comparison methods allow objects to be compared.​

​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 return​​True​​or​​False​​.​
​5.​ ​Return​​NotImplemented​​if comparison with the other​​type is unsupported.​
N
​Example 1​
ith

​PYTHON CODE​
​class Student:​
eW

​def __init__(self, name, marks):​


​[Link] = name​
​[Link] = marks​
od

​def __eq__(self, other):​


​if not isinstance(other, Student):​
​return NotImplemented​
​C

​return [Link] == [Link]​

​student1 = Student("Aman", 85)​


​student2 = Student("Riya", 85)​
​print(student1 == student2)​

​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

​2.​ ​In-place methods are used for operators like​​+=​​,​​-=​​,​​*=​​.​


​3.​ ​These are advanced but useful to know.​
eW

​Table​
​Type​ ​Example Operator​ ​Method​

​Normal addition​ ​obj + other​ ​__add__​


od

​Reverse addition​ ​other + obj​ ​__radd__​


​C

​In-place addition​ ​obj += other​ ​__iadd__​

​Normal subtraction​ ​obj - other​ ​__sub__​

​Reverse subtraction​ ​other - obj​ ​__rsub__​

​In-place subtraction​ ​obj -= other​ ​__isub__​


​14.3.13​​__bool__​
​__bool__​​defines truth value behavior of an object.​

​Syntax​


h al
​Explanation​

hc
​ .​
1 ​ _bool__​​is called by​​bool(obj)​​.​
_
​2.​ ​It is also used in​​if obj:​​conditions.​
​3.​
​4.​
​It must return​​True​​or​​False​​.​
is
​If​​__bool__​​is not defined, Python may use​​__len__​​.​
​5.​ ​If both are missing, most objects are considered​​True​​.​
N
​Example 1​
ith

​PYTHON CODE​
​class Cart:​
eW

​def __init__(self, items):​


​[Link] = items​

​def __bool__(self):​
od

​return len([Link]) > 0​

​cart = Cart(["Book"])​
​C

​if cart:​
​print("Cart has items")​

​Output: Cart has items​


​14.3.14​​__iter__​​and​​__next__​
​These methods make an object iterable.​
​Syntax​
​PYTHON CODE​
​def __iter__(self):​
​return self​


​def __next__(self):​

al
​return next_value​

h
​ .​ _
1 ​ _iter__​​returns an iterator object.​​__next__​​returns​​the next value.​
​2.​ ​When no value is left,​​__next__​​should raise​​StopIteration​​.​

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 the​​in​​operator.​

​Syntax​

​def __contains__(self, item):​

​return True_or_False​


al
​Explanation​

h
​ .​ _
1 ​ _contains__​​is called by​​item in obj​​.​
​2.​ ​It should return​​True​​or​​False​​.​

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​

​def __contains__(self, member):​


eW

​return member in [Link]​

​team = Team(["Aman", "Riya", "Kabir"])​


od

​print("Aman" in team)​
​print("Neha" in team)​
​C

​Output:​

​True​

​False​
​Important Rules for Special Methods​
​Rule​ ​Explanation​

​Return correct type​ ​__str__​​and​​__repr__​​must return string​

​__len__​​must return integer​ ​It should return non-negative integer​

​Use​​NotImplemented​ ​For unsupported operator types​

​Avoid confusing behavior​ ​Operators should behave logically​


al
​Do not call directly​ ​Use​​len(obj)​​, not​​obj.__len__()​

​Special Methods Summary​

h
hc
​Method​ ​Meaning​ ​Common Use​

​__str__​ ​User-friendly string​ ​print(obj)​

​__repr__​

​__len__​
​Developer-friendly string​

​Defines length​
is ​repr(obj)​

​len(obj)​
N
​__getitem__​ ​Defines indexing​ ​obj[index]​
ith

​__add__​ ​Defines addition​ ​obj1 + obj2​

​__sub__​ ​Defines subtraction​ ​obj1 - obj2​


eW

​__call__​ ​Makes object callable​ ​obj()​

​__enter__​ ​Starts context manager​ ​with obj:​

​__exit__​ ​Ends context manager​ ​End of​​with​


od

​__eq__​ ​Equality comparison​ ​obj1 == obj2​

​__lt__​ ​Less-than comparison​ ​obj1 < obj2​


​C

​__bool__​ ​Truth value​ ​if obj:​

​__iter__​ ​Returns iterator​ ​for item in obj:​

​__next__​ ​Returns next item​ ​Iterator protocol​

​__contains__​ ​Membership test​ ​item in obj​


​Chapter 15: Advanced OOP in Python​
​Advanced OOP topics help us write cleaner, safer, and more reusable class-based code.​

​This section includes:​

​ .​
1 ​ classmethod​
@
​2.​ ​@staticmethod​
​3.​ ​@property​
​4.​ ​Abstract base classes​
​5.​ ​Mixins​


al
​6.​ ​Metaclasses​
​7.​ ​Data classes​

h
hc
​15.1​​@classmethod​
is
​A​​class method​​is a method that receives the class​​as its first argument.​

​The first parameter is usually named​​cls​​.​


N
​Syntax​
ith

​class ClassName:​
​@classmethod​
eW

​def method_name(cls):​
​statement​

​Explanation​
od

​ .​
1 ​ classmethod​​is used to create a class method.​
@
​2.​ ​A class method receives the class automatically as​​cls​​.​
​3.​ ​It can access class variables.​
​C

​4.​ ​It can modify class variables.​


​5.​ ​It can be called using the class name or object name.​
​6.​ ​It is commonly used to create alternate constructors.​

​Example 1​
​PYTHON CODE​
​class Student:​
​school_name = "ABC School"​

​def __init__(self, name):​


​[Link] = name​

​@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

​First parameter​ ​cls​

​Receives​ ​Class​
​C

​Can access class variables​ ​Yes​

​Can access instance variables directly​ ​No​

​Can be called by class​ ​Yes​

​Can be called by object​ ​Yes​


​15.2 Class Method as Alternate Constructor​
​An alternate constructor means creating an object in a different way.​

​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

​def __init__(self, name, age):​


​[Link] = name​
​[Link] = age​
eW

​ 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​
​A​​static method​​is a method inside a class that does​​not receive​​self​​or​​cls​​.​

​Syntax​
​class ClassName:​
​@staticmethod​
​def method_name():​
​statement​


al
​ .​
1 ​ staticmethod​​creates a static method.​
@
​2.​ ​It does not receive the object as​​self​​.​
​3.​ ​It does not receive the class as​​cls​​.​

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

​def add(a, b):​


​return a + b​
​print([Link](10, 20))​
eW

​Output: 30​

​Important Points​
od

​Point​ ​Explanation​

​First parameter​ ​No automatic first parameter​


​C

​Receives object?​ ​No​

​Receives class?​ ​No​

​Can access instance variables directly?​ ​No​

​Can access class variables directly?​ ​No​


​15.4 Instance Method vs Class Method vs Static Method​
​Point​ ​Instance Method​ ​Class Method​ ​Static Method​

​Decorator​ ​No decorator​ ​@classmethod​ ​@staticmethod​

​First parameter​ ​self​ ​cls​ ​ o automatic​


N
​parameter​

​Receives​ ​Object​ ​Class​ ​Nothing automatically​


​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
​@property​​allows a method to be accessed like an attribute.​
ith

​Syntax​
​class ClassName:​
eW

​@property​
​def attribute_name(self):​
​return value​

​Explanation​
od

​ .​
1 ​ property​​is used to create managed attributes.​
@
​2.​ ​It allows method logic to run when accessing an attribute.​
​C

​3.​ ​It helps with encapsulation.​


​4.​ ​It can be used for validation.​
​5.​ ​It makes code cleaner than normal getter methods.​
​Example 1​
​PYTHON CODE​
​class Student:​
​def __init__(self, marks):​
​self._marks = marks​

​@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​​@property​​Setter​
ith

​A setter is used to control how a property value is updated.​


eW

​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

​Getter and Setter Table​


​Part​ ​Purpose​
od

​@property​ ​Reads value​

​@[Link]​ ​Updates value​


​C

​self._marks​ ​Internal storage attribute​

​[Link]​ ​Public property access​


​15.7 Read-only Property​
​A property becomes read-only if we define only getter and no setter.​

​Syntax​
​@property​

​def property_name(self):​


​return value​

al
​Explanation​

h
​ .​ I​f 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]​

​rectangle = Rectangle(10, 5)​


od

​print([Link])​
​C

​Output:​

​50​

​Invalid update:​

​[Link] = 100​

​Output:​

​AttributeError: property 'area' of 'Rectangle' object has no setter​


​15.8 Abstract Base Classes​
​An​​abstract base class​​defines a common structure​​that child classes must follow.​
​Syntax​


al
​ .​
1 ​ bstract base classes are created using​​ABC​​.​
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

​Child class must implement method​


​|​
​v​
​Child object can be created​
eW

​PYTHON CODE​
​from abc import ABC, abstractmethod​

​class Shape(ABC):​
​@abstractmethod​
od

​def area(self):​
​pass​

​class Square(Shape):​
​C

​def __init__(self, side):​


​[Link] = side​

​def area(self):​
​return [Link] * [Link]​

​square = Square(5)​
​print([Link]())​

​Output: 25​
​15.9​​Why Abstract Base Classes Are Used​
​ bstract base classes are used when we want to force child classes to implement required​
A
​methods.​

​ very payment class must have pay() method.​


E
​UPI payment -> pay()​
​Card payment -> pay()​
​Cash payment -> pay()​

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

​Supports polymorphism​ ​Same method name works across classes​


is
N
ith

​15.10 Mixins​
eW

​A​​mixin​​is a small class that provides extra reusable​​behavior to another class.​

​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 with​​Mixin​​.​
​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

​Common with​ ​Multiple inheritance​

​Naming style​ ​Ends with​​Mixin​


eW

​Best design​ ​Small and focused​

​15.11 Mixin vs Normal Parent Class​


od

​Point​ ​Normal Parent Class​ ​Mixin​

​Purpose​ ​Represents main inheritance relationship​ ​Adds extra behavior​


​C

​Relationship​ ​Usually​​is-a​ ​Usually feature-based​

​Used alone​ ​Often yes​ ​Usually no​

​Example​ ​Dog​​inherits​​Animal​ ​Student​​uses​​JsonMixin​

​Size​ ​Can be large​ ​Should be small​


​15.12 Metaclasses​
​A​​metaclass​​is the class of a class.​
​Basic Idea​
​Object is created from class. Class is created from metaclass.​

​ .​
1 I​n Python, classes are also objects.​
​2.​ ​The default metaclass in Python is​​type​​.​
​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

​type(student)​ ​student​​is an object of​​Student​

​type(Student)​ ​Student​​is an object of​​type​


od

​15.13 Data Classes​


​ ​​data class​​is a class mainly used to store data. It reduces repeated code like​​__init__​​,​
A
​C

​__repr__​​, and comparison methods.​

​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

​15.14 Normal Class vs Data Class​


eW

​Comparison Table​
od

​Point​ ​Normal Class​ ​Data Class​

​Need to write​​__init__​ ​Yes​ ​Automatically generated​


​C

​Useful​​__repr__​ ​Need to write manually​ ​Automatically generated​

​Type annotations​ ​Optional​ ​Used for fields​

​Best for​ ​Behavior-heavy classes​ ​Data-storing classes​

​Less repeated code​ ​No​ ​Yes​


​15.15 Default Values in Data Classes​
​Data class fields can have default values.​
​Syntax​
​@dataclass​
​class ClassName:​
​field1: type​
​field2: type = default_value​


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

​This is not allowed in modern Python data classes.​

​Correct Style :​​Use​​field(default_factory=list)​​.​


od
​C

​Output: ['Python']​
​[]​
​1.​ ​Mutable defaults can accidentally be shared.​
​2.​ ​default_factory=list​​creates 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
​ .​ f​rozen=True​​makes 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

​point = Point(10, 20)​


​print(point)​
​C

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

​ ile handling is used to store and read data from files.​


F
​Exception handling is used to handle runtime errors safely.​


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

​5.​ ​Close files​


​6.​ ​Work with text files, binary files, CSV, JSON, and XML​
eW

​16.1.2 Opening Files​


​A file is opened using the​​open()​​function.​

​Syntax​
od

​file = open("file_name", "mode")​


​With encoding:​
​C

​file = open("file_name", "mode", encoding="utf-8")​

​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-8​​is a common and recommended encoding.​

​Example 1​
f​ile = open("[Link]", "r", encoding="utf-8")​
​This opens​​[Link]​​in read mode.​

​16.1.3 Closing Files​


​Syntax​
​[Link]()​


​1.​ C ​ losing a file releases system resources. If a file is not closed, data may not be​

al
​saved properly.​
​2.​ ​The​​with​​statement is preferred because it closes​​the file automatically.​

h
​Example 1​

hc
f​ile = open("[Link]", "r", encoding="utf-8")​
​[Link]()​

​16.1.4 Reading Files​


is
N
​Reading means getting data from a file.​
ith

​Method​ ​Meaning​

​read()​ ​Reads the entire file​


eW

​readline()​ ​Reads one line​

​readlines()​ ​Reads all lines into a list​


od

​Example 1​
f​ile = 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]())​

​Output: Hello Python​


is
​Welcome to file handling​
N
​strip()​​removes extra newline characters from the line.​
ith

​16.1.6 Writing Files​


eW

​Writing means saving data into a file.​

​Syntax​
od

​open("file_name", "w")​

​ .​ "​ w"​​means write [Link] the file does not exist, Python​​creates it.​
1
​2.​ ​If the file already exists, old content is removed.​
​C

​3.​ ​New content is written from the beginning.​

​Example 1​
​with open("[Link]", "w", encoding="utf-8") as file:​
​[Link]("Hello Python")​

​ his writes text into​​[Link]​​.​


T
​NOTE:​​Write mode overwrites old file content.​
​16.1.7 Appending Files​
​Appending means adding new data at the end of an existing file.​

​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

​File modes tell Python how the file should be opened.​

​Mode​ ​Meaning​ ​File Must Exist?​ ​Old Content​


eW

​"r"​ ​Read text file​ ​Yes​ ​Not changed​

​"w"​ ​Write text file​ ​No​ ​Removed if file exists​

​"a"​ ​Append text file​ ​No​ ​Kept​


od

​"x"​ ​Create new file​ ​No​ ​Error if file exists​


​C

​"b"​ ​Binary mode​ ​Depends​ ​Depends​

​"t"​ ​Text mode​ ​Depends​ ​Depends​

​"+"​ ​Read and write​ ​Depends​ ​Depends​


​Common Mode Combinations​
​Mode​ ​Meaning​

​"rt"​ ​Read text file​

​"wt"​ ​Write text file​

​"at"​ ​Append text file​

​"rb"​ ​Read binary file​


al
​"wb"​ ​Write binary file​

​"r+"​ ​Read and write existing file​

h
​"w+"​ ​Write and read, overwrites file​

hc
​"a+"​ ​Append and read​

is
​Important point:​​Default mode is "rt", which means​​read text.​
N
​16.1.9​​with​​Statement​
ith

​The​​with​​statement is the recommended way to work​​with files.​

​Syntax​
eW

​with open("file_name", "mode") as file:​


​statement​

​ .​ w
1 ​ ith​​automatically closes the file. It is safer than​​manually using​​close()​​.​
od

​2.​ ​It works even if an error happens inside the block. It makes file handling cleaner.​

​Example 1​
​C

​with open("[Link]", "r", encoding="utf-8") as file:​


​content = [Link]()​
​print(content)​

​No need to write:​

​[Link]()​
​16.1.10 File Object Methods​
​Method​ ​Meaning​

​read()​ ​Reads entire file​

​read(size)​ ​ eads given number of​


R
​characters/bytes​

​readline()​ ​Reads one line​


al
​readlines()​ ​Reads all lines into a list​

​write(text)​ ​Writes text​

h
​writelines(list)​ ​Writes multiple strings​

hc
​seek(position)​ ​Moves file pointer​

​tell()​ ​Returns current file pointer position​


is
​close()​ ​Closes file​
N
​flush()​ ​Forces buffered data to be written​
ith

​16.1.11 Binary Files​


eW

​Binary files store data in bytes.​

​​
● I​mages​
​●​ ​Videos​
od

​●​ ​Audio files​


​●​ ​PDF files​
​●​ ​Executable files​
​C

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

​Relative path​ ​Path from current folder​ ​"[Link]"​

​Absolute path​ ​Full path from root/drive​ ​"C:/Users/Aman/[Link]"​

​Folder path​ ​File inside folder​ ​"files/[Link]"​


​Parent folder path​ ​File in parent folder​ ​"../[Link]"​

al
​16.1.13 Basic​​os​​Module​

h
hc
​The​​os​​module helps work with the operating system.​

​Syntax​ is
N
​import os​
ith

​Common​​os​​Functions​
​Function​ ​Meaning​
eW

​[Link]()​ ​Gets current working directory​

​[Link]()​ ​Lists files and folders​

​[Link]("folder")​ ​Creates folder​


od

​[Link]("[Link]")​ ​Deletes file​

​[Link]("old", "new")​ ​Renames file/folder​


​C

​[Link](path)​ ​Checks if path exists​

​[Link](path)​ ​Checks if path is a file​

​[Link](path)​ ​Checks if path is a folder​

​[Link](a, b)​ ​Joins paths safely​

​16.1.14 Basic​​pathlib​​Module​
​pathlib​​is a modern way to work with file paths.​

​Syntax​
​from pathlib import Path​

​ .​ p
1 ​ athlib​​works with paths as [Link] is cleaner​​than manually joining strings.​
​2.​ ​It is recommended for modern Python [Link] works across operating systems.​

​Common​​pathlib​​Methods​


​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

​Encoding decides how text is stored in bytes.​


eW

​Syntex:​​open("[Link]", "r", encoding="utf-8")​

​ .​
1 ​ ext files store text using an encoding.​
T
​2.​ ​utf-8​​supports most common characters.​
​3.​ ​Always mention encoding when working with text files.​
od

​4.​ ​Encoding problems can cause​​UnicodeDecodeError​​.​

​Example 1​
​C

​with open("[Link]", "w", encoding="utf-8") as file:​


​[Link]("Python is easy")​

​16.2 Exception Handling​


​ n exception is an error that happens while the program is running. Exception handling​
A
​allows us to handle errors safely without crashing the whole program.​

​Example Runtime Error​


​number = int("abc")​

​Output:​​ValueError: invalid literal for int() with​​base 10: 'abc'​

​Why Exception Handling is Used​


​ .​
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.1​​try-except​
​try-except​​is 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 inside​​try​​.​
C
​2.​ ​Error handling code is written inside​​except​​.​
​3.​ ​If an exception occurs, Python jumps to the matching​​except​​block.​
​4.​ ​If no exception occurs, the​​except​​block 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​

​16.2.2 Catching Exception Object​


​We can store the exception object using​​as​​.​

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

​Output:​​invalid literal for int() with base 10: 'abc'​


eW

​16.2.3 Multiple​​except​​Blocks​
od

​Multiple​​except​​blocks are used to handle different​​errors differently.​


​Syntax​
​C

​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 matching​​except​​block.​
​4.​ ​Exception​​should 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

​16.2.4​​Handling Multiple Exceptions Together​


​Multiple exception types can be handled in one​​except​​block.​
eW

​Syntax​
​PYTHON CODE​
od

​except (ErrorType1, ErrorType2):​


​statement​

​Example 1​
​C

​PYTHON CODE​
​try:​
​value = int("abc")​
​except (ValueError, TypeError):​
​print("Invalid conversion")​

​Output:​​Invalid conversion​
​16.2.5​​else​​in Exception Handling​
​The​​else​​block 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 ​ lse​​runs only if the​​try​​block 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

​Output:​​Conversion successful: 100​

​16.2.6​​finally​
eW

​The​​finally​​block always runs.​


​Syntax​
od

​PYTHON CODE​
​try:​
​risky_code​
​except ExceptionType:​
​C

​handling_code​
​finally:​
​cleanup_code​

​Explanation​
​ .​
1 f​inally​​runs 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,​​with​​is usually cleaner than manually using​​finally​​.​
​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.7​​try-except-else-finally​​Flow​

hc
t​ry​
​|​ 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​

​16.2.8 Raising Exceptions​


​Raising an exception means creating an error manually.​

​Syntax​
​raise ExceptionType("message")​
​ .​
1 r​ aise​​is 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 ​ lain​​raise​​is used inside an​​except​​block.​
ith

​2.​ ​It re-raises the current exception.​


​3.​ ​It is useful when we want to log an error but still allow it to continue upward.​
eW

​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 from​​Exception​​.​
C
​2.​ ​They make errors more meaningful.​

hc
​3.​ ​They are useful in larger projects.​
​4.​ ​Custom exception names usually end with​​Error​​.​

​Example 1​
​PYTHON CODE​
is
N
​class InsufficientBalanceError(Exception):​
​pass​
ith

​ alance = 500​
b
​withdraw_amount = 1000​
eW

​if withdraw_amount > balance:​


​raise InsufficientBalanceError("Not enough​
​balance")​

​Output:​​InsufficientBalanceError: Not enough balance​


od

​16.2.11 Exception Hierarchy​


​BaseException​
​C

​|​
​v​
​Exception​
​|​
​├── ArithmeticError​
​├── LookupError​
​├── OSError​
​├── RuntimeError​
​├── ValueError​
​└── TypeError​
​Exception​ ​When It Happens​

​ValueError​ ​Correct type, invalid value​


​TypeError​ ​Operation with wrong type​
​NameError​ ​Name not defined​
​IndexError​ ​Invalid list/tuple index​
​KeyError​ ​Missing dictionary key​
​FileNotFoundError​ ​File does not exist​
​ZeroDivisionError​ ​Division by zero​


al
​ImportError​ ​Import fails​
​ModuleNotFoundError​ ​Module not found​

h
​PermissionError​ ​No permission for file operation​
​UnicodeDecodeError​ ​Text decoding fails​

hc
​16.2.12 Bare​​except​​Warning​
is
​A bare​​except​​catches almost everything and should​​usually 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")​

​Why Bare​​except​​is Bad​


​C

​Problem​ ​Explanation​

​Too broad​ ​Catches errors you did not expect​

​Hides bugs​ ​Makes debugging difficult​

​Poor readability​ ​Does not show what error is handled​

​Can catch system-exit style errors​ ​Not safe for normal use​
​16.2.13​​File Handling with Exception Handling​
​Error​ ​Meaning​

​FileNotFoundError​ ​File does not exist​

​PermissionError​ ​No permission​

​IsADirectoryError​ ​Expected file but got folder​

​UnicodeDecodeError​ ​Encoding issue​


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

​16.3 File Formats​


eW

​16.3.1 Text Files​


​A text file stores human-readable text.​

​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 means​​Comma-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-in​​csv​​module. CSV is commonly​​used for spreadsheets​
​and data export. Use​​newline=""​​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)​

​for row in reader:​


​print(row)​
is
​Possible output:​​['name', 'age', 'course']​
N
​['Aman', '21', 'Python']​
​['Riya', '20', 'Java']​
ith

​Writing CSV File​


​PYTHON CODE​
​import csv​
eW

​ ith open("[Link]", "w",​


w
​encoding="utf-8", newline="") as file:​
​writer = [Link](file)​
od

​ [Link](["name", "age", "course"])​


w
​[Link](["Aman", 21, "Python"])​
​C

​16.3.3​​[Link]​​vs​​[Link]​
​Tool​ ​Output Type​ ​Best Use​

​[Link]()​ ​List for each row​ ​Simple row-based reading​

​[Link]()​ ​Dictionary for each row​ ​Column-name based reading​

​[Link]()​ ​Writes rows​ ​Simple CSV writing​

​[Link]()​ ​Writes dictionaries​ ​Column-name based writing​


​16.3.4 JSON Files​
​ SON means​​JavaScript Object Notation​​. JSON is commonly​​used for APIs and​
J
​configuration files.​

​Example JSON Data​


​PYTHON CODE​
​{​
​"name": "Aman",​


​"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-in​​json​​module.​
​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​

​Reading JSON File​


​PYTHON CODE​
​import json​

​ ith open("[Link]", "r",​


w
​encoding="utf-8") as file:​
​data = [Link](file)​
​print(data["name"])​
​Writing JSON File​
​PYTHON CODE​
​import json​

​student = {​
​"name": "Aman",​
​"age": 21,​
​"course": "Python"​
​}​

​ ith open("[Link]", "w",​


w


​encoding="utf-8") as file:​

al
​[Link](student, file, indent=4)​

h
​16.3.5​​[Link]()​​vs​​[Link]()​

hc
​Function​ ​Meaning​ ​Input​

​[Link]()​ ​Reads JSON from file​


is ​File object​
N
​[Link]()​ ​Reads JSON from string​ ​JSON string​

​[Link]()​ ​Writes JSON to file​ ​File object​


ith

​[Link]()​ ​ onverts Python object to JSON​


C ​Python object​
​string​
eW

​16.3.6 XML Files​


​XML means​​Extensible Markup Language​​.​
od

​XML stores data using tags.​


​C

​Example XML Data​


​<student>​
​<name>Aman</name>​
​<age>21</age>​
​<course>Python</course>​
​</student>​
​Chapter 17. Advanced Python Concepts​
​ dvanced Python concepts help us write cleaner, memory-efficient, reusable, and​
A
​professional Python code.​
​This chapter covers:​

​ .​
1 ​ ecorators​
D
​2.​ ​Generators and Iterators​
​3.​ ​Context Managers​
​4.​ ​Regular Expressions​


al
​17.1 Decorators​

h
​17.1.1 Decorators​

hc
​ ​​decorator​​is 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

​is equal to:​


​1.​ D ​ ecorators are based on functions being first-class objects. A decorator takes a​
​function as input.​
​2.​ ​It usually defines an inner wrapper function. It returns the wrapper function.​
​3.​ ​The wrapper adds extra behavior before or after the original function.​

​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_decorator​​receives​​greet​​.​​wrapper​​adds extra behavior.​
​2.​ ​greet()​​now actually calls​​wrapper()​​. Inside​​wrapper​​,​​the original​​greet()​​is called.​
​17.1.3 Decorators with Function Arguments​
​If the decorated function has arguments, the wrapper should accept​​*args​​and​​**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

f​[Link]​​preserves the original function’s​​metadata. Without​​wraps​​, the decorated​


​function may lose its original name and docstring.​

​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 function​​to 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

​17.1.5 Decorators with Arguments​


eW

​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

​return func(*args, **kwargs)​


​return wrapper​
​return actual_decorator​

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

​17.1.6 Multiple Decorators​


ith

​A function can have more than one decorator.​


​Syntax​
eW

​PYTHON CODE​
​@decorator1​
​ decorator2​
@
​def function_name():​
od

​statement​

​NOTE:​​Decorators are applied from bottom to top.​


​C

​PYTHON CODE​
​ decorator1​
@
​@decorator2​
​def greet():​
​pass​

​is equal to:​

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

​17.1.8 Built-in and Standard Decorators​ is


​Decorator​ ​From​ ​Purpose​
N
​@staticmethod​ ​Built-in​ ​Creates static method​
ith

​@classmethod​ ​Built-in​ ​Creates class method​

​@property​ ​Built-in​ ​Creates managed attribute​


eW

​@property_name.setter​ ​Built-in​ ​Adds setter to property​

​@dataclass​ ​dataclasses​ ​Generates data class methods​

​@abstractmethod​ ​abc​ ​Defines abstract method​


od

​@wraps​ ​functools​ ​Preserves function metadata​

​@lru_cache​ ​functools​ ​Caches function results​


​C

​17.2 Generators and Iterators​


​ enerators and iterators are used to work with values one at a time. They are​
G
​memory-efficient because they do not need to store all values at once.​
​17.2.1 Iterable vs Iterator​
​Explanation​
​ n iterable is an object we can loop over. An iterator is an object that gives values one by​
A
​one using​​next()​​.​

​Term​ ​Meaning​ ​Example​


​Iterable​ ​Can be looped over​ ​list, tuple, string, dictionary, set, range​

al
​Iterator​ ​Gives next value using​​next()​ ​object from​​iter()​

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​

​17.2.2 Iterator Protocol​


od

​The iterator protocol uses two methods:​


​C

​ .​ _
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__()​​raises​​StopIteration​​.​
​4.​ ​for​​loops 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

​for number in counter:​


​print(number)​
​C

​ 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 by​​iter(object)​​.​
_

al
​2.​ ​It is also used automatically for loops.​
​3.​ ​If the object itself is the iterator, it returns​​self​​.​

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

​Output: A list_iterator object​


eW

​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 by​​next(iterator)​​.​
_
​2.​ ​It returns one value at a time.​
​3.​ ​It should raise​​StopIteration​​when there are no values​​left.​
​4.​ ​Without​​StopIteration​​, the iteration may not stop​​correctly.​

​Example 1​
​PYTHON CODE​
​numbers = iter([10, 20])​

​print(next(numbers))​
​print(next(numbers))​
​print(next(numbers))​

​ utput:​
O
​10​
​20​


​StopIteration​

al
​The third​​next()​​raises​​StopIteration​​because no values​​are left.​

h
​17.2.5 Generator Functions​

hc
​A generator function is a function that uses​​yield​​.​

​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 at​​yield​​.​
​4.​ ​When​​next()​​is called again, it continues from where​​it paused.​
od

​5.​ ​Generators are memory-efficient.​

​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.6​​yield​
is
N
​yield​​is used to return a value from a generator without​​ending the function permanently.​
ith

​Syntax​
​yield value​
eW

​ .​
1 ​ ield​​gives 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 previous​​yield​​.​
​4.​ ​When the function finishes, Python raises​​StopIteration​​.​
od

​return​​vs​​yield​
​Point​ ​return​ ​yield​
​C

​Used in​ ​Normal functions​ ​Generator functions​

​Gives​ ​Final result​ ​One value at a time​

​Function state​ ​Ends function​ ​Pauses function​

​Memory use​ ​May store full result​ ​Memory-efficient​

​Output​ ​Normal value​ ​Generator object​


​17.2.7 Generator Expressions​
​A generator expression is a short way to create a generator.​

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

​for value in squares:​


ith

​print(value)​
​ utput:​
O
​1​
eW

​4​
​9​
​16​
od

​17.2.8​​yield from​
​yield from​​is used to yield values from another iterable​​or generator.​
​C

​Syntax​
​yield from iterable​

​1.​ y ​ ield from​​simplifies 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.10​​itertools​
​itertools​​is a standard library module for working​​with iterators.​
od

​Syntax​
​C

​import itertools​

​Explanation​
​ .​
1 i​tertools​​provides memory-efficient iterator tools.​
​2.​ ​It is useful for combinations, permutations, counting, grouping, and chaining.​
​3.​ ​Many​​itertools​​functions return iterators.​
​4.​ ​Results may need to be converted using​​list()​​for​​display.​
​Common​​itertools​​Tools​
​Tool​ ​Meaning​

​count()​ ​Infinite counting​

​cycle()​ ​Repeats iterable forever​

​repeat()​ ​Repeats a value​

​chain()​ ​Joins iterables lazily​


al
​islice()​ ​Slices an iterator​

​combinations()​ ​Unique combinations​

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

​ umbers = (number for number in​


n
​range(1000000))​
​print(next(numbers))​
​print(next(numbers))​

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

​The most common example is file handling using​​with​​.​

​Syntax​
​with resource as name:​


​statement​

al
​ .​
1 ​ ontext managers are used with the​​with​​statement.​
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")​

​The file closes automatically after the​​with​​block.​


​17.3.1​​__enter__​
​__enter__​​runs at the beginning of a​​with​​block.​

​Syntax​


al
​1.​ _ ​ _enter__()​​is called when the​​with​​block starts.​​It usually prepares or opens a​

h
​resource.​
​2.​ ​The value returned by​​__enter__()​​is stored after​​as​​. It is part of the context manager​

hc
​protocol.​

​17.3.2​​__exit__​ is
​__exit__​​runs when the​​with​​block ends.​
N
​Syntax​
ith
eW

​ .​ _
1 ​ _exit__()​​is called at the end of the​​with​​block.​​It is used for cleanup.​
​2.​ ​It receives exception details if an error occurs. If it returns​​True​​, the exception is​
​suppressed.​
od

​3.​ ​If it returns​​False​​or​​None​​, the exception continues​​normally.​

​__exit__​​Parameters​
​C

​Parameter​ ​Meaning​

​exc_type​ ​Exception class/type​

​exc_value​ ​Exception object/message​

​traceback​ ​Traceback object​

​None, None, None​ ​Passed if no exception occurred​


​17.3.3​​Custom Context Manager Using Class​
​Syntax​
​PYTHON CODE​
​class ClassName:​
​def __enter__(self):​
​return self​

​def __exit__(self, exc_type, exc_value,​


​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.4​​contextlib​
​contextlib​​is a standard library module for creating​​and working with context managers.​
​C

​Syntax​
​from contextlib import contextmanager​

​ .​ c
1 ​ ontextlib​​provides utilities for context managers.​
​2.​ ​It helps create context managers without writing a full class.​
​3.​ ​The most common tool is​​@contextmanager​​. It is useful​​for simple setup-cleanup​
​logic.​
​17.3.5​​@contextmanager​
​@contextmanager​​converts a generator function into​​a context manager.​

​Syntax​
​from contextlib import contextmanager​

​ contextmanager​
@
​def manager_name():​


​setup_code​

al
​yield value​
​cleanup_code​

h
​Explanation​

hc
​ .​ C
1 ​ ode before​​yield​​works like​​__enter__​​. The yielded​​value is used after​​as​​.​
​2.​ ​Code after​​yield​​works like​​__exit__​​. Cleanup should​​be placed in​​finally​​for safety.​
is
​3.​ ​This is useful for simple context managers.​

​Class Context Manager vs​​@contextmanager​


N
​Point​ ​Class-based​ ​@contextmanager​
ith

​Uses​ ​__enter__​​,​​__exit__​ ​yield​

​Best for​ ​Complex managers​ ​Simple managers​


eW

​Code length​ ​More​ ​Less​

​16.3.6 Resource Management​


od

​Resource management means safely opening and closing resources.​

​Resource​ ​Why Context Manager Helps​


​C

​File​ ​Closes automatically​

​Database connection​ ​Disconnects safely​

​Lock​ ​Releases lock​

​Network connection​ ​Closes connection​

​Temporary setup​ ​Cleans up after use​


​17.4 Regular Expressions​
​ regular expression, or​​regex​​, is a pattern used to search, match, extract, replace, or split​
A
​text.​

​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.1​​re​​Module​
N
​Python provides the built-in​​re​​module for regular​​expressions.​
ith

​Syntax​
eW

​import re​

​Explanation​
​ .​
1 r​ e​​is Python’s regular expression module.​
od

​2.​ ​It provides functions like​​search()​​,​​match()​​,​​findall()​​,​​sub()​​, and​​split()​​.​


​3.​ ​Regex patterns are usually written as raw strings.​
​4.​ ​Raw strings use prefix​​r​.​
​C

​Raw String Example​


​ attern = r"\d+"​
p
​This is preferred over:​
​pattern = "\\d+"​

​NOTE:​​Use raw strings for regex patterns to avoid​​escape-character confusion.​


​17.4.2 Pattern Matching​
​Pattern matching means checking whether text follows a specific pattern.​

​PYTHON CODE​
​import re​

​text = "My age is 21"​


​result = [Link](r"\d+", text)​


​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

​^​ ​Start of string​ ​^Hello​

​$​ ​End of string​ ​world$​


eW

​*​ ​Zero or more​ ​a*​

​+​ ​One or more​ ​a+​

​?​ ​Zero or one​ ​a?​


od

​{n}​ ​Exactly n times​ ​a{3}​

​{n,}​ ​n or more times​ ​a{2,}​


​C

​{n,m}​ ​Between n and m times​ ​a{2,4}​

​[]​ ​Character set​ ​[abc]​

​[^]​ ​Not in set​ ​[^0-9]​

​`​ ​`​ ​OR​

​()​ ​Group​ ​(ab)+​

​\​ ​Escape character​ ​\.​


​ 7.4.4 Common Regex Character​
1
​Classes​
​Pattern​ ​Meaning​

​\d​ ​Digit, same as​​[0-9]​

​\D​ ​Non-digit​


​\w​ ​ ord character: letters, digits,​
W

al
​underscore​

​\W​ ​Non-word character​

h
​\s​ ​Whitespace​

hc
​\S​ ​Non-whitespace​

​\b​ ​Word boundary​ is


​\A​ ​Start of string​
N
​\Z​ ​End of string​
ith

​17.4.5 Groups and Capturing​


eW

​Groups are created using parentheses​​()​​.​

​They are used to capture parts of a match.​


od

​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.7​​search()​
​search()​​looks for the first match anywhere in the​​string.​
is
​Syntax​
N
​[Link](pattern, text)​
ith

​Explanation​
eW

​ .​ S
1 ​ earches the entire string. Returns the first match object.​
​2.​ ​Returns​​None​​if no match is found.​
​3.​ ​Use​​.group()​​to get matched text.​

​17.4.8​​match()​
od

​match()​​checks for a match only at the beginning of​​the string.​


​C

​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.​ ​Returns​​None​​if pattern appears later.​
​17.4.9​​fullmatch()​
​fullmatch()​​checks whether the whole string matches​​the pattern.​

​Syntax​
​[Link](pattern, text)​

​Explanation​


al
​ .​ I​t 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.10​​findall()​
​findall()​​returns all non-overlapping matches as a​​list.​
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.11​​finditer()​
​finditer()​​returns an iterator of match objects.​
​C

​Syntax​
​[Link](pattern, text)​

​ .​ I​t finds all matches. It returns match objects one by one.​


1
​2.​ ​It is useful when we need match positions.​
​3.​ ​It is more memory-friendly for large text than​​findall()​​.​
​17.4.12​​sub()​
​sub()​​replaces matched text with new 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.13​​split()​

hc
​split()​​splits a string using a regex pattern.​

​Syntax​
is
N
​[Link](pattern, text)​

​ .​ S
1 ​ plits text wherever the pattern matches.​
ith

​2.​ ​More powerful than normal string​​split()​​.​


​3.​ ​Useful when separators are multiple or irregular.​
eW

​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 like​​search()​​,​​findall()​​,​​sub()​​, and​​split()​
​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​

​CPU-bound task​ ​Task doing heavy calculation​

​Thread​
is
​Lightweight unit of execution inside a process​

​Process​ ​Independent program execution with separate memory​


N
​Async programming​ ​Single-threaded cooperative concurrency using​​async​​and​​await​
ith

​Choosing the Right Tool​


eW

​Task Type​ ​Better Tool​

​Waiting for network/API/file/database​ ​threading​​,​​ThreadPoolExecutor​​, or​​asyncio​

​Heavy CPU calculation​ ​multiprocessing​​or​​ProcessPoolExecutor​


od

​Many async network operations​ ​asyncio​

​Simple parallel task execution​ ​[Link]​


​C

​18.1 Multithreading​
​Multithreading means running multiple threads inside the same process.​

​ ython provides the​​threading​​module for thread-based​​concurrency. The official docs​


P
​describe​​threading​​as thread-based parallelism and​​also point to​​ThreadPoolExecutor​​as a​
​higher-level interface.​
​Syntax​
​import threading​

​ .​
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.1​​threading​​Module​
​The​​threading​​module provides classes and tools for​​working with threads.​
od

​Tool​ ​Purpose​

​Thread​ ​Creates and manages a thread​


​C

​Lock​ ​Prevents multiple threads from changing shared data at the same time​

​RLock​ ​Re-entrant lock; same thread can acquire it multiple times​

​Semaphore​ ​Limits how many threads can access a resource​

​Event​ ​Allows communication between threads​

​Condition​ ​Allows threads to wait for a condition​

​current_thread()​ ​Returns current thread object​


​active_count()​ ​Returns number of active threads​

​18.1.2 Creating Threads​


​Syntax​
t​hread = [Link](target=function_name)​
​[Link]()​
​[Link]()​


​Explanation​

al
​ .​
1 t​arget​​is the function that the thread will run.​

h
​2.​ ​start()​​starts the thread.​
​3.​ ​join()​​waits for the thread to finish.​

hc
​4.​ ​Without​​join()​​, the main program may continue while​​the thread is still running.​

​Example 1​ is
​PYTHON CODE​
N
​import threading​
ith

​def show_message():​
​print("Thread is running")​
eW

t​hread =​
​[Link](target=show_message)​

​[Link]()​
od

​[Link]()​

​print("Main program finished")​


​C

​Output:​

​Thread is running​

​Main program finished​


​18.1.3 Managing Threads​
​Method / Attribute​ ​Meaning​

​start()​ ​Starts thread execution​

​join()​ ​Waits for thread to finish​


​is_alive()​ ​Checks whether thread is still running​

al
​name​ ​Thread name​

h
​daemon​ ​If​​True​​, 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

​Thread 2 reads count = 0​

​Thread 1 updates count to 1​

​Thread 2 updates count to 1​

​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​
l​ock = [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.​ ​Use​​with 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.​

​Synchronization Tools Table​


​Tool​ ​Purpose​


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

​Condition​ ​Threads wait until a condition becomes true​

​Queue​
is
​Thread-safe data exchange between threads​
N
​18.2 Multiprocessing​
ith

​Multiprocessing means running multiple processes.​


eW

​ ython provides the​​multiprocessing​​module for process-based parallelism.​


P
​ProcessPoolExecutor​​is also documented as a higher-level​​interface for running tasks in​
​background processes.​
od

​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 like​​Queue​​,​​Pipe​​,​​Manager​​,​
​or shared memory.​
​Thread vs Process​
​Point​ ​Thread​ ​Process​

​Memory​ ​Shared memory​ ​Separate memory​

​Creation cost​ ​Lighter​ ​Heavier​


​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

​join()​ ​Waits for process to finish​

​is_alive()​ ​ hecks whether process is​


C
​running​
eW

​terminate()​ ​Stops process forcefully​

​pid​ ​Process ID​


od

​name​ ​Process name​

​exitcode​ ​Process exit status​


​C

​18.2.2 Process Pools​


​A process pool manages multiple worker processes.​

​Syntax​
​from multiprocessing import Pool​

​1.​ ​A pool reuses worker processes. It is useful when many tasks need to be processed.​
​ .​ I​t avoids manually creating many process objects.​
2
​3.​ ​For many cases,​​ProcessPoolExecutor​​is simpler and​​more modern.​

​18.2.3 Memory Sharing Basics​


​Processes have separate memory by default.​

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

​[Link]​ ​Shared list/dict-like objects​


N
​[Link]​ ​Shared single value​
ith

​[Link]​ ​Shared array​

​multiprocessing.shared_memory​ ​Direct shared memory block​


eW

​18.3 Concurrent Futures​


od

​ he​​[Link]​​module provides a high-level​​interface for running callables​


T
​asynchronously using threads, processes, or interpreters. The main executors are​
​ThreadPoolExecutor​​and​​ProcessPoolExecutor​​.​
​C

​Syntax​
​from [Link] import ThreadPoolExecutor​

​from [Link] import ProcessPoolExecutor​

​Explanation​
​1.​ ​[Link]​​is easier than manually creating​​threads/processes.​
​ .​ I​t uses executors to manage workers. It returns​​Future​​objects.​
2
​3.​ ​A​​Future​​represents a result that may not be ready​​yet.​
​4.​ ​It is useful for running many tasks concurrently.​

​18.3.1​​ThreadPoolExecutor​
​ThreadPoolExecutor​​runs tasks using a pool of threads.​ ​Best for I/O-bound tasks​

​Example 1​


al
​PYTHON CODE​
f​rom [Link] import​
​ThreadPoolExecutor​

h
hc
​def square(number):​
​return number * number​

​with ThreadPoolExecutor() as executor:​


is
​results = [Link](square, [1, 2, 3, 4])​
N
​print(list(results))​
ith

​Output: [1, 4, 9, 16]​


eW

​18.3.2​​ProcessPoolExecutor​
​ProcessPoolExecutor​​runs 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​

​if __name__ == "__main__":​


​with ProcessPoolExecutor() as executor:​
​results = [Link](square, [1, 2, 3, 4])​
​print(list(results))​
​Output: [1, 4, 9, 16]​

​18.3.3 Futures​
​A​​Future​​represents a task that may complete later.​

​Method​ ​Meaning​

​result()​ ​Gets result, waits if needed​


al
​done()​ ​Checks whether task is completed​

​cancel()​ ​Attempts to cancel task​

h
​cancelled()​ ​Checks whether task was cancelled​

hc
​exception()​ ​Returns exception if task failed​

​add_done_callback()​ ​Runs callback when task finishes​


is
N
​Example 1​
ith

​PYTHON CODE​
f​rom [Link] import​
​ThreadPoolExecutor​
eW

​def square(number):​
​return number * number​

​with ThreadPoolExecutor() as executor:​


od

​future = [Link](square, 5)​


​C

​print([Link]())​

​Output: 25​

​18.4 Async Programming​


​Async programming is used to write concurrent code using​​async​​and​​await​​.​

​ ython’s official​​asyncio​​documentation describes​​it as a library for writing concurrent code​


P
​using​​async​​/​await​​, commonly used for high-performance​​network servers, web servers,​
​ atabase libraries, and distributed task queues.​​Best for I/O-bound tasks with many​
d
​waiting operations​

​18.4.1​​asyncio​
​asyncio​​is Python’s standard library module for asynchronous​​programming.​

​Syntax​


​import asyncio​

al
​ .​
1 ​ syncio​​runs asynchronous tasks.​
a
​2.​ ​It uses an event loop.​

h
​3.​ ​It is usually single-threaded cooperative concurrency.​

hc
​4.​ ​Tasks pause when they reach​​await​​.​
​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.2​​async​​and Coroutines​
​A coroutine is created using​​async def​​.​
​C

​Syntax​
​async def function_name():​
​statement​

​Explanation​
​ .​ a
1 ​ sync def​​defines 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​

​async def greet():​


​print("Hello async")​

al
​[Link](greet())​

h
hc
​Output: Hello async​

​18.4.3​​await​ is
N
​await​​pauses a coroutine until an awaitable finishes.​

​Syntax​
ith

​await awaitable​
eW

​Explanation​
​ .​ a
1 ​ wait​​can be used only inside​​async def​​. It pauses​​the current coroutine.​
​2.​ ​It allows the event loop to run other tasks.​
od

​3.​ ​It is used with coroutines, tasks, and async operations.​

​Example 1​
​C

​PYTHON CODE​
​import asyncio​

​async def main():​


​print("Start")​
​await [Link](1)​
​print("End")​
​[Link](main())​
​Output: Start​

​End​

​18.4.4 Event Loop​


​The event loop manages and runs async tasks.​

​ .​ T
1 ​ he event loop schedules coroutines. It switches between tasks when they await.​
​2.​ ​[Link]()​​creates and manages the event loop for​​most programs.​


​3.​ ​Beginners should usually use​​[Link]()​​instead​​of 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 task​​gets​​the final result.​
ith

​Example 1​
eW

​PYTHON CODE​
​import asyncio​

​async def work(name):​


od

​await [Link](1)​
​print(name, "done")​
​C

​async def main():​


​task1 = asyncio.create_task(work("Task 1"))​
​task2 = asyncio.create_task(work("Task 2"))​

​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 concurrently​​and collects their results.​

​18.4.7 Async Futures​


al
​An​​[Link]​​represents a result that may be​​available 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 usually​​for low-level callback-based code and​
​recommend not exposing Future objects in user-facing APIs.​
N
​Future Comparison​
ith

​Type​ ​Module​ ​Used With​

​[Link]​ ​[Link]​ ​Thread/process executors​


eW

​[Link]​ ​asyncio​ ​Event loop and async tasks​

​18.4.8 Async Context Managers​


od

​Async context managers are used with​​async with​​. They​​use:​

​__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 with​​is 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 use​​await​​.​


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​

​ sync def __aexit__(self, exc_type,​


a
eW

​exc_value, traceback):​
​print("Exiting async context")​

​async def main():​


od

​async with AsyncManager():​


​print("Inside async context")​
​C

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

​Memory​ ​Shared​ ​Separate​ ​Shared in same thread​

h
​Best for​ I​/O-bound blocking​ ​CPU-bound work​ ​I/O-bound non-blocking work​

hc
​work​

​Runs in​ ​Same process​ ​Separate processes​ ​Event loop​

​Communication​ ​Shared data, queue​


is ​ ueue, pipe,​
Q
​manager​
​Awaitables, tasks​
N
​Main risk​ ​Race conditions​ ​Process overhead​ ​Blocking the event loop​
ith

​Common tool​ ​threading​ ​multiprocessing​ ​asyncio​

​Important Async Rule​


eW

​Do not put long blocking code inside async functions.​

I​f 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

​SOME LOVE BY FOLLOWING​​CodeWithNishchal on social​​media:​


​●​ ​Instagram:​​[Link]
​●​ ​LinkedIn:​​[Link]
​●​ ​YouTube:​​[Link]
​●​ ​Telegram​​[Link]
​●​ ​Watch My Latest Time Complexity Series:​​Time Complexity​
​●​ ​Join My IG Community for Tech discussions :​​CodeN' community​

You might also like