Data Science · मराठी आवृत्ती · Python basics
P8.4 Python try except else finally सोप्या भाषेत
हे का शिकायचं?
Error आला नाही तरच काही करायचं किंवा काहीही झालं तरी शेवटी काही करायचं असतं.
हे काय आहे?
else: error आला नाही तर चालतो. finally: नेहमी चालतो — files बंद करणं, message देणं.
कसं करायचं?
Step 1. try
Step 2. except (एक किंवा अनेक)
Step 3. else
Step 4. finally
उदाहरणं: copy करा आणि चालवा
उदाहरण A: अनेक except blocks
हा code चालवा:
def get_price(rec):
try:
return float(rec["price"])
except KeyError:
return "no price field"
except ValueError:
return "price is not a number"
print(get_price({"price": "19.99"}))
print(get_price({"name": "Pen"}))
print(get_price({"price": "free"}))
तुम्हाला दिसणारा output:
19.99
no price field
price is not a number
याचा अर्थ: प्रत्येक error प्रकाराला वेगळा message मिळाला.
उदाहरण B: else आणि finally
हा code चालवा:
def process(qty):
try:
per_box = 100 / qty
except ZeroDivisionError:
print("Error: quantity is zero")
else:
print("Per box:", per_box)
finally:
print("Batch logged")
process(4)
process(0)
तुम्हाला दिसणारा output:
Per box: 25.0
Batch logged
Error: quantity is zero
Batch logged
याचा अर्थ: Error नसताना else चालला आणि finally दोन्ही वेळा चालला.