for loops
Line 1 stores 0 in total. total will hold a running sum, so it must start at zero before the loop begins adding to it.
Line 2 starts a for loop. range(1, 5) counts from 1 up to 5 but leaves out 5, so it gives 1, 2, 3, 4. The loop variable n takes the first one: 1.
The indented line under the header is the loop body. It works out total + n, which is 0 + 1, and stores 1 in total. A variable that collects a result like this is called an accumulator.
After the last line of the body, Python jumps back to the header on line 2. n takes the next number from range, 2. The loop variable changes on every pass.
The same two moves repeat. total becomes 1 + 2 = 3, n becomes 3, total becomes 6, n becomes 4, total becomes 10. Each trip through the body is one pass, also called an iteration.
range has no numbers left, so the for loop ends and Python moves on to the first line after the body. print(total) shows 10, which is 1 + 2 + 3 + 4.
while loops
A while loop repeats as long as its condition is True, and checks it before every pass. total > 4 is 10 > 4, which is True, so the body runs and total becomes 7.
Back at the header, 7 > 4 is True, so total becomes 4. Now 4 > 4 is False, so the loop stops. The body has to change something the condition checks, or it never stops.
Forever and break
while True: has a condition that can never turn False. On its own it would repeat forever, an infinite loop, and the program would seem to freeze. In a terminal, Ctrl+C stops it.
break ends the loop it is in at once, whatever the condition says. Python skips the rest of that loop and carries on after it. Here that is the end of the program.
Try it in the Python prompt
;; step 1/10 · line 1: total = 0 >>> total = 0 >>> total 0
range(start, stop) counts up from start and stops just before stop, so range(1, 4) gives 1, 2, 3 and range(1, 5) gives 1, 2, 3, 4. range(5) on its own starts at 0: 0, 1, 2, 3, 4. Python knows which lines are the loop body from the indentation: the lines under the header that are indented further. The header line ends with a colon.