Interview question
How do you use assertions for debugging in Python, and when should you avoid them? Python में debugging के लिए assertions कैसे use करें, और कब avoid करना चाहिए?
Answer
assert statements check that a condition is true, raising an AssertionError if not. They're meant for catching programmer errors and internal invariants during development, NOT for validating user input or handling expected runtime errors.
def calculate_discount(price, discount_percent):
assert 0 <= discount_percent <= 100, 'Discount must be between 0 and 100'
return price * (1 - discount_percent / 100)
print(calculate_discount(100, 20)) # 80.0
# calculate_discount(100, 150) # AssertionError: Discount must be between 0 and 100
# DANGEROUS: using assert for input validation in production code
def withdraw(balance, amount):
assert amount <= balance, 'Insufficient funds' # BAD PRACTICE
return balance - amount
# Problem: assertions are STRIPPED OUT when Python runs with -O (optimized) flag
# python -O script.py -- all asserts are skipped entirely, no error raised!
# CORRECT: use assert for internal invariants/debugging, raise exceptions for real validation
def withdraw_safe(balance, amount):
if amount > balance:
raise ValueError('Insufficient funds') # always runs, regardless of -O flag
return balance - amount
# Good use of assert: verifying internal logic assumptions during development
def binary_search(arr, target):
assert arr == sorted(arr), 'binary_search requires a sorted array' # dev-time check
# ... search logic ...assert statement condition true है या नहीं check करता है, अगर नहीं तो AssertionError raise करता है। ये programmer errors और internal invariants development के दौरान catch करने के लिए हैं, user input validate करने के लिए नहीं।
def calculate_discount(price, discount_percent):
assert 0 <= discount_percent <= 100, 'Discount 0 से 100 के बीच होना चाहिए'
return price * (1 - discount_percent / 100)
print(calculate_discount(100, 20)) # 80.0
# खतरनाक: production code में input validation के लिए assert use करना
def withdraw(balance, amount):
assert amount <= balance, 'Insufficient funds' # गलत practice
return balance - amount
# Problem: python -O flag के साथ assertions STRIP हो जाते हैं!
# सही: internal checks के लिए assert, real validation के लिए exception
def withdraw_safe(balance, amount):
if amount > balance:
raise ValueError('Insufficient funds') # हमेशा चलता है
return balance - amount
# assert का अच्छा उपयोग - dev-time internal logic check
def binary_search(arr, target):
assert arr == sorted(arr), 'array sorted होनी चाहिए'
# ... search logic ...Was this answer clear?