# Preconditiondefbinary_search(arr, target):
assert arr == sorted(arr), "Array must be sorted"
lo, hi = 0, len(arr) - 1while lo <= hi:
mid = (lo + hi) // 2if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid + 1else:
hi = mid - 1return -1print(binary_search([1, 3, 5, 7, 9], 5))
# Postconditiondeffactorial(n):
result = 1for i inrange(2, n + 1):
result *= i
assert result > 0, "Factorial must be positive"return result
print(factorial(10))
# Type checking assertionsdefconcat(a, b):
assertisinstance(a, str) andisinstance(b, str), \
f"Expected strings, got {type(a).__name__} and {type(b).__name__}"return a + b
print(concat("hello", " world"))
Output
Click "Run" to execute your code
assert is ideal for checking invariants during development. Use it for conditions that should never be false in correct code.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?