Everyone shakes hands
At a party, everyone shakes hands with everyone else, once. How do you count the handshakes? Take the first person, and they shake hands with each of the others. Then take the second person, and so on.
In code, that's a loop inside a loop. The outer loop picks a person. The inner loop goes through the people they shake hands with. For every single pass of the outer loop, the inner loop runs all the way through from start to finish.
Start the inner loop later
If the inner loop also started from the first person, you would count a person shaking hands with themselves, and every handshake twice, once from each side. That's wrong.
The fix: the inner loop starts just after the outer person. Person 1 meets 2, 3, 4, and so on. Person 2 meets 3, 4, and so on, because they already met 1. Each pair then appears exactly once, with the smaller number first.
count = 0
for a in range(1, n + 1):
for b in range(a + 1, n + 1):
if a + b == total:
count = count + 1- a
- 1
- b
- 2
- count
- 0
The outer loop picks a = 1. The inner loop starts after it, at b = 2. 1 plus 2 is 3, not 6.