The format didn't quite take; I've seen that problem with the code block before. Sadly, you're going to need to edit and fix that to show your format before anyone can give you an accurate answer. This issue is typically due to not quite following the scope within the loop. Break statements look back along the execution path and terminate the first loop they encounter. while True: for item in items: if item = "close": break else: print(item) will only break out of the for loop, but the while loop will run forever. You would have to put another break statement at the same indentation level (scope) as the for loop in order for the while loop to stop while True: for item in items: if item = "close": break else: print(item) break Answer from Guideon72 on reddit.com
🌐
Python.org
discuss.python.org › python help
Can't get while loop to stop - Python Help - Discussions on Python.org
May 6, 2024 - I am making a number guessing game, and I have a while loop over the whole thing. The problem is, I can’t get it to stop when I want it to. import random import sys import time ynChoice = 'x' global runGTN runGTN = True while runGTN == True: #the loop typing_speed = 300 #wpm def printSlow(*t): for l in t: sys.stdout.write(l) sys.stdout.flush() time.sleep(random.random()*10.0/typing_speed) print() def confirmChoice(ynChoice): ...
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - Python allows an optional else clause at the end of while loops. The syntax is shown below: ... The code under the else clause will run only if the while loop terminates naturally without encountering a break statement. In other words, it executes when the loop condition becomes false, and only then. Note that it doesn’t make much sense to have an else clause in a loop that doesn’t have a break statement.
Discussions

Python while loop not stopping? - Stack Overflow
I'm trying to make a dice 21 game (look up if you need to, it's too long to type out here) on Python. It's not finished yet, but for now I'm going through and fixing any mistakes I made. I'm having... More on stackoverflow.com
🌐 stackoverflow.com
April 27, 2019
Python - While loop won't stop - Stack Overflow
my code seems to work up to the line before WHILE loop. The idea is to have the computer try to guess the number inputted by Player 1('P1') by picking a middle number from the lowest and highest nu... More on stackoverflow.com
🌐 stackoverflow.com
python - While loop doesn't stop - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
April 30, 2015
python - Why doesn't the while loop stop when the condition becomes False? - Stack Overflow
I am a beginner in Python and was watching a 6 hr video by Mosh Hamedami. He has shown an example of designing an elementary Car Game using a while loop. The code is suggested is below: command = '' More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › my while loop won't stop, how do i end it?
r/learnpython on Reddit: My while loop won't stop, how do I end it?
February 16, 2024 -

No matter where I put the break or “return,” it just won’t work. I need it to end then go onto the next defined function (printInvoice) but it either continues on an endless loop or ends but won’t go onto the next function.

Here's the code:

Dictionary1 = {'Brad': 18.99, 'Chad': 16.99, 'Andy': 15.99, 'Suzy': 12}

Shipping = {'Ally Express': [10.00, 0.50], 'DHL Express': [11.75, .35], 'Bob Economy': [10.00,40], 'Queen Priority':[13.00, 0.40]} 
GST = 0.05

def checkInput(): 
    order = [] 
    while True: 
    for value in Dictionary1:
        try: decision = int(input("How many sets of " + value + " do you want?"))
            order.append(str(decision)) 
        except ValueError: 
            print("You did not enter an integer") 
            decision = int(input("How many sets of " + value + " do you want?"))
    break 

def printInvoice(order): 
print("We can deliver by Ally Express, Bob Economy or Queen Priority Shipping")
🌐
Stack Overflow
stackoverflow.com › questions › 33399560 › python-while-loop-not-stopping
Python while loop not stopping? - Stack Overflow
April 27, 2019 - It only needs one thing to be true for a whole string of x or y or z or... to be true logically, so as soon as the first thing checked is true, or stops looking. Since you are setting playeraddedrolls = False to break out of this loop, the check becomes False < 21, which is true and short-circuits. Rather than setting playeraddedrolls = False and implicitly breaking, you could explicitly add break there. However, this isn't recommended because break statements can quite easily get buried and thus can be difficult to debug. Perhaps better still would be to change the while condition to this:
Top answer
1 of 3
2

A while loop does not terminate when the condition becomes false. It terminates when it evaluates the condition and the condition is found to be false. That evaluation doesn't happen until the beginning of each loop iteration, not immediately after some event occurs that will allow the condition to become false.

A better way to write this loop is to simply use True as the condition, as it doesn't require you to initialize command to a known non-terminating value, then let a break statement somewhere the loop terminate the command when appropriate.

started = False
while True:
    command = input('Enter a Command: ').lower()
    if command == 'quit':
        break

    if command == 'start':
        if started:
            print("Car already Started! Let's go!")
        else:
            started = True
            print("Car Started.... Ready to Go!!!")
    elif command == 'stop':
        if not started:
            print('Car already stopped!')
        else:
            started = False
            print('Car stopped!')
    elif command == 'help':
        print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
    else:
        print('Sorry, I do not understand that!')

Of course, you don't need two separate if statements as I've shown here; you could combine them into one with if command == 'start' being the first elif clause of the combined if statement. But this provides an explicit boundary between "code that terminates the loop" and "code that allows the loop to continue".

2 of 3
1

The program actually stops when you type quit, but before stopping it prints "Sorry, I do not understand that!". You can fix this by putting command = input('Enter a Command: ').lower() before while and in the end of the while like this (so that while will check if command != quit immediately after inputing):

command = ''
started = False
command = input('Enter a Command: ').lower()
while command != 'quit':
    if command == 'start':
        if started:
            print("Car already Started! Let's go!")
        else:
            started = True
            print("Car Started.... Ready to Go!!!")
    elif command == 'stop':
        if not started:
            print('Car already stopped!')
        else:
            started = False
            print('Car stopped!')
    elif command == 'help':
        print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
    else:
        print('Sorry, I do not understand that!')
    command = input('Enter a Command: ').lower()
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › just curious why my while loop doesn't stop when the condition is met
Just curious why my while loop doesn't stop when the condition is met : r/learnpython
March 12, 2024 - Subreddit for posting questions and asking for general advice about all topics related to learning python. ... Sorry, this post was deleted by the person who originally posted it. Share ... If only one of the lists is empty, the condition will still be true since you're using or. If you want the loop to exit when either is empty, you need and.
Top answer
1 of 3
3

A common, but very frustrating and time-wasting typo, which can get even the best Python developers. Replace roll2 == random.randint(1,6) + random.randint(1,6) with roll2 = random.randint(1,6) + random.randint(1,6).

Also, I think you need roll2 != roll and roll2 != 7. From a stylistic point of view, it's better to omit the parenthesis around the statement evaluated in an if or while line.

Your loop has a slight amount of redundancy in it though. You check for roll2 being roll or 7 at the top of each loop and at the end of each loop. You could also consider trying this:

while True:
    # do everything in the same way as before

or

while roll2 != roll and roll2 != 7:
    # do stuff with the roll
    roll = random.randint(1,6) + random.randint(1,6)
return 1 if roll2 == roll else return 0 # a "ternary operator" in Python
2 of 3
2

A double equals sign tests for equality. Change it to single for your code to work. Here is your edited code:

import random
def craps()
    roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter 
    return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
    return 0
else:
    roll2 = 0 #initializes roll2 for the while
    while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
        roll2 = random.randint(1,6) + random.randint(1,6) #Rolls the dice
        if (roll2 == roll): #Tests if the player should win
            return 1
        elif (roll2 == 7): #Tests if the player should lose
            return 0

win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games): 
    win = win + craps() #adds a 1 or a 0 depending on if a game was won

print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning

Here is an example:

>>> import time
>>> x = 7
>>> x == 7
True
>>> while x != 6:
...     x == 6
...     time.sleep(1)
... 
False
False
False
^CTraceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt
>>> while x != 6:
...     x = 6
...     time.sleep(1)
... 
>>> 
🌐
Quora
quora.com › Why-doesnt-my-while-loop-stop
Why doesn't my while loop stop? - Quora
Answer (1 of 6): When you write a loop, there are several things for you to think about. I’ll specifically address while loops here, but much of this applies to other kinds of loops too. 1. For any loop you are putting into your program, you should have a brief statement in mind (maybe even ...
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-exit-a-while-loop-with-a-break-statement-in-Python.php
How to Exit a While Loop with a Break Statement in Python
Any program that contains the ... evalues to True. Since the while statement is true, it keeps executing. The program goes from 1 upwards to infinity and doesn't break or exit the while loop....
🌐
Python.org
discuss.python.org › python help
Loop not ending - Python Help - Discussions on Python.org
July 16, 2023 - The while loop is not ending even if num2find != -1 , it keeps on doing 27 , 28 (see numbers). para1 is just a paragraph (don’t mind that)
🌐
Reddit
reddit.com › r/learnpython › can someone tell me why my while loop doesn't terminate when i want it to?
r/learnpython on Reddit: Can someone tell me why my while loop doesn't terminate when I want it to?
November 15, 2023 -

Hey everyone,

I've been learning Python for about a month, and I just recently got into exceptions. I was working through a problem from a book, and I can't figure out why my while loop isn't functioning how I want it to. The problem asks me to write a code in which you take in two numbers as input values and add them while also accounting for the "ValueError" exception. In my code, which I've linked below, the while loop doesn't terminate when I enter "quit" as the first_number. It only terminates when I enter it as the second_number. In other words, it only breaks when I enter "quit" twice in a row. However, since I use the "or" keyword, shouldn't the while loop terminate if I enter "quit" as either the first or second number? My code is linked below along with what I see in the terminal. Any help or feedback would be appreciated. Thank you.

Code: while loop code

Terminal: output

🌐
Reddit
reddit.com › r/learnpython › ending while true loop
r/learnpython on Reddit: Ending While True Loop
August 17, 2023 -

I'm doing a CS50p project on making a grocery list. The only issue I'm having is once the list prints, I need the program to end. No matter where I break, it either doesn't stop the program or does stop it but bugs something else.
This is what I have:

def main():
list = []
while True:
    try:
        item = input()
        list.insert(0, item)
        continue
    except EOFError:
        list.sort()
        while list != None:
            for word in list:
                x = list.count(word)
                if x != 0:
                    print(str(x) + " " + str.upper(word), sep=" ")
                    list = [i for i in list if i!=word]
                else:
                    break
        break

main()

🌐
freeCodeCamp
freecodecamp.org › news › python-while-loop-tutorial
Python While Loop Tutorial – While True Syntax Examples and Infinite Loops
November 13, 2020 - We have to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to False. Great. Now you know how while loops work, so let's dive into the code and see how you can write a while loop in Python.