Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python While loop breakout issues

The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great.

From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input 'q' it should break out and stop the loop. But what happens is it keeps going through the loop and then it breaks out. so it goes through the last prompt and prints the exception.

(Python version is 3.8.5)

# Statement that tells the user what we need.
print("Enter two numbers and I will tell you the sum of the numbers.")
# Lets the user know they can press 'q' to exit the program.
print("Press 'q' at anytime to exit.")

keep_going = True

# Loop to make the program keep going until its told to stop.
while keep_going:
    # Prompt for user to input first number and store it in a variable.
    first_number = input("First number: ")
    # Create a break when entering the first number.
    if first_number == 'q':
        keep_going = False
    # 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
    # Exception for non integers being input "ValueError"
    try:
        # Convert input to integers and add them. 
        # storing the answer in a variable.
        answer = int(first_number) + int(second_number)
    except ValueError:
        # Tell the user what they did wrong.
        print("Please enter a number!")
    else:    
        # Print the sum of the numbers
        print(f"\nThe answer is: {answer}")

Using this code it breaks out right away like I expect it to.

while True:
    first_number = input("First number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    if second_number == 'q':
        break

I just would like to understand what the difference is and if thats how it should work. I feel like I'm missing something or misunderstanding something.

like image 458
LRusch Avatar asked Dec 19 '20 06:12

LRusch


People also ask

Does Break Break out of while loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

Does Break stop a while loop Python?

The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

How do you break out of a while in Python?

In Python, the keyword break causes the program to exit a loop early. break causes the program to jump out of for loops even if the for loop hasn't run the specified number of times. break causes the program to jump out of while loops even if the logical condition that defines the loop is still True .

How to break a while loop in Python?

But, in addition to the standard breaking of loop when this while condition evaluates to false, you can also break the while loop using builtin Python break statement. break statement breaks only the enclosing while loop. In this tutorial, we will learn how to break a while loop using break statement, with the help of example programs.

What happens when the break condition is true in a loop?

When the break condition is true, break statement executes and comes out of the loop. Also, please note that the placement of break statement inside while loop is upto you. You can have statements before and after the break statement. Example 1 – Break While Loop

What is the syntax of while loop with BREAK statement?

Following is the syntax of while loop with a break statement in it. Usually break statement is written inside while loop to execute based on a condition. Otherwise the loop would break in the first iteration itself. Above syntax shows a Python If statement acting as conditional branching for break statement.

How do you break out of a loop in a function?

Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops. An easier way to do the same is to use an else block containing a continue statement after the inner loop and then adding a break statement after the else block inside the outer loop.


3 Answers

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"! :)

like image 154
Samwise Avatar answered Oct 09 '22 14:10

Samwise


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
like image 38
Ice Bear Avatar answered Oct 09 '22 12:10

Ice Bear


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")
like image 2
scupit Avatar answered Oct 09 '22 13:10

scupit