Exercise 7: Find a Pair That Adds Up, Leaving Both Loops — Possible Solution ==================================================================== numbers = [8, 3, 11, 5, 2, 9] target = 14 # Way 1: a variable checked after the inner loop pair = None for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] + numbers[j] == target: pair = (numbers[i], numbers[j]) break # leaves the inner loop only if pair is not None: break # leaves the outer loop print("way 1:", pair) # Way 2: return leaves every loop in the function def find_pair(numbers, target): for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] + numbers[j] == target: return (numbers[i], numbers[j]) return None print("way 2:", find_pair(numbers, target)) Example run: way 1: (3, 11) way 2: (3, 11) WHY THIS WORKS AS AN ANSWER ------------------------------ Starting the inner loop at i + 1 means each pair is tried once and no number is paired with itself. In way 1 the first break ends the inner loop; the outer loop would then simply carry on with the next i, so a second check (if pair is not None: break) is needed to end that one too. In way 2, return leaves the whole function, loops and all, in one step, and the 'return None' at the end covers the case where no pair exists. The function version is usually the tidier of the two, and Python has no labelled break (break outer) to do it more directly.