Learn Python Coding
38.8K subscribers
611 photos
27 videos
24 files
370 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
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

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
In Python programming exams, follow these structured steps to solve problems methodically, staying focused and avoiding panic: Start by reading the problem twice to clarify inputs, outputs, and constraints—write them down simply. Break it into small sub-problems (e.g., "handle edge cases first"), plan pseudocode or a flowchart on paper, then implement step-by-step with test cases for each part, debugging one issue at a time while taking deep breaths to reset if stuck.

# Example: Solve "Find max in list" problem step-by-step
# Step 1: Understand - Input: list of nums; Output: max value; Constraints: empty list?

def find_max(numbers):
if not numbers: # Step 2: Handle edge case (empty list)
return None # Or raise ValueError

max_val = numbers # Step 3: Initialize with first element
for num in numbers[1:]: # Step 4: Loop through rest (sub-problem: compare)
if num > max_val:
max_val = num
return max_val # Step 5: Return result

# Step 6: Test cases
print(find_max([3, 1, 4, 1, 5])) # Output: 5
print(find_max([])) # Output: None
print(find_max()) # Output: 10

# If stuck: Comment code to trace, or simplify (e.g., use max() built-in first to verify)


This approach builds confidence—practice on platforms like LeetCode to make it habit! #python #problemsolving #codingexams #debugging #interviewtips

👉 @DataScience4
🔥2
If you work with Python, remember a simple rule: do not modify a list while iterating over it. 🐍🛑 This can lead to unexpected results because the iterator does not track structural changes.

Here is an example that looks logical but works incorrectly: 🤔

items = [1, 2, 2, 3, 4]
for item in items:
    if item == 2:
        items.remove(item)
print(items)
# Output: [1, 2, 3, 4]


It seems that all 2s should disappear, but one remains. Why?

After removing an element, the list shifts, but the loop moves on — as a result, some values are simply skipped. 🔄🚫

How to do it correctly — iterate over a copy:

for item in items[:]:
    if item == 2:
          items.remove(item)
print(items)
# Output: [1, 3, 4]


Even better — use list comprehension: 🚀

items = [x for x in items if x != 2]

Conclusion: 🏁 do not modify a collection during iteration. This can lead to skipped elements, duplication, or even errors during execution. 🛠️🚧

#Python #Coding #Programming #Debugging #TechTips #PythonTips
1