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

Python - Complete - MSS - Google Docs

The document is a comprehensive tutorial on Python, covering its definition, features, advantages, and installation procedures. It discusses various topics such as data types, control statements, object-oriented programming, and popular libraries like Pandas and Numpy. Additionally, it compares Python with C++, highlighting differences in typing, execution, and portability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

Python - Complete - MSS - Google Docs

The document is a comprehensive tutorial on Python, covering its definition, features, advantages, and installation procedures. It discusses various topics such as data types, control statements, object-oriented programming, and popular libraries like Pandas and Numpy. Additionally, it compares Python with C++, highlighting differences in typing, execution, and portability.
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 - Tutorial​

​*Python Topics:*​
​∙​ ​ ython definition, Introduction - Characteristics, Pros, Cons, Installation procedure.​
P
​∙​ ​Data Types, Operators, Variables.​
​∙​ ​Access Modifiers, Decision-Making concepts, Control statements, Modules​
​∙​ ​Loops, Functions, File I/O, Exceptions​
​∙​ ​Monkey​ ​patching,​ ​Decorators,​ ​Multiprocessing,​ ​Multi-threading,​ ​JSON​ ​package​
​explanation, and usage​
​∙​ ​OOPS​ ​-​ ​Class,​ ​Object,​ ​Inheritance,​ ​Polymorphism,​ ​Encapsulation,​ ​Constructor,​
​Abstraction​
​∙​ ​Pandas, Numpy, XML programming, Sockets, Sending email...​
​∙​ ​Regular expressions and their types, Web scraping​
​∙​ ​API frameworks - Flask, Django, FastAPI, Streamlit, Starlette​
​∙​ ​Servers - Werkzeug, Uvicorn, Waitress, Gunicorn. Monitoring Tool - Supervisor​

​Python Introduction​
​ ython​ ​is​ ​one​ ​of​ ​the​ ​most​ ​popular,​ ​widely​ ​used​ ​programming​ ​language​ ​general-purpose​
P
​interpreted,​​interactive,​​object-oriented,​​and​​high-level​​programming​​language​​that​​focuses​​on​
​code​​readability.​​Python​​is​​a​​dynamically​​typed​​and​​garbage-collected​​programming​​language.​​a​
​Dutch​ ​Programmer​ ​Guido​ ​van​ ​Rossum​ ​created​ ​it​ ​during​ ​1985-​ ​1990​ ​at​ ​the​ ​National​ ​Research​
​Institute​​for​​Mathematics​​and​​Computer​​Science​​in​​the​​Netherlands.​ ​.​​Because​​of​​its​​simpler​​syntax,​
​extensive​ ​features​ ​and​ ​support​ ​of​ ​libraries​​it​​is​​used​​mostly.​​Python​​does​​not​​have​​any​​relation​​to​
S​ nake.​​The​​name​​of​​the​​Python​​programming​​language​​was​​inspired​​by​​a​​British​​Comedy​​Group​​Monty​
​Python a popular comedy series ​Monty Python's Flying Circus​​on BBC. .​

​Listed are some of the key advantages of learning Python:​

​ ython​ ​is​ ​a​ ​general-purpose​ ​language​ ​-​ ​It​ ​is​ ​used​ ​in​ ​various​ ​areas​ ​of​ ​applications​ ​such​ ​as​
p
​Machine​ ​Learning,​ ​Artificial​ ​Intelligence,​ ​web​ ​development,​ ​IoT,​ ​and​ ​more..​ ​Examples​ ​of​
​general-purpose​ ​languages​ ​include​ ​Python,​​Java,​​C++,​​and​​JavaScript.​​Unlike​ ​SQL​​for​​database​
​querying(Domain specific langauage DSL)​

​ ython​ ​is​ ​Interpreted​ ​−​ ​The​​interpreter​​takes​​one​​instruction​​from​​the​​source​​code​​at​​a​​time​​,​


P
​translates​ ​it​ ​into​ ​machine​ ​code,​ ​and​ ​executes​ ​it​​.​ ​With​ ​this​ ​feature,​ ​it​ ​is​ ​easier​ ​to​ ​debug​ ​the​
​program​

​ ython​ ​is​ ​Interactive​ ​−​ ​Python​ ​comes​ ​with​ ​an​ ​interactive​ ​shell​​that​​works​​on​​the​​principle​​of​
P
​REPL​​(​Read​​–​​Evaluate​​–​​Print​​–​​Loop).​ ​You​​can​​actually​​sit​​at​​a​​Python​​prompt​​and​​interact​
​with the interpreter directly to write your programs.​

​ ython​ ​is​ ​Object-Oriented​ ​−​ ​Python​ ​supports​ ​Object-Oriented​ ​style​ ​or​ ​technique​ ​of​
P
​programming that encapsulates code within objects.​

​The shell presents a Python prompt >>>.​

​∙​ ​ pen​ ​the​ ​command​ ​prompt​ ​and​ ​type​ ​python​ ​there​ ​you​ ​can​ ​enter​ ​into​ ​python​
o
​interactive mode.​
​∙​ ​You can type any valid Python expression and press Enter.​
​∙​ ​The​ ​interactive​ ​mode​ ​is​ ​especially​ ​useful​ ​for​ ​getting​ ​familiar​ ​with​ ​a​ ​library​ ​and​
​testing out its functionality.​

​Features of Python​
​∙​ ​ ython is simple and Open Source which means it's available free of cost.​
P
​∙​ ​Python​ ​is​ ​versatile​ ​and​ ​can​ ​be​ ​used​ ​to​ ​create​ ​many​ ​different​ ​things​ ​like​ ​web​
​development (server-side), software development, mathematics, and system scripting.​
​∙​ ​Python​​has​​powerful​​development​​libraries​​including​​AI,​​ML,​​etc,​​and​​extensive​​support​
​libraries(NumPy for numerical calculations, Pandas for data analytics, etc).​
​∙​ ​Python has elegant syntax and dynamic typing.​
​∙​ ​Python​ ​is​ ​platform-independent​ ​Cross-platform,​ ​which​ ​means​ ​it​ ​works​ ​on​ ​different​
​platforms (Windows, Mac, Linux, Raspberry Pi, etc).​
​∙​ ​Known​ ​for​ ​its​ ​readability,​ ​which​ ​means​ ​code​ ​is​ ​easier​ ​to​ ​write,​ ​understand​ ​and​
​maintain.​
​∙​ ​Dynamically​​typed​​language(No​​need​​to​​mention​​data​​type​​based​​on​​the​​value​​assigned,​
​it takes data type)​
​∙​ ​Object-oriented and Procedural Programming language​
​∙​ ​High-level language, Interpreted Language.​
​∙​ ​In​ ​Python,​ ​Indentation​ ​is​ ​used​ ​to​ ​define​ ​blocks​ ​of​ ​code.​ ​It​ ​tells​ ​the​ ​Python​
​interpreter​​that​​a​​group​​of​​statements​​belongs​​to​​a​​specific​​block.​​All​​statements​
​with the same level of indentation are considered part of the same block​
​∙​ ​Automatic​​Memory​​Management:​​Python​​offers​​automatic​​memory​​management,​
​which​ ​means​ ​developers​ ​do​ ​not​ ​require​ ​to​ ​allocate​ ​or​ ​deallocate​ ​memory​
​manually.​ ​The​ ​memory​ ​manager​ ​of​ ​Python​ ​handles​ ​object​ ​creation,​ ​memory​
​allocation, garbage collection, and memory optimization automatically.​

​Con's of Python​
​ erformance​​:​ ​Python​ ​is​ ​an​ ​interpreted​ ​language,​ ​which​ ​means​ ​that​ ​it​ ​can​ ​be​ ​slower​ ​than​
P
​compiled languages like C or Java. This can be an issue for performance-intensive tasks.​

​ emory​ ​consumption​​:​ ​Python​ ​can​ ​consume​ ​a​ ​lot​ ​of​ ​memory,​ ​especially​ ​when​ ​working​ ​with​
M
​large datasets or running complex algorithms.​

​ ynamically​ ​typed​​:​ ​Python​ ​is​ ​a​ ​dynamically​ ​typed​ ​language,​ ​which​ ​means​ ​that​ ​the​ ​types​ ​of​
D
​variables​​can​​change​​at​​runtime.​​This​​can​​make​​it​​more​​difficult​​to​​catch​​errors​​and​​can​​lead​​to​
​bugs.​

​ ackaging​ ​and​ ​versioning​​:​ ​Python​ ​has​ ​a​ ​large​ ​number​ ​of​ ​packages​ ​and​ ​libraries,​ ​which​ ​can​
P
​sometimes lead to versioning issues and package conflicts.​

​Download and Install Python 3​


​Downloading Python on Windows​

​∙​ ​open a browser and type​​[Link]


​∙​ ​Under the Python Releases for Windows find the Latest Python 3 Release​
​∙​ ​click​ ​on​ ​Windows​ ​x86-64​ ​executable​ ​installer​ ​for​ ​64-bit​ ​or​ ​Windows​ ​x86​ ​executable​
​installer for 32-bit.​

​Installing Python on Windows​

​∙​ ​ pen the downloads folder and click on Python that you have installed on your PC.​
O
​∙​ ​Make​​sure​​to​​mark​​Add​​Python​​3.11​​to​​PATH​​otherwise​​you​​will​​have​​to​​do​​it​​explicitly.​​It​
​will start installing Python on Windows.​
​∙​ ​Installation is complete​
​∙​ ​Now go to Windows and type IDLE. This is Python Interpreter also called Python Shell.​

∙​​ T​ o close the interactive session, type "quit()" or "exit()".​


​∙​ ​To list out all the installed versions of Python use the command "where python"​

​Checking the installation is successful or not​


​ Python is the standard and official implementation of Python, written in C.​
C
​It compiles Python source code to bytecode and executes it using the Python Virtual​
​Machine.​
​There are other implementations like PyPy (with JIT for high performance), Jython (runs​
​on JVM), IronPython (runs on .NET), and Cython (optimizes Python using C).​
​It’s called “C-Python” because:​
👉 It is​​written in C language​

👉 It compiles Python source code into​​bytecode (.pyc)​

👉 It executes bytecode using the​​PVM (Python Virtual​​Machine)​

​So: CPython = Python compiler + PVM + runtime.​
​This is the version​​99% of the world uses​
​1. CPython (Official, default)​


​ Written in C​
​✔ Generates .pyc​
​✔ Uses PVM​
​✔ Most stable, most libraries support it​
​✔ Slower than Java but reliable​

🔶
​ ​​2. PyPy​​(Fast Python – JIT Compiler)​

​ Written in RPython​
​✔ Has​​Just-In-Time (JIT) compiler​
​✔ Much faster than CPython in long-running programs​
​✔ Great for loops, heavy functions​
❌ ​ Not all libraries support it (especially C-extensions)​
💭 PyPy is Python with a turbocharger.​

🔶
​ ​​3. Jython​​(Python on Java)​

​ Written in Java​
​✔ Runs on JVM​
​✔ Allows mixing Python + Java​
​✔ Can import Java libraries directly​
❌ ​ Slower development​
❌ ​ Not fully updated to latest Python versions​
💭​ Good when working with Java ecosystems.​
🔶
​ ​​4. IronPython​​(Python on .NET)​

​ Written in C#​
​✔ Runs on .NET CLR​
​✔ Can use C#, .NET libraries​
❌ ​ Limited community support​
❌ ​ Not the latest Python version​
💭​ Ideal for Microsoft/.NET environments.​
🔶
​ ​​5. Cython​

​ Not a full implementation​
​✔ Helps convert Python code → C for​​speed​
​✔ Mostly used to optimize performance​
​✔ Used heavily in machine learning libraries (NumPy, Pandas internals)​
💭 Cython is like giving Python a gym membership to get stronger.​

​ ython​ ​is​ ​both​ ​a​ ​programming​ l​anguage​ a​ nd​ ​a​ ​scripting​ ​[Link]​ ​is​ a​ ​ ​high-level,​
P
​general-purpose​ ​language,​ ​so​ ​we​ ​use​ ​it​ ​to​ ​build​ ​complete​ ​applications​ ​like​ ​APIs​ ​or​ ​data​
​pipelines.​

​ t​​the​​same​​time,​​Python​​can​​also​​be​​used​​as​​a​​scripting​​language​​for​​automation,​​quick​​tasks,​
A
​and running scripts without compilation.​

​ irtual​​Environments​​:​​Python​​supports​​virtual​​environments​​(venv)​​which​​helps​​isolating​
V
​the​​dependencies​​for​​different​​projects.​​This​​also​​helps​​preventing​​package​​conflicts​​and​
​ensuring each project runs with the required library versions.​

​ EP​​8​:​​Python's​​official​​style​​guide​​promotes​​best​​practices​​such​​as​​meaningful​​variable​
P
​names,​ ​consistent​ ​indentation,​ ​proper​ ​spacing,​ ​and​ ​a​ ​79-character​ ​line​ ​limit​ ​for​ ​better​
​code readability and maintainability.​

​ ip​ ​is​ ​the​ ​Python​ ​Package​ ​Installer.​ ​It​ ​is​ ​used​ ​to​ ​install,​​upgrade,​​and​​manage​​Python​​libraries​
p
​from​ ​the​ ​Python​ ​Package​ ​Index​ ​(PyPI).​ ​Tools​ ​like​ ​[Link]​ ​and​ ​virtual​ ​environments​
​depend on pip for dependency management.​

​ urpose​
P ​ ommand​
C
​Run a Python file​ ​python [Link]​
​Run with Python 3​ ​python3 [Link]​
​Open Python shell​ ​python​
​Check Python version​ ​python --version​
​Run a module​ ​python -m module_name​
​Disassemble to view​
​python -m dis [Link]​
​bytecode​

​ urpose​
P ​ ommand​
C
​Install a package​ ​pip install package_name​
​Install specific version​ ​pip install package==1.2.3​
​Upgrade a package​ ​pip install --upgrade package_name​
​Uninstall package​ ​pip uninstall package_name​
​List installed packages​ ​pip list​
​Show package details​ ​pip show package_name​
​Create requirements file​ ​pip freeze > [Link]​
​Install from requirements​
​pip install -r [Link]​
​file​

​ urpose​
P ​Command​
​Create virtual​
​python -m venv venv​
​environment​
​Activate venv (Windows)​ ​venv\Scripts\activate​
​ ctivate venv​
A
​source venv/bin/activate​
​(Mac/Linux)​
​Deactivate venv​ ​deactivate​
​Difference Between Python and C++​

​The following table summarizes the differences between Python and C++​

​Criteria​ ​Python​ ​C++​

​ ython is an interpreted-based​
P ​ ++ is a compiler-based​
C
​programming language. Python​ ​programming language. C++​
​Execution​
​programs are interpreted by an​ ​programs are compiled by a​
​interpreter.​ ​compiler.​

​ ython is a dynamic-typed​
P
​Typing​ ​C++ is a static-typed language.​
​language.​

​ ython is a highly portable​


P ​ ++ is not a portable language,​
C
​language, code written and​ ​code written and executed on a​
​Portability​
​executed on a system can be easily​ ​system cannot be run on another​
​run on another system.​ ​system without making changes.​

​ ython provides a garbage​


P
​ ++ does not provide garbage​
C
​collection feature. You do not need​
​ arbage​
G ​collection. You have to take care of​
​to worry about the memory​
​collection​ ​freeing memories. It is manual in​
​management. It is automatic in​
​C++.​
​Python.​

​ ython's syntaxes are very easy to​


P
​Syntax​ ​C++'s syntaxes are tedious.​
​read, write, and understand.​

​ erformanc​ P
P ​ ython's execution performance is​ ​ ++ codes are faster than Python​
C
​e​ ​slower than C++'s.​ ​codes.​

​Python's application areas are​ ​ ++'s application areas are​


C
​ pplication​
A
​ achine learning, web applications,​ ​embedded systems, device​
m
​areas​
​and more.​ ​drivers, and more.​
​Python - Script Mode Programming​

​way to execute a Python script​

​ e​ ​assume​ ​that​ ​you​ ​have​ ​Python​ ​interpreter​ ​available​ ​in​ ​/usr/bin​ ​directory.​ ​Now,​
W
​try to run this program as follows −​

​Different Aspects of Python Syntax:​

​The following are the different aspects of Python Syntax:​

​•​ ​Variables​
​•​
​Identifiers​
​•​
​Keywords​
​•​
​Comments​
​•​
​Input from Users​

​Python Variables​
​ ariables​ ​in​ ​Python​​are​ ​used​ ​to​ ​store​ ​data​ ​values.​ ​Unlike​ ​other​ ​languages,​ ​Python​
V
​variables​ ​do​ ​not​ ​require​ ​explicit​ ​declaration​ ​of​ ​type;​ ​they​ ​are​ ​dynamically​ ​typed.​ ​This​
​ eans​ ​that​​the​​type​​of​​variable​​is​​determined​​at​​runtime​​based​​on​​the​​value​​assigned​​to​
m
​it.​

​Output:​

​10 -> <class 'int'>​

​TpointTech -> <class 'str'>​

I​dentifiers​​are​ ​names​ ​used​ ​for​​variables,​​functions,​​classes,​​and​​other​​entities​​in​​Python.​


​They must follow specific rules to be valid:​

​1.​ I​t can contain letters (A-Z, a-z), digits (0-9), and underscores (_).​
​2.​ ​It cannot start with a digit.​
​3.​ ​We cannot use Python keywords as identifiers.​
​4.​ ​Case-sensitive (MyVar and myvar are different identifiers).​
​5.​ ​It​ ​should​ ​be​ ​descriptive​ ​and​ ​follow​ ​naming​ ​conventions​ ​(e.g.,​ ​using​
​snake_case for variables and functions and CamelCase for class names).​

​Python Keywords​
​ eywords​​are​​reserved​​words​​in​​Python​​that​​cannot​​be​​used​​as​​variable​​names.​​Examples​
K
​include if, else, while, for, def, class, import, etc. Python has​​35 keywords​​(Python 3.10+).​

​ eyword​
K ​Meaning / Use​
​False​ ​Boolean false value​
​True​ ​Boolean true value​
​ one​
N ​ epresents null / no value​
R
​and​ ​Logical AND operator​
​or​ ​Logical OR operator​
​not​ ​Logical NOT operator​
​as​ ​Used to create alias (modules, exceptions)​
​Debugging check; raises error if condition​
​assert​
​fails​
​ reak​
b ​Exit loop immediately​
​continue​ ​Skip to next loop iteration​
​class​ ​Define a class​
​def​ ​Define a function or method​
​del​ ​Delete variable/object/item​
​elif​ ​Else-if condition​
​else​ ​Else condition block​
​except​ ​Catch an exception​
​finally​ ​Always executed after try–except​
​for​ ​Loop keyword​
​while​ ​Loop keyword​
​from​ ​Import specific module parts​
​import​ ​Import module​
​global​ ​Declare global variable inside function​
​nonlocal​ ​Access outer function variable​
​if​ ​Conditional statement​
​in​ ​Membership operator (value in sequence)​
​is​ ​Identity comparison (checks object identity)​
​lambda​ ​Create anonymous function​
​pass​ ​Placeholder; does nothing​
r​ aise​ ​ aise an exception manually​
R
​return​ ​Return a value from function​
​try​ ​Try block for exception handling​
​ ith​
w ​ ontext manager (auto resource handling)​
C
​yield​ ​Return generator value​
​Python Comments​
​ omments​ ​in​​Python​​are​​used​​to​​explain​​code​​and​​make​​it​​more​​[Link]​​are​
C
​ignored​ ​by​ ​the​ ​Python​ ​interpreter,​ ​meaning​ ​they​ ​do​ ​not​ ​affect​ ​the​ ​execution​ ​of​ ​the​
​program.​

​Taking Input from User in Python​


I​n​​Python,​​we​​use​​the​​input()​​function​​to​​take​​user​​input.​​The​​input​​is​​always​​received​​as​​a​
​string, even if the user enters a number.​
​Casting Python Variables​
​ ype​​casting​​refers​​to​​the​​process​​of​​converting​​the​​value​​of​​one​​data​​type​​into​​another.​
T
​Python​ ​provides​​several​​built-in​​functions​​to​​facilitate​​casting,​​including​​int(),​​float()​​and​
​str() among others.​

​ ​​1.​​int("10.5")​​→ Error​
​"10.5" is a​​floating-point string​​, not an integer​​string.​
​int() can only convert:​
​•​ ​"10" → ✔ valid integer​
​Not:​
​•​ "​ 10.5" →❌ contains a dot​
​•​ ​"5e3" → ❌ exponential form​
​•​ ​"abc" → ❌ not numeric​
​Real reason:​
​int() expects​​whole number characters only​​.​


​ ​​2.​​int("abc")​​→ Error​
​Reason​
"​ abc" is​​not numeric​​.​
​Python has no way to convert alphabets to an integer.​

​ ​​3.​​float("abc")​​→ Error​
​Reason​
​float() expects numeric text:​
​•​ "​ 10"​
​•​ ​"10.5"​
​•​ ​"2e5"​

​"abc" is not numeric → conversion not defined.​



​ ​​4.​​list(10)​​or​​list(10.5)​​→ TypeError​
​Reason​
​list() only converts​​iterable​​objects into a list.​
​Iterables:​
​Strings, tuples, lists, sets, dictionaries.​
​ on-iterables:​
N
​Integers, floats, booleans.​
​10 is not something Python can loop over → ❌​

​ ​​5.​​tuple(10)​​→ Error​
​Same reason as list.​
​10 is not iterable → Python cannot break it into pieces.​

​ ​​6.​​set(10)​​→ Error​
​Again, sets require​​iterables​​.​
s​ et("abc") → works​
​set([1,2,3]) → works​
​set(10) → ❌ non-iterable​

​ ​​7.​​dict("abc")​​→ Error​
​Reason​
​A dictionary needs​​key-value pairs​​.​
​ictionary expects​​pair-like​​structure:​
​•​ l​ist/tuple of 2-element items​
​•​ ​{key: value}​

​ ype​
T
​What It Expects (Works For)​ ​Not Possible (Fails For)​
​Cast​
-​ Integer strings → "10" - Floats → 10.5​ ​- Float strings → "10.5" -​
​int()​
​(converted to 10) - Boolean → True/False​ ​Non-numeric strings → "abc"​
​- Numeric strings → "10", "10.5" - ints →​
​float()​ ​- Non-numeric strings → "xyz"​
​10 - booleans → True, False​
​str()​ ​ nything​​→ numbers, lists, tuples​
A ​✔ Never fails​
​Any object (empty → False, non-empty →​
​bool()​ ​✔ Never fails​
​True)​
​list()​ ​Iterable objects → "abc", (1,2,3), [1,2]​ ​Non-iterables → 10, 10.5, True​
​tuple()​ ​Iterable objects → "hi", [1,2]​ ​Non-iterables → 10, 10.5​
​set()​ ​Iterable objects → "hello", [1,2,3]​ ​Non-iterables → 10, 10.5​
I​terable of​​key-value pairs​​→​ -​ Strings → "abc" - Non-pair lists →​
​dict()​
​[("a",1),("b",2)]​ ​[1,2,3] - Non-iterables → 10​
​One-Line Summary​
​•​ i​nt() / float()​​→ needs numeric text​
​•​ ​list() / tuple() / set()​​→ needs iterable​
​•​ ​dict()​​→ needs iterable of 2-value items​
​•​ ​str() / bool()​​→ always works​

​Do list, tuple, set allow duplicates?​

​Allows​
​Type​ ​Ordered?​ ​Mutable?​
​ uplicates?​
D
​list​ ​✔ Yes​ ​✔ Yes​ ​✔ Yes​
​tupl​
​e​
​✔ Yes​ ​✔ Yes​ ❌ No​

​set​ ​ ❌ No​ ❌
​ ​ ✔
​ Mutable (but elements must be​
​Unordered​ ​immutable)​

​Python Collections Comparison Table​

​ eature​
F ​List​ ​Tuple​ ​Set​ ​ ictionary​
D
​ yntax​
S ​[ ]​ ​( )​ ​{ }​ ​{ key: value }​

​Ordered​ ​✔ Yes​ ​✔ Yes​ ❌ No​



​✔ Yes (Python​
​3.7+)​
​ llows​
A
​✔ Yes​ ​✔ Yes​ ​❌ No​
🔶 ​ Keys ❌ ,​
​Duplicates​ ​Values ✔​

​Mutable​ ​✔ Yes​ ❌ No​




​ Yes (but elements​
​must be immutable)​
​✔ Yes​

​Indexing​ ​✔ Yes​ ​✔ Yes​ ❌ No​




​ Keys can be​
​accessed​
​Slicing​ ​✔ Yes​ ​✔ Yes​ ​❌ No​ ❌​ No​
​ ynamic data,​
D ​ ixed data,​ U
F ​ nique items, fast​ ​ ey–value​
K
​Use Case​
​frequent updates​ ​read-only​ ​membership test​ ​mapping​

​•​ ​ amel​​case −​​First​​letter​​is​​a​​lowercase,​​but​​first​​letter​​of​​each​​subsequent​​word​


C
​is in uppercase. For example: kmPerHour, pricePerLitre​
​•​ ​ ascal​ ​case −​ ​First​ ​letter​ ​of​ ​each​ ​word​ ​is​ ​in​ ​uppercase.​ ​For​ ​example:​
P
​KmPerHour, PricePerLitr​​e​
​•​ ​Snake​ ​case​​−​ ​Use​ ​single​ ​underscore​ ​(_)​ ​character​ ​to​ ​separate​ ​words.​ ​For​
​example: km_per_hour, price_per_litre​
​Access Modifiers :​
​ ython​ ​is​ ​an​ ​object-oriented​ ​programming​ ​language​ ​that​ ​allows​ ​you​ t​ o​ ​create​
P
​classes​ ​and​ ​objects.​ ​Encapsulation​ ​is​ ​one​ ​of​ ​the​ ​core​ ​principles​ ​of​ ​OPPs.​ ​To​
​achieve ​encapsulation​​, we use private variables and​​methods. ​

​ ython​​does​​NOT​​have​​true​​access​​modifiers​​like​​Java​​or​​C++.​​Instead,​​it​​uses​​naming​
P
​conventions.​

​1. Public​
​ nything without underscores​
A
​Accessible from anywhere: inside class, outside class, subclass, modules.​

​2. Protected​
​Prefix with one underscore _​
​Used to indicate: “internal use – don’t access directly”​
​But still accessible—Python DOES NOT restrict it.​
​Protected variable can be accessed within the class and its subclasses. ​
​3. Private​​(name-mangled)​
​Prefix with​​two underscores​​__​
​ ython performs​​name mangling​​→ internally changes​​name to​
P
​_ClassName__variable.​
​This prevents accidental access​
​Private variables are only accessible within the class they are defined in. ​

​ _init__​ ​is​ ​the​ ​constructor​ ​in​ ​[Link]​ ​runs​ ​automaticallyWhenever​ ​you​ ​create​ ​an​
_
​object:​
​obj = MyClass() Python automatically calls: MyClass.__init__(obj)​
​self represents​​the current object (instance) calling the method​​.​

​Python Data Types​

​ he data types are used to define the type of a variable. It represents the type of​
T
​data we are going to store in a variable and determines what operations can be​
​done on it. Since Python is dynamically typed, the data type of a variable is​
​determined at runtime based on the assigned value.​

​Types of Data Types in Python​

​Python has 7 core built-in data types, grouped into categories.​

​Numeric​​: int, float, complex​

​Sequence​​Type​​: string, list, tuple​

​Mapping​​Type​​: dict​

​Boolean​​: bool​

​Set Type​​: set, frozenset​

​Binary Types​​: bytes, bytearray, memoryview​


​None Type:​​None​

🟩
​ ​​1. Numeric Types​

​ ython numbers represent data that has a numeric value. A numeric value can be an​
P
​integer, a floating number or even a complex number. These values are defined as int,​
​float and complex classes.​

​ ype​
T ​Description​ ​ xample​
E
​int​ ​Whole numbers​ ​10, -5, 1000​
​ ecimal numbers,characters e E​ 1
D ​ 0.5,​
​float​
​allowed positive or negative​ ​3.14,10.5e4​
​ omple​ ​Numbers with real + imaginary​
c
​3+4j​
​x​ ​parts​
🟪
​ ​​2. Sequence Types​

​ equence is a collection data type. It is an ordered collection of items. Items in the​


S
​sequence have a positional index starting with 0.​

​ ython string​​​is a sequence of one or more Unicode​​characters, enclosed in single,​


P
​double or triple quotation marks (also called inverted commas). Python strings are​
​immutable which means when you perform an operation on strings, you always​
​produce a new string object of the same type, rather than mutating an existing​
​string.​

​ ython Lists​​​are the most versatile compound data​​types. A Python list contains​
P
​items separated by commas and enclosed within square brackets ([]). To some​
​extent, Python lists are similar to arrays in C. One difference between them is that​
​all the items belonging to a Python list can be of different data type where as C​
​array can store elements related to a particular data type.​

​ ython tuple​​​is another sequence data type that is​​similar to a list. A Python tuple​
P
​consists of a number of values separated by commas. Unlike lists, however, tuples​
​are enclosed within parentheses (...).​

​◦​ ​ s in case of a list, an item in the tuple may also be a list, a tuple itself or​
A
​an object of any other Python class.​

​◦​ ​ o form a tuple, use of parentheses is optional. Data items separated by​
T
​comma without any enclosing symbols are treated as a tuple by default.​

​Ordered​ ​Mutable​ ​Allows​


​Type​ ​Example​
​?​ ​?​ ​Duplicates?​
​str​ ​✔​ ​ ​❌ ​✔​ "​ hello"​
​list​ ​✔​ ​✔​ ​✔​ ​[1,2,3]​
t​ uple​​✔​ ​ ​ ❌ ​✔​ ​(1,2,3)​
​These support indexing and slicing.​

🟧
​ ​​3. Set Types​

​ et​​​is a Python implementation of set as defined in​​Mathematics. A set in Python is​


S
​a collection, but is not an indexed or ordered collection as string, list or tuple. An​
​object cannot appear more than once in a set, whereas in List and Tuple, same​
​object can appear more than once.​

​ set can store only ​immutable​​​objects such as number​​(int, float, complex or​
A
​bool), string or tuple. If you try to put a list or a dictionary in the set collection,​
​Python raises a ​TypeError​​.​

​Ordered​ ​Mutable​ ​Allows​


​Type​ ​Example​
​?​ ​?​ ​Duplicates?​
​set​ ❌
​ ​ ​✔​ ❌​ ​ ​{1,2,3}​
​frozense​
​t​

​ ​ ❌ ​ ​ ❌​ ​ ​frozenset([1,2,3])​
​Used for unique elements and fast membership checks.​

🟦 4. Mapping Type​

​ ython dictionary is like associative arrays or hashes found in Perl and consist​
P
​of ​key:value​​​pairs. The pairs are separated by comma​​and put inside curly​
​brackets {}. To establish mapping between key and value, the semicolon':' symbol​
​is put between the two.​

​Type​ ​Description​ ​Example​


​ ey–value​
K
​dict​ ​{"a":1, "b":2}​
​pairs​
👉
​ Keys must be unique and immutable.​
👉
​ Values can be anything.​
🟨
​ ​​5. Boolean Type​

​ ython ​boolean​​​type is one of built-in data types which represents one of the two​
P
​values either ​True​​​or ​False​​. Python ​bool()​​​function​​allows you to evaluate the​
​value of any expression and returns either True or False based on the​

​expression.​

​ alue​
V ​Meaning​
​True /​ ​Subclass of int (True=1,​
​False​ ​False=0)​
​Used in conditions, loops, comparisons.​

🟫 6. None Type​

​ ython's none type is represented by the "​​


P nonetype​ ​." It is an object of its own data​
​type. The ​​ ​​represents the null type of values or absence of a value​
nonetype​

​.​

​Type​ ​Meaning​ ​Example​


​Represents no value / empty​
​None​ ​x = None​
​state​
​Often used for default return values.​

🌟
​ ​​Python Collections – Master Comparison Table​

​ ata​
D ​Mutable​ ​Allows​
​Ordered?​ ​Notes​
​Type​ ​?​ ​Duplicates?​
​list​ ✔
​ Yes​ ​✔ Yes​ ​✔ Yes​ ​ est for dynamic items​
B
​tuple​ ​✔ Yes​ ❌​ No​ ​✔ Yes​ ​Faster than list; safe data​
​str​ ​✔ Yes​ ❌​ No​ ​✔ Yes​ ​Immutable sequence of chars​

​dict​
​✔ Yes (Python​
​✔ Yes​
​✔ Values❌ ​ ​Keys must be unique &​
​3.7+)​ ​Keys​ ​immutable​
​set​ ❌ ​ No​ ❌
​✔ Yes​ ​ No​ ​Stores only unique elements​

​frozenset​ ​ No​ ❌ ❌
​ No​ ​ No​ ​Immutable version of set​
​bytes​ ​✔ Yes​ ❌ ​ No​ ​✔ Yes​ ​Immutable sequence of bytes​
​bytearray​​✔ Yes​ ​✔ Yes​ ​✔ Yes​ ​Mutable byte sequence​

​Python Operators​

​Python operators​​​are special symbols used to perform​​specific operations on one or​


​more operands. The ​variables​​, values, or expressions​​can be used as operands.​

​•​ ​ perators​​: Special symbols like -, + , * , /, etc.​


O
​•​ ​Operands​​: Value on which the operator is applied.​
​•​ ​Unary operators​​: Python operators that require one​​operand to​
​perform a specific operation are known as unary operators.​
​•​ ​Binary operators​​: Python operators that require two​​operands to​
​perform a specific operation are known as binary operators.​
​•​ ​Operands​​: Variables, values, or expressions that are​​used with the​
​operator to perform a specific operation.​

​Major 7 types of Operators used in Python are as follows:​

​1.​ ​ rithmetic Operators​


A
​2.​ ​Comparison Operators​
​3.​ ​Assignment Operators​
​4.​ ​Logical Operators​
​5.​ ​Bitwise Operators​
​6.​ ​Membership Operators​
​7.​ ​Identity Operators​

🔹
​ ​​1. Arithmetic Operators​

​Python Arithmetic operators​​​are used to perform basic​​mathematical operations​


​such as addition, subtraction, multiplication, etc.​

​ perator​
O ​Meaning​ ​ xample​ ​Result​
E
​+​ ​Addition​ ​10 + 5​ ​15​
​-​ ​Subtraction​ ​10 - 5​ ​5​
*​ ​ ​ ultiplication​
M ​ 0 * 5​
1 ​ 0​
5
​/​ ​Division (float)​ ​10 / 4​ ​2.5​
​//​ ​Floor division​ ​10 // 4​ ​2​
​Modulus​
​%​ ​10 % 3​ ​1​
​(remainder)​
​**​ ​Exponentiation​ ​2 ** 3​ ​8​
🔹 2. Relational / Comparison Operators​

​ ython Comparison operators​​​compare the values on​​either side of them and decide​
P
​the relation among them. They are also called Relational operators.​

​Exampl​
​Operator​ ​Meaning​ ​Output​
​e​
​ =​
= ​ qual to​
E ​5 == 5​ ​True​
​!=​ ​Not equal to​ ​5 != 3​ ​True​
​>​ ​Greater than​ ​5 > 3​ ​True​
​<​ ​Less than​ ​3 < 5​ ​True​
​Greater or​
​>=​ ​ >= 5​
5 ​True​
​equal​
​<=​ ​Less or equal​ ​3 <= 5​ ​True​

🔹 3. Logical Operators​

​ ython logical operators​​​are used to combile two or​​more conditions and check the​
P
​final result. There are following logical operators supported by Python language.​
​Assume variable a holds 10 and variable b holds 20 then​

​ perator​
O ​Meaning​ ​ xample​
E ​ esult​
R
​and​ ​True if both are true​ ​True and False​ ​False​
​True if at least one is​
​or​ ​True or False​ ​True​
​true​
​not​ ​Negates result​ ​not True​ ​False​
🔹
​ 4. Assignment Operators​

​ ython Assignment operators​​are used to assign values​​to variables. Following is a​


P
​table which shows all Python assignment operators.​

​ perator​
O ​Meaning​ ​ xample​ ​Equivalent to​
E
​=​ ​Assign​ ​x = 5​ ​—​
​+=​ ​Add & assign​ ​x += 3​ ​x = x + 3​
​ ubtract &​
S
​-=​ ​x -= 2​ ​x = x - 2​
​assign​
​ ultiply &​
M
​*=​ ​x *= 2​ ​x = x * 2​
​assign​
/​=​ ​Divide & assign​ x​ /= 2​ ​ = x / 2​
x
​//=​ ​Floor divide​ ​x //= 2​ ​x = x // 2​
​%=​ ​Modulus​ ​x %= 3​ ​x = x % 3​
​**=​ ​Power​ ​x **= 3​ ​x = x ** 3​

🔹
​ ​​5. Bitwise Operators​
​Python Bitwise operator​​​works on bits and performs​​bit by bit operation. These​
​operators are used to compare binary numbers.​

​Exampl​ ​Binary​
​Operator​ ​Meaning​
​e​ ​Result​
​​
& ​AND​ ​5 & 3​ ​1​
​`​ ​`​ ​OR​ ​`5​
​^​ ​XOR​ ​5 ^ 3​ ​6​
​~​ ​NOT​ ​~5​ ​-6​
​<<​ ​Left shift​ ​5 << 1​ ​10​
​Right​
​>>​ ​5 >> 1​ ​2​
​shift​

🔹
​ ​​6. Membership Operators​
​Python's ​membership operators​​​test for membership​​in a sequence, such as strings,​
​lists, or tuples.​

​ perator​
O ​Meaning​ ​Example​ ​ utput​
O
​in​ ​True if value present​ 3
​ in [1,2,3]​ ​True​
​True if value not​
​not in​ ​4 not in [1,2,3]​ ​True​
​present​

​7. Identity Operators​


​Python identity operators​​​compare the memory locations​​of two objects.​
​Operator​ ​Meaning​ ​Example​ ​ utput​
O
​Same memory​ ​Depend​
​is​ ​x is y​
​location​ ​s​
​is not​ ​Not same object​ ​x is not y​ ​Depend​
​s​

​Control Structures​
​ ontrol structures determine the​​flow​​of a Python​​program. They decide​​when​​and​​how​
C
​blocks of code should execute.​

​Python has​​3 types of control structures​​:​

​1.​ ​ onditional/ Decision-making (Selection)​​→ if, elif,​​else​


C
​2.​ ​Looping (Iteration)​​→ for, while​
​3.​ ​Loop Control statements​​→ break, continue, pass​
🟦
​ ​​1. conditional/Decision-Making Statements​
​Conditional statements in Python are used to execute certain blocks of code based on​
​specific conditions.​
​•​ ​if​​Statement​ ​Executes only if the condition is​​True.​
​•​ ​if–else​​Statement​​Runs one block if condition is​​True, another if False.​
​•​ ​if – elif – else​​Statement​​Used for multiple conditions.​
​•​ ​Nested if​​- if inside another if.​

​The match Statement​


​ ython supports ​Match-Case​​​statement, which can also​​be used as a part of​
P
​decision making. If a pattern matches the expression, the code under that case will​
​execute.​
​Ternary Conditional Statement​
​ ternary conditional statement is a compact way to write an if-else condition in a single​
A
​line. It’s sometimes called a "conditional expression."​

​Loops or Iteration Statements​


​Loops in Python are used to repeat actions efficiently​
​•​ f​ or​​Loop - Iterates over sequences: list, tuple, string, set, dictionary or range. It​
​allow to execute a block of code repeatedly, once for each item in the sequence.​
​•​ ​while​​Loop -​​The ​while loop​​​repeatedly executes a​​target statement as long​
​as a given boolean expression is true.​
​•​ ​Nested Loops – Loops within loops​
​Loop Control Statements​
​ oop control statements change execution from their normal sequence. When execution​
L
​leaves a scope, all automatic objects that were created in that scope are destroyed.​
​Python supports the following control statements.​
​•​ ​break – Stops the loop immediately​
​•​ ​continue – Skip current iteration of loop and move o next iteration​
​•​ ​pass – Do nothing (placeholder)​
​Python - Functions​
​A​​function​​is a block of reusable code that performs​​a specific task.​
​Advantages​
​•​ ​Functions help in the reusability of code​
​•​ I​t also reduces the code length.​
​•​ ​It improves the readability of code.​
​Defining a Function​

​calling a function​

​Types of functions​
​•​ ​Built-in Functions​​: Python standard functions that​​can be used anytime.​
​•​ ​User-defined​ ​Functions:​​Functions​ ​created​ ​by​ ​the​ ​users​ ​on​ ​the​ ​basis​ ​of​
​their requirements.​

​Function Arguments​

Function​ ​
​ ​​are​ ​the​ ​values​ ​or​ ​variables​ ​passed​ ​into​ ​a​ ​function​​when​​it​​is​
arguments​
​called. The behavior of a function often depends on the arguments passed to it.​
​Types of Function arguments​
​•​
​Positional or Required Arguments​
​•​
​Keyword Arguments​
​•​
​Default Arguments​
​•​
​Positional-only Arguments​
​•​
​Keyword-only arguments​
​•​
​Arbitrary or Variable-length Arguments​

​Positional or Required Arguments​

​ equired​​arguments​​are​​the​​arguments​​passed​​to​​a​​function​​in​​correct​​positional​​order.​
R
​Here,​ ​the​ ​number​ ​of​ ​arguments​ ​in​ ​the​ ​function​ ​call​ ​should​ ​match​ ​exactly​ ​with​ ​the​
​function definition, otherwise the code gives a syntax error.​
​Keyword Arguments​

Keyword​ ​
​ ​​are​ ​related​ ​to​ ​the​ ​function​ ​calls.​ ​When​ ​you​ ​use​ ​keyword​
arguments​
​ rguments​ ​in​ ​a​ ​function​ ​call,​ ​the​ ​caller​ ​identifies​ ​the​​arguments​​by​​the​​parameter​
a
​name.​

​Default Arguments​

​A ​​
default​ ​ ​​is​ ​an​​argument​​that​​assumes​​a​​default​​value​​if​​a​​value​​is​​not​
argument​
​provided in the function call for that argument.​
​Positional-only arguments​

​ hose​ ​arguments​ ​that​ ​can​ ​only​​be​​specified​​by​​their​​position​​in​​the​​function​​call​​is​


T
​called​ ​as ​​
Positional-only​ ​ arguments​ ​.​ ​They​ ​are​ ​defined​ ​by​ ​placing​ ​a​ ​"/"​ ​in​ ​the​
​function's​ ​parameter​ ​list​ ​after​ ​all​ ​positional-only​ ​parameters.​ ​This​ ​feature​ ​was​
​introduced with the release of Python 3.8.​

​Keyword-only arguments​
​ ose​ ​arguments​ ​that​ ​must​ ​be​ ​specified​ ​by​ ​their​ ​name​​while​​calling​​the​​function​​is​
h
​known​ ​as ​​ Keyword-only​ ​ arguments​ ​.​ ​They​​are​​defined​​by​​placing​​an​​asterisk​​("*")​
​in​ ​the​ ​function's​ ​parameter​ ​list​ ​before​ ​any​ ​keyword-only​ ​parameters.​ ​This​ ​type​ ​of​
​argument​​can​​only​​be​​passed​​to​​a​​function​​as​​a​​keyword​​argument,​​not​​a​​positional​
​argument.​

​Arbitrary or Variable-length Arguments​

​args → multiple positional arguments​


​kwargs → multiple keyword arguments​

​Lambda Functions (Anonymous / One-line)​

​Recursion (Function calling itself)​

​Pass by Reference vs Value​


​ ython does not use pass-by-value or pass-by-reference.​
P
​It uses​​pass-by-object-reference​​:​
​•​ ​ utable objects → changes reflect outside​
M
​•​ ​Immutable objects → changes do NOT reflect outside​
​PYTHON BUILT-IN FUNCTIONS​

​1. Type Conversion Functions​


​ unction​
F ​ urpose​
P
​int()​ ​convert to integer​
​float()​ ​convert to float​
​create complex​
​complex()​
​number​
​ ool()​
b ​convert to boolean​
​str()​ ​convert to string​
​list()​ ​convert to list​
t​uple()​ c​ onvert to tuple​
​set()​ ​convert to set​
​convert list/tuple to​
​dict()​
​dict​
​create immutable​
​bytes()​
​bytes​
​bytearray()​ ​mutable bytes​
​memoryview()​ ​access internal buffer​

​2.​​Mathematics Functions​

​Function​ ​ urpose​
P
​Absolute​
​abs(x)​ ​non-negative​
​value​
​ ound to n digits;​
R
​round(x, n)​ ​n<0 → left of​
​decimal​
​ ow(x, y)​
p ​same as x**y​
​sum(iterable)​ ​sum of items​
​min(iterable)​ ​smallest​
​max(iterable)​ ​largest​
​Returns​
​divmod(a, b)​ ​(quotient,​
​remainder)​
​ in(x)​
b ​convert to binary​
​oct(x)​ ​convert to octal​
​hex(x)​ ​convert to hex​

​3. Sequence Handling Functions​

​Function​ ​ urpose​
P
l​en()​ ​length of iterable​
​sorted()​ ​returns sorted list​
​reversed()​ ​reverse iterator​
​ numerate()​
e r​ eturns index + value​
​range()​ ​generate sequence​
​zip()​ ​combine sequences​
​apply function to each​
​map(func, iterable)​
​item​
​filter(func, iterable)​ ​filter items​
​ ll(iterable)​
a ​ rue if all items True​
T
​any(iterable)​ ​True if at least one True​
​4.​​Input / Output Functions​

​ unction​
F ​Purpose​
​print()​ ​ isplay output​
d
​input()​ ​take input​
​string​
​format()​
​formatting​
​open()​ ​file handling​

​5.​​Object & Attribute Functions​

​Function​ ​ urpose​
P
i​d(obj)​ ​memory address​
​type(obj)​ ​type of object​
​isinstance(obj, class)​ ​instance check​
​issubclass(A, B)​ ​subclass check​
​list​
​dir(obj)​
​attributes/methods​
v​ ars(obj)​ ​object __dict__​
​getattr(obj, name)​ ​get attribute​
​setattr(obj, name, value)​ ​set attribute​
​hasattr(obj, name)​ ​check attribute​
​delattr(obj, name)​ ​delete attribute​

​6.​​Functional Programming Helpers​

​ unction​
F ​ urpose​
P
​callable(obj)​ ​check if callable​
​ valuate string​
e
​eval(expr)​
​expression​
​ xec(code)​
e ​ xecute Python code​
e
​globals()​ ​global symbol table​
​locals()​ ​local namespace​

​7. Utility Functions​

​ unction​
F ​Purpose​
​help()​ ​ pen Python help​
o
​escape non-ASCII​
​ascii()​
​characters​
​repr()​ ​string representation​
​ ash()​
h ​ ash of object​
h
​object()​ ​base object​
​super()​ ​parent class helper​

​8. Class & Memory Functions​

​Function​ ​ urpose​
P
​create class​
​classmethod()​
​method​
​create static​
​staticmethod()​
​method​
​property()​ ​create property​

​Python Modules and Packages​


​1. Modules​
​ module is a file containing Python code: functions, classes, or variables. It helps​
A
​organize code into reusable files.​
​ reating a Module​
C
​[Link]​
​def greet(name):​
​return f"Hello, {name}!"​

​Using a Module​
​import mymodule​
​print([Link]("Bhavani"))​

​Other ways to import:​


f​rom mymodule import greet​
​print(greet("Bhavani"))​

i​mport mymodule as mm​


​print([Link]("Bhavani"))​

​Built-in Modules​
​•​ ​math, random, datetime, os, sys, re (regex), json, csv​
​Example:​
i​mport math​
​print([Link](16)) # 4.0​

​2. Packages​
​A package is a collection of modules organized in directories.​
​Structure:​
​mypackage/​
​__init__.py​
​[Link]​
​[Link]​

​Using Packages​
f​rom mypackage import module1​
​[Link]()​

​3. Python Standard Library Highlights​


​•​ ​ s – interacting with the operating system​
o
​•​ ​sys – system-specific parameters and functions​
​•​ ​datetime – working with date & time​
​•​ ​math – advanced mathematical functions​
​•​ ​random – random number generation​
​•​ ​json – JSON parsing & writing​
​•​ ​re – regular expressions​
​File Handling in Python​
​ ile handling in Python involves interacting with files on your computer to read data​
F
​from them or write data to them.​​It​ ​provides several​​built-in functions and methods​
​for creating, opening, reading, writing, and closing files.​

​1. File Operations​


​ Open file​
#
​f = open("[Link]", "r") # r-read, w-write, a-append, rb/rb+ for binary​
​content = [Link]()​
​print(content)​
​[Link]()​

​2. Writing to a file​


​with open("[Link]", "w") as f: # automatically closes file​
​[Link]("Hello Python\n")​

​Exception Handling in Python​


​ hen a Python program meets an error, it stops the execution of the rest of the program.​
W
​An error in Python might be either an error in the syntax of an expression or a Python​
​exception. ​

​What is Exception Handling?​


​•​ ​ xception:​​An error that occurs during program execution.​
E
​•​ ​Exception handling​​allows a program to continue running​​even after an error​
​occurs.​
​•​ ​Without handling, the program​​crashes​​.​

​2. Keywords in Exception Handling​


​ eyword​
K ​Purpose​
​try​ ​Block of code to test for exceptions​
​except​ ​Block to handle the exception​
​else​ ​Executes if no exception occurs​
​ xecutes​​always​​, whether exception occurs​
E
​finally​
​or not​
​raise​ ​Used to manually raise an exception​
​4. Common Built-in Exceptions​
​ xception Name​
E ​ ause​
C
​ZeroDivisionError​ ​Division by zero​
​ValueError​ ​Invalid type conversion​
I​ndexError​ ​ ist index out of range​
L
​KeyError​ ​Dictionary key not found​
​Unsupported operation for data​
​TypeError​
​type​
​ ileNotFoundError​
F ​File does not exist​
​ImportError​ ​Module not found​

​5. Multiple Exceptions in One Block​


​try:​
​x = int(input("Enter a number: "))​
​y = int(input("Enter another number: "))​
​print(x / y)​
​except (ZeroDivisionError, ValueError) as e:​
​print("Error occurred:", e)​

​6. Raising an Exception​


​•​ ​You can​​manually raise an exception​​using raise.​
​ ge = int(input("Enter your age: "))​
a
​if age < 18:​
​raise ValueError("Age must be 18 or above")​

​7. Exception Handling with Files​


​try:​
​f = open("non_existing_file.txt", "r")​
​content = [Link]()​
​except FileNotFoundError:​
​print("File not found!")​
​finally:​
​print("Execution finished")​
​8. Custom Exception​
​class MyError(Exception):​
​pass​

​try:​
​x = int(input("Enter a positive number: "))​
​if x < 0:​
​raise MyError("Negative number not allowed")​
​except MyError as e:​
​print(e)​

​Python String Methods – Complete Table​

​ ethod​
M ​Description​ ​Example​
​ ase Conversion​
C
​ onverts string to​
C
​[Link]()​ ​"hello".upper() → 'HELLO'​
​uppercase​
​Converts string to​
​[Link]()​ ​"HELLO".lower() → 'hello'​
​lowercase​
"​ hello world".capitalize() → 'Hello​
​[Link]()​ ​Capitalizes first letter​
​world'​
​ apitalizes first letter​
C
​[Link]()​ "​ hello world".title() → 'Hello World'​
​of each word​
​Swaps uppercase ↔​
​[Link]()​ ​"HeLLo".swapcase() → 'hEllO'​
​lowercase​
​Whitespace Handling​
​ emoves​
R
​[Link]()​ ​leading/trailing​ ​" hello ".strip() → 'hello'​
​spaces​
​Removes leading​
​[Link]()​ ​" hello".lstrip() → 'hello'​
​spaces​
​Removes trailing​
​[Link]()​ ​"hello ".rstrip() → 'hello'​
​spaces​
​Searching & Finding​
​ eturns lowest index​
R
​[Link](sub)​ ​"hello".find("l") → 2​
​of substring or -1​
​Returns highest index​
​[Link](sub)​ ​"hello".rfind("l") → 3​
​of substring or -1​
​Like find(), raises​
​[Link](sub)​ ​ValueError if not​ ​"hello".index("e") → 1​
​found​
​ ight-most index,​
R
​[Link](sub)​ ​raises ValueError if​ ​"hello".rindex("l") → 3​
​not found​
​Counts occurrences​
​[Link](sub)​ ​"hello".count("l") → 2​
​of substring​
​Checks if string starts​
​[Link](sub)​ ​"hello".startswith("he") → True​
​with substring​
​Checks if string ends​
​[Link](sub)​ ​"hello".endswith("lo") → True​
​with substring​
​ odification /​
M
​Replacement​
​ eplaces all​
R
​[Link](old, new)​ ​"hello".replace("l", "L") → 'heLLo'​
​occurrences​
​Concatenates iterable​
​[Link](iterable)​ ​with string as​ ​",".join(["a","b"]) → 'a,b'​
​separator​
​Splits string into list​
​[Link](sep)​ ​"a,b,c".split(",") → ['a','b','c']​
​using separator​
​[Link](sep)​ ​Right split​ ​"a,b,c".rsplit(",", 1) → ['a,b','c']​
​"line1\nline2".splitlines() →​
​[Link]()​ ​Splits on line breaks​
​['line1','line2']​
​Splits into tuple:​ ​"hello world".partition(" ") →​
​[Link](sep)​
​before, sep, after​ ​('hello',' ','world')​
​"hello world".rpartition(" ") →​
​[Link](sep)​ ​Right partition​
​('hello',' ','world')​
​Checking / Testing​
​ rue if all characters​
T
​[Link]()​ ​"abc123".isalnum() → True​
​are alphanumeric​
​ rue if all characters​
T
​[Link]()​ ​"abc".isalpha() → True​
​are letters​
​ rue if all characters​
T
​[Link]()​ ​"123".isdigit() → True​
​are digits​
​ rue if all characters​
T
​[Link]()​ ​"²³".isnumeric() → True​
​are numeric​
​ rue if all characters​
T
​[Link]()​ "​ 123".isdecimal() → True​
​are decimal​
​True if all cased​
​[Link]()​ ​characters are​ ​"hello".islower() → True​
​lowercase​
​[Link]()​ ​True if all cased​ ​"HELLO".isupper() → True​
c​ haracters are​
​uppercase​
​True if string contains​
​[Link]()​ ​" ".isspace() → True​
​only whitespace​
​True if string is in title​
​[Link]()​ ​"Hello World".istitle() → True​
​case​
​True if string is a valid​
​[Link]()​ ​"var1".isidentifier() → True​
​Python identifier​
​Formatting​
​ enters string with fill​
C
​[Link](width, fillchar)​ ​"hi".center(6,"*") → '**hi**'​
​character​
s​ [Link](width, fillchar)​ ​Left-justify​ "​ hi".ljust(6,"*") → 'hi****'​
​[Link](width, fillchar)​ ​Right-justify​ ​"hi".rjust(6,"*") → '****hi'​
​[Link](width)​ ​Pad with zeros​ ​"42".zfill(5) → '00042'​
​"Hello {}".format("World") → 'Hello​
​[Link]()​ ​String formatting​
​World'​
s​ [Link]() /​ ​"abc".translate([Link]("a","x​
​Map characters​
​[Link]()​ ​")) → 'xbc'​
​Encoding / Decoding​
​ ncode string to​
E
​[Link](encoding)​ ​"hello".encode("utf-8") → b'hello'​
​bytes​
​Decode bytes to​
​[Link](encoding)​ ​b'hello'.decode("utf-8") → 'hello'​
​string​

​FLASK​
​ lask is a lightweight and powerful web framework for Python. It’s often called a​
F
​"micro-framework" because it provides the essentials for web development without​
​unnecessary complexity. Unlike Django, which comes with built-in features like​
​authentication and an admin panel, Flask keeps things minimal and lets us add only​
​what we [Link] was developed by Armin Ronacher. Flask Python is based on the​
​WSGI(​​Web Server Gateway Interface) toolkit and​​Jinja2​​template engine.​

​Advantages of Flask​
​•​ ​ lask is a lightweight backend framework with minimal dependencies.​
F
​•​ ​Flask is easy to learn because its simple and intuitive API makes it easy to learn​
​ nd use for beginners.​
a
​•​ ​Flask is a flexible Framework because it allows you to customize and extend the​
​framework to suit your needs easily.​
•​ ​ ​Flask can be used with any database like:- SQL and NoSQL and with any​
​Frontend Technology such as React or Angular.​
​•​ ​Flask is great for small to medium projects that do not require the complexity of a​
​large framework.​

​Getting Started With Flask​


​from flask import Flask​
​app = Flask(__name__) # Flask constructor​

​# A decorator used to tell the application​


​# which URL is associated function​
​@[Link]('/')​
​def hello():​
​return 'HELLO'​

​if __name__=='__main__':​
​[Link](debug=True)​

​•​ ​ lask(__name__): Creates the Flask app.​


F
​•​ ​@[Link]('/'): Defines the home route (/).​
•​ ​ ​def hello(): creates a function that is bound with '/' route and returns "HELLO"​
​when the root page is accessed.​
​•​ ​[Link](debug=True): runs the app in debug mode. It ensure that app is not need​
​to restart manually if any changes are made in code.​

​ ne alternate way of doing this is by using "add_url_rule()" function of an application​


O
​object, it can also be used to bind URL with the function similar to the above example.​
​def hello_world():​
​return ‘hello world’​
​app.add_url_rule(‘/’, ‘hello’, hello_world)​

You might also like