Error Handling in Python

Python me exceptions aur errors ko handle karna sikhiye

1. Basic try/except

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Number cannot be zero!")
except ValueError:
    print("Please enter a valid integer!")

2. Handling multiple exceptions in one block

try:
    x = int(input("Enter number: "))
    y = int(input("Enter another number: "))
    print(x / y)
except (ZeroDivisionError, ValueError) as e:
    print("Error occurred:", e)

3. Using else and finally

try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    content = file.read()
    print(content)
    file.close()
finally:
    print("Execution complete!")

4. Raising custom exceptions

age = int(input("Enter your age: "))
if age < 18:
    raise Exception("You must be 18 or older!")

Next Step

Ab hum seekhenge Global vs Local Variables, jisme variables ke scope aur accessibility ko samjhenge.