Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Lists
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Exception Handling
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- AES-256 Encryption
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
✨ Handling Exceptions (try, except) in Python
Programming is never perfect on the first try—errors happen. Python gives us a powerful way to manage these unexpected issues through exception handling using try, except, else, and finally. Instead of letting your program crash, you can catch errors, show useful messages, or run backup code.
This makes your program safer, more professional, and easier to debug.
🧠 What Is Exception Handling in Python?
Exception handling is a technique used to manage runtime errors—these errors occur while your program is executing. Without exception handling, a single mistake (like dividing by zero or reading a missing file) can crash your whole program.
Python solves this with:
try→ Code that may cause an errorexcept→ What to do if an error happenselse→ Runs only when no error occursfinally→ Runs no matter what (cleanup code)
---------------------------------
🟦 1. TRY and EXCEPT BASICS
---------------------------------
The simplest form:
try: # risky codeexcept: # backup codeThis prevents the program from stopping when something goes wrong.
⭐ Example 1: Handling Division Errors
try: num = int(input("Enter a number: ")) print(100 / num)except: print("You cannot divide by zero or enter invalid input!")⭐ Example 2: Handling Invalid Integer Input
try: age = int(input("Enter your age: ")) print("In 5 years, you will be:", age + 5)except: print("Please enter a valid number for age.")⭐ Example 3: Accessing a List Index That May Not Exist
try: data = [10, 20, 30] pos = int(input("Enter index: ")) print(data[pos])except: print("Index does not exist! Try a number between 0 and 2.")------------------------------------------
🟩 2. Multiple except Blocks
------------------------------------------
You can catch different errors separately.
⭐ Example 1: Different Error Types
try: x = int(input("Number: ")) print(10 / x)except ZeroDivisionError: print("You tried dividing by zero!")except ValueError: print("Only numbers are allowed!")⭐ Example 2: File + Value Errors
try: filename = input("Enter file name: ") lines = open(filename).readlines() number = int(lines[0])except FileNotFoundError: print("File does not exist.")except ValueError: print("First line must contain a number.")⭐ Example 3: Handling Key Errors in Dictionary
try: student = {"name": "Alex", "age": 20} print(student["grade"])except KeyError: print("Grade information is missing in the record.")------------------------------------------
🟧 3. Using else with try-except
------------------------------------------
else runs only if no exception occurs.
⭐ Example 1: Clean Division
try: x = 5 y = 2 result = x / yexcept ZeroDivisionError: print("Error!")else: print("Division successful:", result)⭐ Example 2: File Read Success
try: file = open("notes.txt")except FileNotFoundError: print("File missing.")else: print("File opened successfully.") print(file.read())⭐ Example 3: Valid User Input
try: age = int(input("Enter your age: "))except ValueError: print("Invalid input.")else: print("Thank you! Your age is recorded.")-------------------------------------------
🟫 4. Using finally for Cleanup
-------------------------------------------
finally always runs, even if an error happens. Useful for:
✔ closing files ✔ closing database connections ✔ freeing resources
⭐ Example 1: Closing a File
try: f = open("sample.txt") print(f.read())except FileNotFoundError: print("No file found.")finally: print("Closing file (if opened).")⭐ Example 2: Safe Division with Cleanup Message
try: print(10 / 0)except ZeroDivisionError: print("Oops! Division error.")finally: print("Process completed.")⭐ Example 3: Database Cleanup Simulation
try: print("Connecting to database...") raise Exception("Connection failed")except Exception as e: print("Error:", e)finally: print("Closing database connection...")-------------------------------------------
🔶 5. Why Is Exception Handling Important?
-------------------------------------------
Exception handling is essential because:
✔ Prevents your program from crashing
Errors become manageable instead of fatal.
✔ Makes your code professional and user-friendly
Programs show helpful messages instead of ugly crash logs.
✔ Helps in debugging
You can catch specific errors and fix them easily.
✔ Required in real-world systems
Every robust app (Banking, AI, Games, Websites) uses exception handling.
✔ Common interview topic
Companies expect you to explain and write try-except code.
-------------------------------------------
🔷 6. How to Remember for Exams & Interviews
-------------------------------------------
💡 Memory Trick 1: T-E-E-F
- Try → code that might break
- Except → handle the error
- Else → runs when everything goes well
- Finally → always runs
💡 Memory Trick 2: “Try your best, Accept your mistakes”
Try → run risky code Except → catch mistakes
💡 Memory Trick 3: Error Flow Diagram
Error? → except No error? → else Always run → finally
💡 Practice Tip
Write 5 small programs daily that intentionally cause errors (ZeroDivision, file errors, input errors).