Topic: Python Exception Handling — Managing Errors Gracefully
---
Why Handle Exceptions?
• To prevent your program from crashing unexpectedly.
• To provide meaningful error messages or recovery actions.
---
Basic Try-Except Block
---
Catching Multiple Exceptions
---
Using Else and Finally
• else block runs if no exceptions occur.
• finally block always runs, used for cleanup.
---
Raising Exceptions
• You can raise exceptions manually using raise.
---
Custom Exceptions
• Create your own exception classes by inheriting from Exception.
---
Summary
• Use try-except to catch and handle errors.
• Use else and finally for additional control.
• Raise exceptions to signal errors.
• Define custom exceptions for specific needs.
---
#Python #ExceptionHandling #Errors #Debugging #ProgrammingTips
---
Why Handle Exceptions?
• To prevent your program from crashing unexpectedly.
• To provide meaningful error messages or recovery actions.
---
Basic Try-Except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
---
Catching Multiple Exceptions
try:
x = int(input("Enter a number: "))
result = 10 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
---
Using Else and Finally
• else block runs if no exceptions occur.
• finally block always runs, used for cleanup.
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
file.close()
---
Raising Exceptions
• You can raise exceptions manually using raise.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
check_age(-1)
---
Custom Exceptions
• Create your own exception classes by inheriting from Exception.
class MyError(Exception):
pass
def do_something():
raise MyError("Something went wrong!")
try:
do_something()
except MyError as e:
print(e)
---
Summary
• Use try-except to catch and handle errors.
• Use else and finally for additional control.
• Raise exceptions to signal errors.
• Define custom exceptions for specific needs.
---
#Python #ExceptionHandling #Errors #Debugging #ProgrammingTips
❤2
Topic: Python List vs Tuple — Differences and Use Cases
---
Key Differences
• Lists are mutable — you can change, add, or remove elements.
• Tuples are immutable — once created, they cannot be changed.
---
Creating Lists and Tuples
---
When to Use Each
• Use lists when you need a collection that can change over time.
• Use tuples when the collection should remain constant, providing safer and faster data handling.
---
Common Tuple Uses
• Returning multiple values from a function.
• Using as keys in dictionaries (since tuples are hashable, lists are not).
---
Converting Between Lists and Tuples
---
Performance Considerations
• Tuples are slightly faster than lists due to immutability.
---
Summary
• Lists: mutable, dynamic collections.
• Tuples: immutable, fixed collections.
• Choose based on whether data should change or stay constant.
---
#Python #Lists #Tuples #DataStructures #ProgrammingTips
https://t.me/DataScience4
---
Key Differences
• Lists are mutable — you can change, add, or remove elements.
• Tuples are immutable — once created, they cannot be changed.
---
Creating Lists and Tuples
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
---
When to Use Each
• Use lists when you need a collection that can change over time.
• Use tuples when the collection should remain constant, providing safer and faster data handling.
---
Common Tuple Uses
• Returning multiple values from a function.
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
• Using as keys in dictionaries (since tuples are hashable, lists are not).
---
Converting Between Lists and Tuples
list_to_tuple = tuple(my_list)
tuple_to_list = list(my_tuple)
---
Performance Considerations
• Tuples are slightly faster than lists due to immutability.
---
Summary
• Lists: mutable, dynamic collections.
• Tuples: immutable, fixed collections.
• Choose based on whether data should change or stay constant.
---
#Python #Lists #Tuples #DataStructures #ProgrammingTips
https://t.me/DataScience4
❤2
Topic: Python File Handling — Reading, Writing, and Managing Files (Beginner to Advanced)
---
What is File Handling?
• File handling allows Python programs to read from and write to external files — such as
• Python uses built-in functions like open(), read(), and write() to interact with files.
---
Opening a File
---
Using with Statement (Best Practice)
• Automatically handles file closing:
---
File Modes
• "r" — read (default)
• "w" — write (creates or overwrites)
• "a" — append (adds to the end)
• "x" — create (fails if file exists)
• "b" — binary mode
• "t" — text mode (default)
---
Writing to Files
• Note:
---
Appending to Files
---
Reading Line by Line
---
Working with File Paths
• Use os.path or pathlib for platform-independent paths.
---
Advanced Tip: Reading and Writing CSV Files
---
Summary
• Use open() with correct mode to read/write files.
• Prefer with statement to manage files safely.
• Use libraries like csv, json, or pickle for structured data.
• Always handle exceptions like FileNotFoundError for robust file operations.
---
Exercise
• Write a Python program that reads a list of names from
---
#Python #FileHandling #ReadWrite #DataProcessing #ProgrammingTips
https://t.me/DataScience4
---
What is File Handling?
• File handling allows Python programs to read from and write to external files — such as
.txt, .csv, .json, etc.• Python uses built-in functions like open(), read(), and write() to interact with files.
---
Opening a File
file = open("example.txt", "r") # "r" = read mode
content = file.read()
file.close()---
Using with Statement (Best Practice)
• Automatically handles file closing:
with open("example.txt", "r") as file:
content = file.read()---
File Modes
• "r" — read (default)
• "w" — write (creates or overwrites)
• "a" — append (adds to the end)
• "x" — create (fails if file exists)
• "b" — binary mode
• "t" — text mode (default)
---
Writing to Files
with open("output.txt", "w") as file:
file.write("Hello, world!")• Note:
"w" overwrites existing content.---
Appending to Files
with open("output.txt", "a") as file:
file.write("\nNew line added.")---
Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())---
Working with File Paths
• Use os.path or pathlib for platform-independent paths.
from pathlib import Path
file_path = Path("folder") / "file.txt"
with open(file_path, "r") as f:
print(f.read())
---
Advanced Tip: Reading and Writing CSV Files
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "age"])
writer.writerow(["Alice", 30])
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)---
Summary
• Use open() with correct mode to read/write files.
• Prefer with statement to manage files safely.
• Use libraries like csv, json, or pickle for structured data.
• Always handle exceptions like FileNotFoundError for robust file operations.
---
Exercise
• Write a Python program that reads a list of names from
names.txt, sorts them alphabetically, and saves the result in sorted_names.txt.---
#Python #FileHandling #ReadWrite #DataProcessing #ProgrammingTips
https://t.me/DataScience4
❤4
Python can make a dictionary immutable without copying data!
Usually, to protect configurations and the overall state, a copy of the dictionary is made, which creates unnecessary memory allocations.
MappingProxyType creates a read-only proxy over a dictionary — writing through it becomes impossible, but the data is not copied.
At the same time, the proxy remains alive: if the original dictionary changes, the changes will automatically be reflected in the read-only view.
This is especially useful for configurations, internal APIs, overall state, and data protection within libraries.
🔥 MappingProxyType allows you to provide a read-only view of the dictionary without copying and without the risk of mutation through the returned object.
#Python #Immutable #DataProtection #MappingProxyType #ProgrammingTips #NoCopy
✨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk
⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
🚀 Level up your AI & Data Science skills with HelloEncyclo — a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
✅ 13 courses live + 40+ coming soon
🎯 One access, lifetime updates
🔑 Use code: PRESALE-BOOK-WAVE-2GFG
👉 https://helloencyclo.com/?ref=HUSSEINSHEIKHO
Usually, to protect configurations and the overall state, a copy of the dictionary is made, which creates unnecessary memory allocations.
safe = dict(config)
MappingProxyType creates a read-only proxy over a dictionary — writing through it becomes impossible, but the data is not copied.
readonly["debug"] = True # TypeError
At the same time, the proxy remains alive: if the original dictionary changes, the changes will automatically be reflected in the read-only view.
config["debug"] = True
This is especially useful for configurations, internal APIs, overall state, and data protection within libraries.
def get_settings():
return MappingProxyType(settings)
🔥 MappingProxyType allows you to provide a read-only view of the dictionary without copying and without the risk of mutation through the returned object.
#Python #Immutable #DataProtection #MappingProxyType #ProgrammingTips #NoCopy
✨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk
⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
🚀 Level up your AI & Data Science skills with HelloEncyclo — a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
✅ 13 courses live + 40+ coming soon
🎯 One access, lifetime updates
🔑 Use code: PRESALE-BOOK-WAVE-2GFG
👉 https://helloencyclo.com/?ref=HUSSEINSHEIKHO
Telegram
AI PYTHON 🌟
You’ve been invited to add the folder “AI PYTHON 🌟”, which includes 14 chats.
❤1