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
Below is a fully original, human-style, plagiarism-free article on:
⭐ Using finally and else in Exception Handling in Python
✔ Detailed explanation
✔ 3 unique example programs for each concept
✔ Why this concept matters
✔ How to memorize it for interview & exam
✔ SEO-optimized title, description & keywords
🔵 SEO Title (Human-Friendly & Unique)
Python Exception Handling: Understanding finally and else for Reliable and Clean Code
🟢 SEO Description (150 characters)
Learn Python’s finally and else blocks with clear explanations, unique examples, memory tricks, and exam-ready guidance for writing safe, predictable code.
🟠 SEO Keywords (150 characters)
python finally else, exception handling python, python try except guide, python beginners errors, try except else finally, python interview prep
✨ Using finally and else in Exception Handling in Python — A Clear Beginner-Friendly Guide
When working with Python programs, exceptions can occur anywhere: user input, file handling, calculations, or data processing. To keep your program stable, Python provides additional tools alongside the basic try and except blocks: the finally and else blocks.
Both blocks add structure, safety, and predictability to exception handling. Understanding them will make your code more professional and easier to maintain.
---------------------------------------
🟩 1. Understanding the else Block
---------------------------------------
The else block runs only when no exception occurs inside the try block.
If an error happens, the else block is skipped entirely.
✔ What else is used for:
- Code that should run only when everything goes smoothly
- Keeping success logic separate from error handling
- Making programs cleaner and easier to read
Structure:
try: # risky codeexcept SomeError: # error handlingelse: # runs only if no exception happens⭐ Example 1: Successful User Input
try: number = int(input("Enter a number: "))except ValueError: print("That was not a valid number.")else: print("Good! You entered:", number)⭐ Example 2: File Reading Without Errors
try: file = open("notes.txt", "r")except FileNotFoundError: print("File not found.")else: print("File opened successfully!") print(file.read())⭐ Example 3: Dictionary Lookup Without Exception
data = {"name": "John", "age": 22}
try: value = data["name"]except KeyError: print("Key not found.")else: print("Value retrieved successfully:", value)--------------------------------------------
🟫 2. Understanding the finally Block
--------------------------------------------
The finally block runs no matter what happens:
- An exception occurs →
finallyruns - No exception occurs →
finallyruns - A
returnstatement is hit →finallystill runs - The program crashes inside
tryorexcept→finallystill runs
✔ What finally is used for:
- Closing files
- Releasing system resources
- Cleaning temporary data
- Disconnecting from databases
- Logging program completion
Structure:
try: # risky codeexcept: # error handlingfinally: # always runs⭐ Example 1: Closing a File Safely
try: f = open("demo.txt", "r") print(f.read())except FileNotFoundError: print("File missing.")finally: print("Cleaning up resources...")⭐ Example 2: Simulating Database Cleanup
try: print("Connecting to database...") raise Exception("Timeout occurred")except Exception as err: print("Error:", err)finally: print("Closing database connection...")⭐ Example 3: Preventing Crash During Division
try: x = int(input("Enter number: ")) print("Result:", 50 / x)except Exception as e: print("Error happened:", e)finally: print("Execution finished.")-----------------------------------------------------
🟦 3. Using else and finally Together
-----------------------------------------------------
You can combine both for clear, well-organized exception handling.
try→ risky codeexcept→ what to do if an error occurselse→ what to do if NO error occursfinally→ what to do EVERY time
⭐ Example 1: Login Attempt
try: password = input("Enter password: ") if password != "admin123": raise ValueError("Wrong password")except ValueError as e: print("Login failed:", e)else: print("Login successful!")finally: print("Attempt completed.")⭐ Example 2: Reading and Processing a File
try: f = open("marks.txt") marks = int(f.readline())except (FileNotFoundError, ValueError): print("Cannot process file.")else: print("Processed Marks:", marks)finally: print("File operation complete.")⭐ Example 3: Network Simulation
try: print("Connecting to server...") connected = False if not connected: raise ConnectionError("Failed to connect")except ConnectionError as ce: print("Connection error:", ce)else: print("Connected successfully!")finally: print("Shutting down network module.")-----------------------------------------------------
🟧 Why Learning else and finally Is Important
-----------------------------------------------------
✔ 1. Makes your code predictable
You always know which block will run and when.
✔ 2. Enhance program reliability
finally ensures cleanup even after errors.
✔ 3. Keeps code organized
Success logic (else) stays away from error logic (except).
✔ 4. Professional applications depend on it
Used in file handling, databases, APIs, networking, automation.
✔ 5. Common interview topic
Employers want to see if you can manage errors properly.
-----------------------------------------------------
🔷 How to Remember for Interview & Exam Preparation
-----------------------------------------------------
💡 Memory Trick 1: E-F Rule
- Else = Everything went well
- Finally = Forever runs
💡 Memory Trick 2: “Success → else, Cleanup → finally”
Ask yourself:
✓ Is this success code? → put it in else
✓ Is this cleanup code? → put it in finally
💡 Memory Trick 3: Waterfall Flow
try↓ problem?except↓ no problem?else↓ alwaysfinally💡 Memory Trick 4: Practice Mini-Errors Daily
Create tiny programs that:
- open missing files
- divide by zero
- use wrong keys
This builds muscle memory.
🎉 Want the next topic?
I can write:
- A complete PDF
- A cheat sheet
- Interview questions
- Coding practice exercises
Just tell me!