Python While loop breakout issues

The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless of the condition) or continue (which jumps to the next iteration, and will therefore terminate the loop if the condition is no longer true).

Using while True: with a break when you want to stop the loop is generally much more straightforward than trying to control the loop by setting and unsetting a flag.

FWIW, rather than copying and pasting the code to input the two numbers, and have two different ways to break out of the loop, I might put that all into a function and break the loop with an Exception, like this:

print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")


def input_number(prompt: str) -> int:
    """Ask the user to input a number, re-prompting on invalid input.
    Exception: raise EOFError if the user enters 'q'."""
    while True:
        try:
            number = input(f"{prompt} number: ")
            if number == 'q':
                raise EOFError
            return int(number)
        except ValueError:
            print("Please enter a number!")


while True:
    try:
        numbers = (input_number(n) for n in ("First", "Second"))
        print(f"The answer is: {sum(numbers)}")
    except EOFError:
        break

This makes it easier to extend the program to handle more than two inputs; try adding a "Third" after where it says "First" and "Second"! :)


Once you run the program and type "q", Yes indeed keep_going will be set to False but it DOES NOT MEAN it will break the loop already, it will just make the keep_going be equal to False thus on the NEXT ITERATION will stop the loop. Why is that? because it would be like this while keep_going: -> while False: so since it is not True thus not executing the program anymore.

Now based on your goal as you mentioned. You can do it this way where you can add the break.

if first_number == 'q':
    keep_going = False
    break
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
    keep_going = False
    break

I'd also like to suggest have it this way, it's just more specific in terms of what is to happen on the code, but of course it is up to you.

first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
    keep_going = False
    break
# Prompt for user to input second number and store it in a variable.
# Create a break when entering the second number.
else:
    second_number = input("Second number: ")
    if second_number =='q':
        keep_going = False
        break

While loops execute until their given condition is false. A loop will only check its condition when required (program execution is moved to the top of the loop). In almost every case, this occurs when the full body of the loop has run. See here:

keep_going = True

while keep_going:
  keep_going = False
  # keep_going is False, but this will still print once
  # because the loop has not checked its condition again.
  print("Will execute once")

"Will execute once" prints a single time even after keep_going is set to False. This happens because the while loop does not re-check its condition until its entire body has run.

However, break statements are different. A break statement will cause a loop to exit immediately no matter what.

keep_going = True

while keep_going:
  break # Exits the while loop immediately. The condition is not checked.
  print("Will never print")

Here, nothing is printed even though keep_going is True the whole time. break made the loop exit regardless of the condition.

A continue statement will move program execution back to the start of the loop, and cause your condition to be checked again.

In this example, continue sends program execution back to the start of the loop. Since keep_going was set to False, nothing will print because the while loop will exit after realizing its condition evaluates to false.

keep_going = True

while keep_going:
  keep_going = False
  continue
  print("Will never print")