Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Series

The document provides a comprehensive guide on Google Colab, detailing its features, usage, and important points for exam preparation. Key topics include notebook execution, file management, Linux shell commands, and Python's applications in various fields such as AI and data science. It also highlights best practices and alternatives to Google Colab for coding and collaboration.

Uploaded by

zameersolangi318
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)
6 views

Python Series

The document provides a comprehensive guide on Google Colab, detailing its features, usage, and important points for exam preparation. Key topics include notebook execution, file management, Linux shell commands, and Python's applications in various fields such as AI and data science. It also highlights best practices and alternatives to Google Colab for coding and collaboration.

Uploaded by

zameersolangi318
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
You are on page 1/ 29

GIAIC EXAM

BATCH-01
quarter-3 Preparation

PYTHON
SERIES
Important
mcqs, notes ,
summary & keypoints

Made By:
Hafsa kamali
(Senior student)
Google Colab Important Points (Simple
and Short for Exam/Quiz)
1. Colab Notebook Execution
Google Colab notebooks run on a virtual machine (VM).
Inside the VM, containers are used to separate each user’s
environment.
2. Files Stored in Session
Files you save during a Colab session are temporary.

I
When the container shuts down, all files are deleted.

L
To save files permanently, you should:

A
Mount Google Drive inside Colab
Download files to your computer

M
Use cloud storage like Google Cloud (optional)

A
3. Notebook Saving
The Colab notebook (.ipynb file) is saved directly to your Google

K
Drive.
That's why the notebook is safe across sessions.

A
However, the environment (libraries, variables) is not saved — you

S
need to set it up again every time.

F
4. Mounting Google Drive

A
Mounting Google Drive does not stay after a session ends.
You have to re-mount it each time the session restarts.

H
Mounting code example:
python
CopyEdit
from google.colab import drive
drive.mount('/content/drive')
5. Same Name Files in Google Drive
You can have multiple files with the same name in Google Drive.
Each file has a unique ID (used in its URL) which keeps them
separate internally.
That’s why no conflict happens even if names are the same.
Google Colab Important Points (Simple
and Short for Exam/Quiz)
📋 Super Short Recap:
TopicKey Point
VM or Container?
VM uses containers inside it

I
Temporary Files?

L
Files are deleted after session ends

A
Notebook Save?

M
Notebook is saved safely in Google Drive

A
Google Drive Mounting?

K
Needs to be done again every new session
Same Name Files?

A
Unique ID keeps same-name files separate

F S
H A
What is Google Colab?
It’s a free online Jupyter notebook service by Google.
Lets you write and run Python code in your browser.
No installation needed — only a Google account is required.
Free access to GPUs and TPUs for faster computing.
How to Start?
Go to colab.research.google.com.
Click File > New Notebook to create a new notebook.
You can also open it from Google Drive (New > More > Google
Colaboratory).

I
Important Features
Code Cells: Write and run Python code.

L
Text Cells: Add explanations using Markdown (for headings, bold text, lists).

A
Install Libraries: Use !pip install library_name.
Use GPU/TPU:

M
→ Go to Runtime > Change Runtime Type > GPU/TPU.

A
Basic Shortcuts

K
Shift + Enter: Run the cell.
Ctrl + M + B: Add a new code cell.
Ctrl + M + A: Add a new text cell.

A
Upload/Download Files

S
Upload: Click on the folder icon → Upload.

F
Download a file:

A
python

H
from google.colab import files
files.download('filename')
Mount Google Drive
To access Google Drive files:
python:
from google.colab import drive
drive.mount('/content/drive')
Sharing and Collaboration
Share your notebook like a Google Doc — Share button → set permissions.
Multiple people can edit at the same time.
Best Practices
Use comments to explain code.
Save of ten (auto - save to Drive happens too).
Use Clear Outputs (Edit > Clear Al l Outputs) to make the notebook
clean.
Use GitHub for version control if working on projects.
✨ Google Colab Alternatives (for quiz)
ToolGood ForNotes
1. Kaggle Notebooks
Free GPUs, ML competitions
9-hour limit per session.

I
2. Paperspace Gradient

L
Powerful GPUs, paid plans
Better hardware, costly.

A
3. Azure ML Studio

M
ML model building + deploying
Needs Azure subscription.

A
4. AW S SageMaker Studio

K
F ull ML workflow s
Mo re complex , costly.

A
5. Deep note

S
Team collaboration
Limited GPU, very collaborative.

F
6. Ju py te r Locally

A
Custom setups

H
Needs manual setup.
7. Hugging Face Spaces
Q uick model demos
Best for small apps, less training.
🚀 Super Quick Revision
G oogle Colab = Free Py thon coding + Free GPUs.
Write Py thon Code and Markdown text .
Install libraries using !pip.
Use GPU by c hanging Runtime Settings.
Share notebooks easily like Google Docs.
Alternatives = Kaggle, Paperspace, AW S SageMaker, etc.
G oogle Colab is a powerful platform widely used for generative AI,
data science, sof tware development , and genera l computing tasks. It
also of fers a platform for generating code using LLMs (Large
Language Models).
This guide provides an overview of the Linux shell c omman ds
available in Googl e Colab, along with tips for accessing th e runtime
terminal , transferring files between Google Drive and Colab, and
more.
Whether you're a seasoned user or just getting started, this guide
wi ll help you unlock the full potential of Google Colab.
Go ogle Colab operates on a Linux-based operating system,

I
specifically a variant of Ubuntu. As of recent updates, it typically
runs on Ubuntu 20.04 LT S (Focal Fossa), altho ugh the exact vers ion

L
may vary as Google periodically updates its backend infrastructure.

A
You can verif y the OS version in your Colab environment by executing
the following command in a code cell:

M
!cat /etc/os-release

A
Example output:

K
NAME="Ubuntu"

A
VERSION=" 20.04.6 LT S (Focal Fossa)"
ID=ubuntu

S
ID_LIKE=debian

F
PRETTY_NAME="Ubuntu 20.04.6 LT S"

A
VERS ION_ID=" 20.04"
The environment comes pre-installed with development tools and

H
libraries, including Py thon, Jupy ter, Git , TensorFlow, PyTorc h, and
others.
Using Shell Commands in Code Cellsi
In Google Colab, you can access Linux shell commands directly from
code cells.
Important: To execute a shell command, prefix it with ! in a code cell .
Example:

!ls
Common Command Categories
1. File Management
List files and directories: ls, ls -l , ls -a
Change directories: cd [directory]
Copy files: cp source destination
Move or rename files: mv source destination
R e m o v e f i l e s /d i r e c t o r i e s : r m f i l e n a m e , r m - r d i r e c t o r y
C r e a t e d i r e c t o r i e s : m k d i r [ d i r e c t o r y_ n a m e ]
2. System Information
Disk space usage: df -h
Memory usage: free -h
C h e c k O S ve r s i o n : l s b_ re l e a s e -a
CPU information: lscpu
O S d e t a i l s : u n a m e -a , l s b_ re l e a s e -a
Check GPU: nvidia-smi
3. Networking
Check network configuration: ifconfig, ip a

I
Download files: wget [url], curl -O [url]

L
Ping a server: ping [hostname]
4. Package Management
Update packages: apt-get update

A
I n s t a l l p a c k a ge s : a p t- ge t i n s t a l l [ p a c k a ge_ n a m e ]
Re m ove p a c k a ge s : a p t- ge t re m ove [ p a c k a ge_ n a m e ]
5 . Te x t P r o c e s s i n g

M
View file contents: cat filename, less filename, more filename
Search text in files: grep 'pattern' filename

A
Edit files: nano filename, vi filename
6. Permissions and Ownership

K
Change permissions: chmod [permissions] filename
Change ownership: chown [user]:[group] filename
7. P r o c e s s M a n a g e m e n t

A
List running processes: ps aux, top, htop
Kill a process: kill [PID]

S
8. Python and Scripting
R u n P y t h o n s c r i p t s : p y t h o n s c r i p t . p y, p y t h o n 3 s c r i p t . p y

F
Run shell scripts: bash script.sh, sh script.sh
9. V e r s i o n C o n t r o l

A
Git operations: git clone [repo], git pull , git push
1 0. M i s c e l l a n e o u s

H
Clear the terminal: clear
Print working directory: pwd
U s i n g R u n t i m e Te r m i n a l i n G o o g l e C o l a b
The free version of Google Colab does not provide a built-in terminal interface.
H o w e v e r, y o u c a n s i m u l a t e a r u n t i m e t e r m i n a l b y f o l l o w i n g t h e s e s t e p s :
A c c e s s i n g a Te r m i n a l
1. Install the terminal extension:
! p i p i n s t a l l c o l a b -x te r m
1. Load the extension:
% l o a d _e x t c o l a bx t e r m
1. Launch the terminal:
%xterm
Yo u c a n n o w u s e t h e r u n t i m e t e r m i n a l t o p e r f o r m a d v a n c e d o p e r a t i o n s , s u c h a s i n s t a l l i n g a d d i t i o n a l
software and tools.
D i f f e r e n t O p t i o n s t o A c c e s s a Te r m i n a l
There are multiple ways to simulate or access a full terminal in Colab:
. Basic Shell Commands
Simply prefix any shell command with ! inside code cells.
2. Using %%bash Magic
To e x e c u t e m u l t i p l e s h e l l c o m m a n d s i n a s i n g l e c e l l :
%%bash
echo "Hello from Bash!"ls -la
3. SSH Connection via colab_ssh
!pip install colab_ssh --upgrade
Setup SSH:
from colab_ssh import launch_ssh
l a u n c h _ s s h ( " y o u r _ p a s s w o r d ", " y o u r _ p u b l i c _ k e y " )
Connect using:
ssh root@<instance_address> -p 22
4. Tunneling with ngrok

I
!pip install pyngrok

L
Create a tunnel:
from pyngrok import ngrok

A
ssh_tunnel = ngrok .connect(22, " tcp")
ssh_tunnel .public_url

M
Connect using the provided ngrok address.
5. Persistent Sessions with tmux

A
!apt-get install tmux
Start a session:

K
!tmux
6. Using localtunnel

A
!npm install -g localtunnel
Expose port:

S
!lt --port 8080

F
7. L a u n c h i n g J u p y t e r L a b ( A d v a n c e d )
!pip install jupyterlab

A
Launch:
! n o h u p j u py te r - l a b - - i p = 0.0.0.0 - - p o r t = 8 8 8 8 - - n o - b ro w s e r &

H
Expose via ngrok.
Copying Files Between Google Drive and Colab
Yo u c a n e a s i l y t r a n s f e r f i l e s b e t w e e n y o u r G o o g l e D r i v e a n d C o l a b
using terminal commands.
1. Mount Google Drive
from google.colab import drive
d r i ve. m o u n t ( ' /c o n te n t /d r i ve ' )
2. Copy Files
From Colab to Drive:
! c p - r /c o n te n t /s o u rc e_d i re c to r y /c o n te n t /d r i ve / M y D r i ve / t a rge t _d i re c to r y

From Drive to Colab:


! c p - r /c o n te n t /d r i ve / M y D r i ve /s o u rc e_d i re c to r y /c o n te n t / t a rge t _d i re c to r y
Introduction To Python
Python is a high-level, interpreted, and versatile programming language known for its
simplicity and readability. Created by Guido van Rossum, it emphasizes code clarity and
supports multiple programming paradigms: procedural, object-oriented, and functional
programming.
Python’s extensive standard library and community support make it ideal for:
Web development
Data analysis
AI
Automation
and more.

I
Its cross-platform compatibility and beginner-friendly syntax have made it one of the most
popular languages worldwide.

L
Python in Agentic AI: Powering Autonomous Intelligence 🚀
Python plays a crucial role in Agentic AI, enabling autonomous agents to perceive, reason,

A
and act. Frameworks like:
LangChain

M
CrewAI
Microsoft AutoGen

A
Auto-GPT

K
OpenAI APIs
allow Python to facilitate LLM-driven workflows, decision-making, and self-improving AI.
Python's rich ecosystem integrates NLP, reinforcement learning, and automation for building

A
intelligent, agentic systems.

S
Practical Applications of Python
Some top applications of Python include:

F
Data Science and Analytics: data analysis, machine learning, and visualization
Agentic AI: building autonomous agents, chatbots, virtual assistants

A
Machine Learning: developing predictive models, recommender systems

H
Natural Language Processing (NLP): text analysis, sentiment analysis, language translation
Computer Vision: image recognition, object detection, facial recognition
Robotics: building and controlling robots, drones, autonomous vehicles
Web Development: web apps and frameworks
Artificial Intelligence: AI, ML, and deep learning
Automation and Scripting: automating tasks and workflows
Scientific Computing: simulations and scientific data analysis
Cybersecurity: security and penetration testing
IoT: Internet of Things applications
Python's Role in Code Execution: A Comprehensive Exploration
From Code Writing to Runtime and Output
Dive into the code execution continuum, exploring how programming languages transform:
Source Code → Bytecode → Runtime → Output
Learn how compilation, interpretation, and execution bring Python programs to life.
Introduction To Python
Python is a high-level, interpreted, and versatile programming language known for its
simplicity and readability. Created by Guido van Rossum, it emphasizes code clarity and
supports multiple programming paradigms: procedural, object-oriented, and functional
programming.
Python’s extensive standard library and community support make it ideal for:
Web development
Data analysis
AI
Automation
and more.

I
Its cross-platform compatibility and beginner-friendly syntax have made it one of the most
popular languages worldwide.

L
Python in Agentic AI: Powering Autonomous Intelligence 🚀
Python plays a crucial role in Agentic AI, enabling autonomous agents to perceive, reason,

A
and act. Frameworks like:
LangChain

M
CrewAI
Microsoft AutoGen

A
Auto-GPT

K
OpenAI APIs
allow Python to facilitate LLM-driven workflows, decision-making, and self-improving AI.
Python's rich ecosystem integrates NLP, reinforcement learning, and automation for building

A
intelligent, agentic systems.

S
Practical Applications of Python
Some top applications of Python include:

F
Data Science and Analytics: data analysis, machine learning, and visualization
Agentic AI: building autonomous agents, chatbots, virtual assistants

A
Machine Learning: developing predictive models, recommender systems

H
Natural Language Processing (NLP): text analysis, sentiment analysis, language translation
Computer Vision: image recognition, object detection, facial recognition
Robotics: building and controlling robots, drones, autonomous vehicles
Web Development: web apps and frameworks
Artificial Intelligence: AI, ML, and deep learning
Automation and Scripting: automating tasks and workflows
Scientific Computing: simulations and scientific data analysis
Cybersecurity: security and penetration testing
IoT: Internet of Things applications
Python's Role in Code Execution: A Comprehensive Exploration
From Code Writing to Runtime and Output
Dive into the code execution continuum, exploring how programming languages transform:
Source Code → Bytecode → Runtime → Output
Learn how compilation, interpretation, and execution bring Python programs to life.
Introduction To Python
Introduction to Python Bytecode
When you write Python code, it undergoes a compilation process:
1. Lexical Analysis: Breaking code into tokens.
2. Syntax Analysis: Ensuring syntactic correctness.
3. Semantic Analysis: Checking logical sense.
4. Bytecode Generation: Outputting intermediate bytecode.
What is Bytecode?
Platform-independent
Executed by the Python interpreter (CPython VM)
Stored in .pyc files
Example: Python Code and Its Bytecode
class Person:
def __init __(self, name: str, age: int):
self.name = name
self.age = age

def greet(self ):
print(f "Hello, my name is {self.name} and I am {self.age} years old.")

I
# Create an object
person: Person = Person("Arif Rozani", 20)

L
person.greet()
Output:
Hello, my name is Arif Rozani and I am 20 years old.

A
Disassembling Bytecode
import dis
dis.dis(Person)
(Output of __init __ and greet methods shown here...)

M
Introduction to the dis Module
The dis module allows inspection of low-level bytecode:

A
Helps understand Python internals
Useful for optimization or learning purposes
Why is Python Bytecode Important?

K
Platform Independence: Bytecode runs on any OS (with Python interpreter)
Dynamic Typing: Types are decided at runtime
Flexibility: Easier to add new features or modify code
How Python Uses Bytecode

A
1. Compilation: Python script → bytecode
2. Execution: Bytecode run by Python VM

S
3. Caching: Compiled bytecode saved to __pycache__ for faster loading
Can Bytecode Run Anywhere?

F
Bytecode is platform-independent BUT:
Needs the right Python version
OS-specific modules (os, sys) can behave differently

A
Still requires the Python interpreter (unlike Java bytecode with JVM)
How to Compile and Run Python Bytecode Manually
1. Compile:

H
python -m compileall TestP.py
1. Navigate to __pycache__ directory.
2. Run:
python TestP.cpython-312.pyc
Indentation in Python
Introduction to Indentation
Indentation is critical in Python for:
Code structure
Readability
Preventing syntax errors
Rules
4 spaces per indentation level
Indent after colons (for if, loops, functions, classes)
Consistent use of spaces (no tabs!)
Examples:
✅ Correct:
if True:
print("Hello")
❌ Incorrect:
if True:
print("Hello")
Python Data Types
1 . Numeric Types
a . Integer (int)
Whole numbers (positive or negative) without decimals.
num_int: int = 42
print(type(num_int), " num_int = ", num_int)
# Output: <class 'int '> num_int = 42
b. Floating-Point (float)
Numbers with decimal points.
num_float: float = 3.14# num_float: float = .14
print(type(num_float), " num_float = ", num_float)
# Output: <class ' float '> num_float = 3.14
c. Complex (complex)

I
Numbers with real and imaginary parts.
num_complex: complex = 2 + 3j

L
print(type(num_complex), " num_complex = ", num_complex)

A
# Output: <class 'complex'> num_complex = (2+3j)
Accessing Real and Imaginary Parts:

M
z = 3 + 4j
print("Real Part:", z.real)

A
print("Imaginary Part:", z.imag)

K
# Output:# Real Part: 3.0# Imaginary Part: 4.0
2. Boolean (bool)
Represents True or False.

A
is_python_fun: bool = True
print(type(is_python_fun), " is_python_fun = ", is_python_fun)

S
# Output: <class 'bool'> is_python_fun = True

F
3. Sequence Types
a. String (str)

A
A sequence of characters enclosed in quotes.
text _double: str = "Hello, Python!"

H
text _single: str = 'Hello, Python!'
text _multi: str = '''Hello, Python!'''
text _multi_1: str = """Hello, Python!"""
print(type(text _double), " text _double = ", text _double)
print(type(text _single), " text _single = ", text _single)
print(type(text _multi), " text _multi = ", text _multi)
print(type(text _multi_1), " text _multi_1 = ", text _multi_1)
Key Takeaways:
Use Double Quotes (") when the string contains single quotes.
Use Single Quotes (') when the string contains double quotes.
Use Triple Quotes (''' or """) for multi-line strings or docstrings.
Python Data Types
b. L i s t ( l i s t )
Ordered, mutable collection.
m y_l i s t : l i s t = [ 1 , 2 , 3, " P y t h o n ", 3. 1 4 , 3 + 2 j ]
p r i n t ( t y p e ( m y_l i s t ) , " m y_l i s t = ", m y_l i s t )
# O u t p u t : < c l a s s ' l i s t ' > m y_l i s t = [ 1 , 2 , 3, ' P y t h o n ', 3. 1 4 , ( 3 + 2 j ) ]
c . Tu p l e ( t u p l e )
Ordered, immutable collection.
m y_t u p l e : t u p l e = ( 1 , 2 , 3, "A I ", 2 .7 1 , Fa l s e, . 3, 3 + 2 j )
p r i n t ( t y p e ( m y_t u p l e ) , " m y_t u p l e = ", m y_t u p l e )
d. Range (range)
Represents a sequence of numbers.
n u m _ r a n g e : r a n g e = r a n g e ( 1 , 10, 2 )
p r i n t ( t y p e ( n u m _ r a n g e ) , " n u m _ r a n g e. s t e p = ", n u m _ r a n g e. s t e p )
# Loop:for i in num_range:
print(i)
# Output: 1 3 5 7 9

I
4 . S e t Ty p e s
(Unordered collection with unique elements)

L
a. Set (set)
m y_ s e t : s e t = { 1 , 2 , 3 3, 4 , 4 , 5 }

A
p r i n t ( t y p e ( m y_ s e t ) , " m y_ s e t = ", m y_ s e t )
# O u t p u t : < c l a s s ' s e t ' > m y_ s e t = { 1 , 2 , 3 3, 4 , 5 }
b. F r o z e n S e t ( f r o z e n s e t )

M
Immutable version of a set .
f r o z e n _ s e t = f r o z e n s e t ( [ 1 1 , 2 , 3, 4 , 4 , 5 ] )

A
p r i n t ( t y p e ( f r o z e n _ s e t ) , " f r o z e n _ s e t = ", f r o z e n _ s e t )
5. M a p p i n g Ty p e
Dictionary (dict)

K
S t o r e s k e y- v a l u e p a i r s .
m y_d i c t : d i c t = { " n a m e " : "A l i c e ", " a g e " : 2 5, " l a n g u a g e " : " P y t h o n " }
p r i n t ( t y p e ( m y_d i c t ) , " m y_d i c t = ", m y_d i c t )

A
6. B i n a r y Ty p e s
a . Bytes (bytes)
Immutable sequence of bytes.

S
b y t e_d a t a : b y t e s = b" H e l l o"
p r i n t ( t y p e ( b y t e_d a t a ) , " b y t e_d a t a = ", b y t e_d a t a )

F
File Example:
w i t h o p e n ( "A p o l l o 1 1 . j p g ", " r b" ) a s s o u r c e_ f i l e :

A
d a t a = s o u r c e_ f i l e. r e a d ( )

H
w i t h o p e n ( "c o p y. j p g ", " w b" ) a s t a rg e t _ f i l e :
t a rg e t _ f i l e.w r i t e ( d a t a )

print("Image copied successfully!")


b. B y t e a r r a y ( b y t e a r r a y )
Mutable sequence of bytes.
b y t e_ a r r a y : b y t e a r r a y = b y t e a r r a y ( [ 6 5, 6 6, 67, 6 9 ] )
p r i n t ( t y p e ( b y t e_ a r r a y ) , " b y t e_ a r r a y = ", b y t e_ a r r a y )
p r i n t ( b y t e_ a r r a y [ 0 ] )
p r i n t ( c h r ( b y t e_ a r r a y [ 0 ] ) )
Modifying Bytearray:
b a : b y t e a r r a y = b y t e a r r a y ( b" h e l l o" )
b a [ 0 ] = 7 2 # A S C I I v a l u e o f ' H ' p r i n t ( "A f t e r : ", b a )
# O u t p u t : b y t e a r r a y ( b' H e l l o ' )
c. Memoryview (memoryview)
Efficiently accesses binary data without copying.
m e m _v i e w : m e m o r y v i e w = m e m o r y v i e w ( b" O p e r a t i o n B a d a r " )
p r i n t ( t y p e ( m e m _v i e w ) , " m e m _v i e w = ", m e m _v i e w )
p r i n t ( b y t e s ( m e m _v i e w [ 0 : 5 ] ) )
p r i n t ( m e m _v i e w [ 6 : 1 1 ] )
Python Data Types
7. N o n e D a t a Ty p e
R e p r e s e n t s t h e a b s e n c e o f a v a l u e.
x: str = None
y: str = None
z: str = x

print(type(x))
p r i n t ( " x = = y : ", x = = y )
p r i n t ( " x i s y : ", x i s y )
p r i n t ( " i d ( x ) = = i d ( z ) : ", i d ( x ) = = i d ( z ) )
Special Notes:
== compares values.
is compares memory locations.
id() gives the unique identifier of the object .

I
Summary
✅ Python supports diverse data types for flexible programming.

L
✅ N u m e r i c , S e q u e n c e, S e t , M a p p i n g , B i n a r y, a n d N o n e t y p e s e a c h s e r v e s p e c i f i c p u r p o s e s .
✅ U n d e r s t a n d i n g t y p e b e h a v i o r ( m u t a b l e v s i m m u t a b l e, o r d e r e d v s u n o r d e r e d ) i s k e y t o w r i t i n g

A
e f f i c i e n t P y t h o n c o d e.

Operators, Operands, Keywords, and

M
Variables

A
✅ Operator vs Operand

K
O p e r a t o r : S y m b o l p e r f o r m i n g a n o p e r a t i o n . ( + , - , *, / )
O p e r a n d : Va l u e o r v a r i a b l e o n w h i c h t h e o p e r a t o r a c t s . ( 5 + 3, o p e r a n d s a r e 5 a n d 3 )
✅ Unary and Binary Operators

A
Unary Operator
1 Operand

S
-x , n o t a
Single change

F
Binary Operator
2 Operands

A
a + b
Combination

H
Ty p e s o f O p e r a t o r s i n P y t h o n
Arithmetic
Basic math operations
+ , - , *, / , // , % , * *
Comparison (Relational)
Compare two values
==, !=, >, <, >=, <=
Logical
Combine conditions
a n d , o r, n o t
Assignment
Assign and modify variables
= , + = , - = , * = , / = , // =
Identity
Compare memory locations
is, is not
Membership
Check presence in sequence
in, not in
✅ Python Keywords
R e s e r v e d w o r d s l i k e Tr u e, Fa l s e, i f, e l s e, f o r, w h i l e, e t c .
Cannot be used as variable names.
View them using:
python
CopyEdit
import keyword
print(keyword.kwlist)
✅ P y t h o n Va r i a b l e s
Containers for storing data.
No need to define the type — Python infers it!
Rules:

I
Must start with a letter or underscore (_), not a digit .
Can contain letters, digits, underscores.

L
Are case-sensitive (Age and age are different).
Cannot use Python keywords as variable names.

A
✅ Naming Conventions
s n a k e_c a s e

M
P u r p o s e : Va r i a b l e s a n d f u n c t i o n s
E x a m p l e : u s e r_ n a m e, t o t a l _ p r i c e

A
C a m e l C a s e ( o r Pa s c a l C a s e )
Purpose : Class names

K
Example: BankAccount
U P P E R _C A S E

A
Purpose : Constants
E x a m p l e : M A X _ S P E E D, P I

S
_ s i n g l e_l e a d i n g _ u n d e r s c o r e
P u r p o s e : I n t e r n a l /p r i v a t e u s e

F
Example: _password
_ _d o u b l e_l e a d i n g _ u n d e r s c o r e

A
Purpose : Name mangling (internal)

H
Example: __secret _key
_ _d u n d e r_ _
Purpose : Special methods
E x a m p l e : _ _ i n i t _ _ , _ _ s t r_ _
🔥 Follow PEP 8 for professional style!

✅ A s s i g n i n g M u l t i p l e Va l u e s
Yo u c a n a s s i g n m u l t i p l e v a r i a b l e s a t o n c e :
x , y, z = 1 , 2 , 3
Strings & Type_Casting

K e y Po i n t s :
1. String Basics
Strings are immutable sequences of characters.
Can be created using single (' '), double (" "), or triple quotes (''' '''
or """ """).
Raw strings (r ' ') treat backslashes as literal characters.
2. Escape Sequences
\ n → N e w l i n e, \ t → Ta b, \ b → B a c k s p a c e, \ " → D o u b l e q u o t e.
U n i c o d e c h a r a c t e r s : \ u 0 0 4 1 → 'A'.

I
3. String Operations

L
Concatenation (+), Indexing (str[0]), Slicing (str[7:]), Length
(len(str)).

A
Case conversion: upper(), lower().
4. String Methods

M
split() → Split into a list .
join() → Combine a list into a string.

A
replace() → Replace substrings.

K
f i n d ( ) / i n d e x ( ) → L o c a t e s u b s t r i n g s ( d i f f e r e n c e : f i n d ( ) r e t u r n s -1 i f n o t
found, index() raises an error).
count() → Count substring occurrences.

A
5. String Formatting

S
% O p e r a t o r : " H e l l o, % s " % " Wo r l d ".
s t r.f o r m a t ( ) : " H e l l o, { } ".f o r m a t ( " Wo r l d " ) .

F
f- S t r i n g s : f " H e l l o, { ' Wo r l d ' } ".

A
6 . S t r i n g Po o l & I n t e r n i n g
P y t h o n r e u s e s m e m o r y f o r i d e n t i c a l s t r i n g l i t e r a l s ( e. g . , a = " h e l l o" ;

H
b = " h e l l o" → s a m e i d ) .
D y n a m i c a l l y c r e a t e d s t r i n g s ( e. g . , " h e " + " l l o" ) m a y n o t b e i n t e r n e d .
Manual interning: sys.intern("string").
7. String Repetition
U s e * t o r e p e a t s t r i n g s : " H i " * 3 → " H i H i H i ".
8. String Comparisons
Lexicographical (dictionary) order based on Unicode values.
C a s e - s e n s i t i v e : "A" < " a" ( U n i c o d e : 6 5 < 97 ) .
9 . Ty p e C a s t i n g
I m p l i c i t : A u t o m a t i c ( e. g . , i n t + f l o a t → f l o a t ) .
Explicit: int(), float(), str(), bool(), etc.
N o t e : i n t ( " 3. 1 4" ) r a i s e s Va l u e E r r o r ( u s e f l o a t ( ) f i r s t ) .
Strings & Type_Casting
Quiz Questions:
1 . String Creation & Escape Sequences
W h a t i s t h e o u t p u t o f p r i n t ( r " H e l l o \ t Wo r l d " ) ?
A n s w e r : H e l l o \ t Wo r l d ( r a w s t r i n g i g n o r e s e s c a p e s e q u e n c e s ) .
2. String Methods
W h a t d o e s " h e l l o w o r l d ". s p l i t ( " l " ) r e t u r n?
A n s w e r : [ ' h e ', ' ', 'o w o r ', 'd ' ] .

I
3. S t r i n g F o r m a t t i n g
H o w w o u l d y o u f o r m a t n a m e = "A l i c e " i n t o " H e l l o, A l i c e ! " u s i n g f-

L
strings?

A
A n s w e r : f " H e l l o, { n a m e } ! ".
4 . S t r i n g Po o l

M
W h y d o e s a = " h e l l o" ; b = " h e l l o" ; p r i n t ( a i s b ) r e t u r n Tr u e?
Answer: Due to string interning, both variables point to the same

A
memory object.

K
5. Ty p e C a s t i n g
W h a t i s t h e r e s u l t o f b o o l ( " Fa l s e " ) ?
A n s w e r : Tr u e ( n o n - e m p t y s t r i n g s a r e Tr u e ) .

A
6. S t r i n g C o m p a r i s o n s

S
W h a t i s t h e o u t p u t o f p r i n t ( " a p p l e " < " B a n a n a" ) ?

F
A n s w e r : Fa l s e ( U n i c o d e : ' a' ( 97 ) > ' B ' ( 6 6 ) ) .
7. S t r i n g R e p e t i t i o n

A
W h a t d o e s " N a " * 2 + " B a t m a n ! " p r o d u c e?

H
A n s w e r : " N a N a B a t m a n ! ".
8. String Slicing
What is the output of "Python"[1:4]?
A n s w e r : " y t h ".
9. E s c a p e S e q u e n c e s
How do you print a literal backslash in a string?
A n s w e r : U s e \ \ ( e. g . , p r i n t ( " \ \ " ) ) .
10. I m p l i c i t v s . E x p l i c i t C a s t i n g
W h a t i s t h e r e s u l t o f i n t ( 3.9 ) ?
Answer: 3 (truncates, does not round).
Control Flow, Loops, and Iteration
K e y Po i n t s :
1 . Control Flow (Decision Making)
i f, e l i f, e l s e : U s e d f o r c o n d i t i o n a l e x e c u t i o n .
i f : C h e c k s a c o n d i t i o n ; e x e c u t e s i f Tr u e.
e l i f : A d d i t i o n a l c o n d i t i o n s a f t e r i f.
e l s e : E x e c u t e s i f a l l c o n d i t i o n s a r e Fa l s e.
N e s t e d i f : i f i n s i d e a n o t h e r i f.
m a t c h - c a s e ( P y t h o n 3. 10 + ) : S t r u c t u r a l p a t t e r n m a t c h i n g
( a l t e r n a t i v e t o i f- e l i f- e l s e ) .

I
2. Comparison Operators

L
==, !=, >, <, >=, <=
R e t u r n Tr u e o r Fa l s e b a s e d o n c o m p a r i s o n .

A
3. L o g i c a l O p e r a t o r s
a n d : B o t h c o n d i t i o n s m u s t b e Tr u e.

M
o r : A t l e a s t o n e c o n d i t i o n m u s t b e Tr u e.

A
n o t : I n v e r t s t h e c o n d i t i o n ( Tr u e → Fa l s e, Fa l s e → Tr u e ) .
4. Loops

K
for Loop: Iterates over sequences (lists, strings, ranges).
for i in range(5): → Executes 5 times.

A
else block: Runs if loop completes without break .

S
w h i l e L o o p : R e p e a t s w h i l e c o n d i t i o n i s Tr u e.

F
w h i l e c o u n t < = 5 : → R u n s u n t i l c o u n t e x c e e d s 5.
Loop Control:

A
b r e a k : E x i t s t h e l o o p i m m e d i a t e l y.

H
continue: Skips to the next iteration.
5. N e s t e d L o o p s
A l o o p i n s i d e a n o t h e r l o o p ( e. g . , m u l t i p l i c a t i o n t a b l e s ) .
Use cases: Matrix operations, multi-list iterations,
simulations.
6. P r a c t i c a l E x a m p l e s
C a l c u l a t o r : U s e s i f- e l i f- e l s e f o r o p e r a t i o n s ( + , - , *, / , % , // ,
**).
G r a d i n g S y s t e m : A s s i g n s g r a d e s ( A + , B, e t c . ) b a s e d o n m a r k s .
S u m o f N u m b e r s : U s e s f o r l o o p t o s u m 1 t o 10 0.
F i n d i n g Fa c t o r s : U s e s f o r l o o p a n d % o p e r a t o r.
Control Flow, Loops, and Iteration
Quiz Questions:
1 . Control Flow
What is the output of:
x = 10 i f x > 5 :
p r i n t ( "A" )
elif x > 8:
print("B")
else:
print("C")

I
A n s w e r : A ( O n l y t h e f i r s t Tr u e c o n d i t i o n i s e x e c u t e d ) .

L
2. Logical Operators
W h a t d o e s ( 5 > 3 ) a n d ( 10 < 8 ) e v a l u a t e t o?

A
A n s w e r : Fa l s e ( S e c o n d c o n d i t i o n i s Fa l s e ) .
3. for Loop

M
What is printed by:

A
for i in range(3):
print(i, end=" ")

K
else:
print("Done")

A
Answer: 0 1 2 Done.

S
4. while Loop

F
H o w m a n y t i m e s d o e s t h i s l o o p r u n?
count = 5while count > 0:

A
count -= 1

H
Answer: 5 times (count: 5 → 0).
5. break vs continue
What is the output of:
for i in range(5):
if i == 3:
continue
print(i, end=" ")
Answer: 0 1 2 4 (Skips 3).
Control Flow, Loops, and Iteration
6. N e s t e d L o o p s
What does this code print?
for i in range(2):
for j in range(2):
print(i + j, end=" ")
Answer: 0 1 1 2.
7. m a t c h - c a s e
What is the output of:
def check(n):

I
match n:

L
case 1:

A
r e t u r n " O n e "c a s e
case 2:

M
r e t u r n " Tw o"c a s e

A
case 3:

K
return "Other "
print(check(3))
A n s w e r : " O t h e r ".

A
8. Grading System

S
I f m a r k s = 7 5, w h a t g r a d e i s a s s i g n e d ?

F
Answer: "B" (70 ≤ marks < 80).

A
9. C a l c u l a t o r
What is the result of 5 ** 2?

H
Answer: 25 (Exponentiation).
10. S u m o f N u m b e r s
W h a t i s t h e s u m o f n u m b e r s f r o m 1 t o 10?
Answer: 55 (Use sum(range(1, 11))).
Lists, Tuples & Dictionary
K e y Po i n t s :
1. Lists
Mutable: Can be modified after creation (append(), remove(),
pop(), etc.).
Indexed: Access elements via list[index] (starts at 0).
Slicing: Extract sublists with list[start:end].
Methods:
sort(): Sorts in-place (use key= for custom sorting).
reverse(): Reverses the list .

I
c o u n t ( ) : R e t u r n s o c c u r r e n c e s o f a v a l u e.

L
i n d e x ( ) : R e t u r n s t h e f i r s t i n d e x o f a v a l u e.
List Comprehensions: Concise way to create lists ([x ** 2 for x

A
in range(5)]).
2 . Tu p l e s

M
Immutable: Cannot be modified after creation.

A
U s e C a s e s : F i x e d d a t a ( e. g . , c o o r d i n a t e s ) , d i c t i o n a r y k e y s

K
(because they are hashable).
Methods: Only count() and index().

A
3. D i c t i o n a r i e s
K e y-Va l u e Pa i r s : U n o r d e r e d ( b u t i n s e r t i o n - o r d e r e d i n P y t h o n

S
3.7 + ) .

F
M u t a b l e : A d d /u p d a t e /d e l e t e w i t h d i c t [ k e y ] = v a l u e o r

A
update().
Methods:

H
keys(): Returns all keys.
values(): Returns all values.
i t e m s ( ) : R e t u r n s k e y- v a l u e p a i r s .
g e t ( k e y, d e f a u l t ) : S a f e l y a c c e s s v a l u e s ( a v o i d s K e y E r r o r ) .
Dictionary Comprehensions: {k: v * 2 for k , v in
o r i g i n a l _d i c t . i t e m s ( ) } .
4. Common Pitfalls
L i s t s : Av o i d m o d i f y i n g w h i l e i t e r a t i n g ; u s e c o p i e s i f n e e d e d .
Tu p l e s : C a n n o t a d d /r e m o v e e l e m e n t s .
D i c t i o n a r i e s : K e y m u s t b e i m m u t a b l e ( e. g . , s t r i n g s , n u m b e r s ,
tuples).
Lists, Tuples & Dictionary
Quiz Questions:
1. Lists
What is the output of:
nums = [1, 2, 3]
nums.append([4, 5])
print(nums)
A n s w e r : [ 1 , 2 , 3, [ 4 , 5 ] ] ( a p p e n d ( ) a d d s t h e l i s t a s a s i n g l e e l e m e n t ) .
2. List Slicing
What does
n u m s = [ 10, 2 0, 3 0, 4 0, 5 0 ] ;

I
print(nums[1:4]) print?
A n s w e r : [ 2 0, 3 0, 4 0 ] ( s l i c e s f r o m i n d e x 1 t o 3 ) .

L
3. Tu p l e s

A
Why does this code fail?
t = (1, 2, 3)

M
t [ 0 ] = 10
A n s w e r : Tu p l e s a r e i m m u t a b l e ; c a n n o t m o d i f y e l e m e n t s .

A
4. Dictionary Access
What is the output of:

K
d = { " a" : 1 , " b" : 2 }
p r i n t ( d . g e t ( "c ", 9 9 ) )

A
Answer: 99 (default value when key doesn’t exist).
5. D i c t i o n a r y M e t h o d s

S
How do you get all keys from a dictionary d?

F
Answer: d.keys().
6. L i s t C o m p r e h e n s i o n s

A
Convert [1 , 2, 3] to [2, 4, 6] using a list comprehension.
Answer: [x *2 for x in [1, 2, 3]].

H
7. Tu p l e U n p a c k i n g
W h a t d o e s t h i s c o d e d o?
a , b, c = ( 10, 2 0, 3 0 )
A n s w e r : U n p a c k s t h e t u p l e i n t o a = 10, b = 2 0, c = 3 0.
8. Nested Dictionaries
H o w d o y o u a c c e s s "A l i c e " i n { "c l a s s " : { " s t u d e n t s " : { " n a m e " : "A l i c e " } } } ?
A n s w e r : d [ "c l a s s " ] [ " s t u d e n t s " ] [ " n a m e " ] .
9. S o r t i n g L i s t s
S o r t [ " a p p l e ", " k i w i ", " b a n a n a" ] b y l e n g t h .
Answer: sorted(words, key=len).
10. D i c t i o n a r y C o m p r e h e n s i o n s
Create a dictionary {1: 1 , 2: 4, 3: 9} using a comprehension.
Answer: {x: x **2 for x in range(1, 4)}.
Sets and Frozen sets
K e y Po i n t s :
1. Sets
Unordered: Elements have no fixed position.
M u t a b l e : C a n a d d /r e m o v e e l e m e n t s ( a d d ( ) , r e m o v e ( ) , d i s c a r d ( ) ) .
Unique Elements: No duplicates allowed.
Methods:
union() / |: Combine sets.
intersection() / &: Common elements.
d i f f e r e n c e ( ) / - : E l e m e n t s i n s e t A b u t n o t B.
s y m m e t r i c_d i f f e r e n c e ( ) / ^ : E l e m e n t s i n e i t h e r s e t b u t n o t b o t h .
Hashing: Uses hash tables for O(1) lookups (order is

I
unpredictable).

L
2. Frozensets

A
I m m u t a b l e Ve r s i o n o f S e t s : C a n n o t m o d i f y a f t e r c r e a t i o n .
Hashable: Can be used as dictionary keys or in other sets.

M
Methods: Similar to sets but no modification methods (add(),
remove()).

A
3. C o m m o n O p e r a t i o n s

K
M e m b e r s h i p Te s t i n g : x i n s e t ( f a s t d u e t o h a s h i n g ) .
Set Comprehensions: {x ** 2 for x in range(5)}.

A
C o p y i n g : n e w_ s e t = o l d _ s e t .c o p y ( ) .

S
4. Pitfalls

F
U n o r d e r e d : C a n n o t i n d e x ( s e t [ 0 ] r a i s e s Ty p e E r r o r ) .
M u t a b l e E l e m e n t s : S e t s c a n n o t c o n t a i n l i s t s /d i c t i o n a r i e s

A
(unhashable).

H
R e h a s h i n g : O r d e r m a y c h a n g e w h e n e l e m e n t s a r e a d d e d /r e m o v e d .

Quiz Questions:
1. Set Basics
What is the output of:
s = {1, 2, 2, 3}
print(s)
Answer: {1 , 2, 3} (duplicates are removed).
2. Set Operations
W h a t d o e s { 1 , 2 , 3 } & { 3, 4 , 5 } r e t u r n?
Answer: {3} (intersection).
Sets and Frozen sets
3. S e t M e t h o d s
How do you safely remove an element if it exists (without raising
an error)?
A n s w e r : s .d i s c a r d ( e l e m e n t ) .

4. Frozensets
Why does this fail?
fs = frozenset([1 , 2, 3])
fs.add(4)
Answer: Frozensets are immutable; no add() method.

I
5. H a s h i n g
Why can' t a set contain a list?

L
A n s w e r : L i s t s a r e m u t a b l e /u n h a s h a b l e ; s e t s r e q u i r e h a s h a b l e

A
elements.

M
6. S e t C o m p r e h e n s i o n
C r e a t e a s e t o f s q u a r e s f o r n u m b e r s 1- 5 u s i n g c o m p r e h e n s i o n .

A
Answer: {x **2 for x in range(1, 6)}

K
7. D i c t i o n a r y K e y s
Which can be a dictionary key: set([1 , 2]) or frozenset([1 , 2])?

A
Answer: frozenset (only immutable objects can be keys).

S
8. Symmetric Difference

F
W h a t i s { 1 , 2 , 3 } ^ { 3, 4 , 5 } ?
Answer: {1 , 2, 4, 5} (elements in either set but not both).

H A
9. S e t C o n v e r s i o n
How do you remove duplicates from a list [1 , 2, 2, 3]?
Answer: list(set([1, 2, 2, 3])).

10. Pe r f o r m a n c e
Why are sets faster than lists for membership testing?
Answer: Sets use hash tables (O(1) lookup) vs. lists (O(n)).
Order of Arguments in Python
Functions
K e y Po i n t s : O r d e r o f A rg u m e n t s i n P y t h o n F u n c t i o n s
Po s i t i o n a l A rg u m e n t s
Must be passed in the correct order as defined in the function.
Example: func(a, b) → func(1, 2) assigns a=1, b=2.

K e y w o r d A rg u m e n t s
Pa s s e d w i t h e x p l i c i t p a r a m e t e r n a m e s , o r d e r d o e s n ’ t m a t t e r.
Example: func(b=2, a=1) works even if defined as func(a , b).

I
D e f a u l t A rg u m e n t s

L
Pa r a m e t e r s w i t h d e f a u l t v a l u e s m u s t c o m e a f t e r n o n - d e f a u l t

A
parameters.
E x a m p l e : d e f f u n c ( a , b = 0 ) i s v a l i d ; d e f f u n c ( a = 0, b ) i s i n v a l i d .

M
Va r i a b l e - L e n g t h Po s i t i o n a l ( * a rg s )

A
C o l l e c t s e x t r a p o s i t i o n a l a rg u m e n t s i n t o a t u p l e.

K
M u s t c o m e a f t e r p o s i t i o n a l a n d k e y w o r d a rg u m e n t s .
E x a m p l e : d e f f u n c ( a , * a rg s ) .

A
Va r i a b l e - L e n g t h K e y w o r d ( * * k w a rg s )

S
C o l l e c t s e x t r a k e y w o r d a rg u m e n t s i n t o a d i c t i o n a r y.
Must come last in the parameter list .

F
E x a m p l e : d e f f u n c ( a , * * k w a rg s ) .

A
Po s i t i o n a l - O n l y A rg u m e n t s ( P y t h o n 3. 8 + )

H
D e f i n e d b e f o r e / i n t h e f u n c t i o n s i g n a t u r e.
Example: def func(a, /, b) → a must be positional; b can be
positional /keyword.

K e y w o r d - O n l y A rg u m e n t s
D e f i n e d a f t e r * i n t h e f u n c t i o n s i g n a t u r e.
E x a m p l e : d e f f u n c ( a , *, b ) → b m u s t b e p a s s e d a s a k e y w o r d
a rg u m e n t .

Order Summary (Left to Right):


d e f f u n c ( p o s_o n l y, / , p o s_o r_ k w, * a rg s , k w_o n l y, * * k w a rg s )
Order of Arguments in Python
Functions
Quiz Questions
1 . W h i c h a rg u m e n t t y p e m u s t a l w a y s c o m e f i r s t i n a f u n c t i o n
d e f i n i t i o n?
A ) D e f a u l t a rg u m e n t s
B ) Po s i t i o n a l a rg u m e n t s
C ) K e y w o r d a rg u m e n t s
A n s w e r : B ( Po s i t i o n a l a rg u m e n t s )
2. What happens if you define a function as def func(a=1, b)?

I
A ) Wo r k s f i n e
B) Raises a SyntaxError

L
A n s w e r : B ( D e f a u l t a rg u m e n t s m u s t f o l l o w n o n - d e f a u l t o n e s )

A
3. How would you force a to be positional-only in def func(a , b)?
A ) d e f f u n c ( *, a , b )

M
B) def func(a, /, b)
Answer: B (Uses / for positional-only)

K A
4 . W h e r e d o e s * * k w a rg s a p p e a r i n t h e p a r a m e t e r l i s t ?
A ) B e f o r e * a rg s
B) At the end

A
Answer: B (Must be last)

S
5 . W h a t d o e s d e f f u n c ( a , *, b ) e n f o r c e?
A) a must be keyword-only

F
B) b must be keyword-only

A
A n s w e r : B ( A rg u m e n t s a f t e r * a r e k e y w o r d - o n l y )
6. Which of these is a valid function header?

H
A ) d e f f u n c ( a , / , b = 1 , * a rg s , c , * * k w a rg s )
B ) d e f f u n c ( a = 1 , b, / , * a rg s , * * k w a rg s )
Answer: A (Follows correct order)

7 . W h a t w i l l f u n c ( 1 , 2 , x = 3, y = 4 ) u n p a c k i f d e f i n e d a s d e f f u n c ( a , b,
* * k w a rg s ) ?
A ) a = 1 , b = 2 , k w a rg s = { ' x ' : 3, ' y ' : 4 }
B) Raises an error
A n s w e r : A ( E x t r a k e y w o r d s g o i n t o k w a rg s )

8 . Tr u e / Fa l s e : * a rg s c a n a p p e a r a f t e r * * k w a r g s .
A n s w e r : Fa l s e ( * a rg s m u s t c o m e b e f o r e * * k w a rg s ) .
Exception Handling in Python,
K e y Po i n t s : E x c e p t i o n H a n d l i n g i n P y t h o n

1. try Block
Wraps code that might raise an exception.
Example:
try:
x = 10 / 0 e x c e p t : p r i n t ( " E r r o r ! " )
2. except Block
C a t c h e s s p e c i f i c e x c e p t i o n s ( e. g . , Z e r o D i v i s i o n E r r o r, Ty p e E r r o r ) .
Use Exception to catch all errors.

I
Example:
except ZeroDivisionError:

L
print("Cannot divide by zero!")

A
3. else Block
E x e c u t e s o n l y i f n o e x c e p t i o n s o c c u r i n t r y.

M
Example:
else:print("Success!")

A
4. finally Block

K
Always executes (used for cleanup like closing files).
Example:
f i n a l l y : p r i n t ( " D o n e." )

A
5. Raising Exceptions

S
U s e r a i s e t o t h r o w e x c e p t i o n s m a n u a l l y.
Example:

F
i f x < 0 : r a i s e Va l u e E r r o r ( " N e g a t i v e v a l u e ! " )

A
6. Custom Exceptions
Define by inheriting from Exception.

H
Example:
class CustomError(Exception):pass
7 . N o R e t u r n Ty p e H i n t
I n d i c a t e s a f u n c t i o n n e v e r r e t u r n s ( e. g . , a l w a y s r a i s e s a n
exception).
Example:
from typing import NoReturn
def fail() -> NoReturn:raise SystemExit
8. Alternatives to NoReturn
Use -> None for functions that return nothing but don’t raise
exceptions.
Omit type hints if not using static analysis.
Exception Handling in Python,
Quiz Questions
1 . W h a t d o e s t h e f i n a l l y b l o c k d o?
A ) R u n s o n l y i f n o e x c e p t i o n s o c c u r.
B) Runs regardless of exceptions.
Answer: B

1. Which block executes when no exceptions occur?


A) except
B) else
Answer: B

I
2 . H o w d o y o u r a i s e a c u s t o m e x c e p t i o n?

L
A) raise CustomError()

A
B) throw CustomError()
Answer: A

M
3 . W h a t i s t h e P y t h o n e q u i v a l e n t o f J a v a ’s t h r o w s ?

A
A) raise
B) Python doesn’t have one (uses docstrings/type hints).

K
Answer: B
4 . W h e n s h o u l d y o u u s e N o R e t u r n?

A
A ) Fo r f u n c t i o n s t h a t r e t u r n N o n e.

S
B ) Fo r f u n c t i o n s t h a t n e v e r r e t u r n ( e. g . , a l w a y s r a i s e
exceptions).

F
Answer: B

A
5 . W h i c h e x c e p t i o n i s r a i s e d b y 10 / 0?

H
A ) Ty p e E r r o r
B) ZeroDivisionError
Answer: B
6. What happens if an exception is unhandled?
A ) P r o g r a m c o n t i n u e s s i l e n t l y.
B) Program crashes with a traceback .
Answer: B

7 . Tr u e / Fa l s e : e l s e r u n s e v e n i f e x c e p t c a t c h e s a n e r r o r.
A n s w e r : Fa l s e ( e l s e r u n s o n l y i f n o e x c e p t i o n s o c c u r ) .
The quizzes, summaries, and topics shared here are
compiled purely through my personal efforts, based on
w h a t e v e r I u n d e r s t o o d t o t h e b e s t o f m y a b i l i t y. I h a v e
tried to cover as much as I could, but these notes are
not a substitute for your own hard work .
P l e a s e u s e t h e m a s a g u i d e, n o t a s y o u r s o l e
p r e p a r a t i o n . P u t i n y o u r f u l l e f f o r t , t r u s t y o u r s e l f, a n d
stay consistent . ✨💎

Wishing you all the very best of

L I
A
luck for your exams!

Believe in your hard work —

A M 🤞🏻✨
K
success will surely follow!

S A
A F
H

You might also like