Bug: If no valid i is found in the second loop, d will be undefined, leading to a UnboundLocalError. Fix: Set default d = None before the loop and handle the case if no such i exists