-4

Could you explain why the output of this program is equal to 6? I’m confused on how it’s 6

  k = 0
  total = 0 
  while (k < 4):
        total += k 
        k += 1 
  print(“ The total is”, total)
  • 2
    You sum the numbers 0 to 3 - `0 + 1 + 2 + 3` – Iain Shelvington Oct 05 '22 at 03:55
  • The quotes are invalid, so the code you posted is not syntactically valid. Perhaps [edit] it to fix it; but really, we expect you to spend some time debugging this yourself before asking for human assistance. Maybe add a `print` statement inside the loop to see how the two variables change while the loop runs. Perhaps see also https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues – tripleee Oct 05 '22 at 03:55
  • 1
    Can you explain your confusion? What were you expecting the answer to be? – John Gordon Oct 05 '22 at 03:56

1 Answers1

1

This program is short enough to walk through the entire thing:

First iteration: k = 0, total += 0, k += 1. Total = 0, k = 1
Second iteration: k = 1, total += 1, k += 1. Total = 1, k = 2
Third iteration: k = 2, total += 2, k += 1. Total = 3, k = 3
Fourth iteration: k = 3, total += 3, k += 1. Total = 6, k = 4

Fifth iteration does not happen because k < 4 or 4 < 4 evaluates to false.

JRose
  • 1,382
  • 2
  • 5
  • 18