A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break
Answer from John La Rooy on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how can i break out of a while loop immediately and at any point during the while loop.
r/learnpython on Reddit: How can I break out of a while loop immediately and at any point during the while loop.
February 5, 2023 -

I have a long while loop, it has a lot of code in it and a lot of delays.

I want to break out of the loop when a condition is met but I need to break out of it instantly. The only thing I can think of, is to print if statements constantly through the loop, checking if the condition is true, but this seems a little silly because it would have literally 100s of break statements.

Is there any better way to do this without typing break statements after every single line of code, that seems impractical because there's 100s of lines of code in the while loop, it takes around 10 minutes to finish and I need it to break instantly

🌐
W3Schools
w3schools.com › python › python_while_loops.asp
Python While Loops
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. With the break statement we can stop the loop even if the while condition is true:
Discussions

Can't get while loop to stop
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): ... More on discuss.python.org
🌐 discuss.python.org
0
0
May 6, 2024
how to stop the while loop
Andrew McLane is having issues with: So I added a while loop so that the loop could run for words that had multiple vowels, and multiple of the same vowels. However, I can't figure ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
October 29, 2017
Breaking/continuing out of multiple loops - Ideas - Discussions on Python.org
Hi! SUGGESTION An easy way to break/continue within nested loops. MY REAL LIFE EXAMPLE I am looping through a list of basketball players, each of which has multiple tables, each of which can have up to three different versions. I manipulate data in the deepest loop and, if some key data is ... More on discuss.python.org
🌐 discuss.python.org
2
August 21, 2022
Exit while loop in Python - Stack Overflow
I thought the while loop would provide that option but so far I can't figure out how to make it work. 2013-05-20T19:25:39.86Z+00:00 ... You won't be able to swiftly break out of all the nested loops. If you're in a script however, you can use sys.exit() which will break out of the complete execution of the file and execute nothing after it. 2013-05-20T19:29:44.573Z+00:00 ... @caadrider Python ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - So far, you’ve seen examples where the entire loop body runs on each iteration. Python provides two keywords that let you modify that behavior: break: Immediately terminates a loop.
🌐
LearnDataSci
learndatasci.com › solutions › python-break
Python break statement: break for loops and while loops – LearnDataSci
Can you see why? while True: res = input("Enter the number 5: ") try: res = int(res) except: pass if res == 5: print("Thanks!") break ... It can be hard to spot when one of your background processes gets caught in an infinite loop. You're not breaking any of Python's rules by getting stuck in a loop, so there are often not any helpful error messages to let you know what you've done wrong.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-break-statement
Python break statement - GeeksforGeeks
The break statement can be used within a for loop to exit the loop before it has iterated over all items, based on a specified condition. ... A while loop in Python repeatedly executes a block of code as long as a specified condition is True.
Published   5 days ago
Find elsewhere
🌐
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): ...
🌐
Enki
enki.com › post › how-to-exit-a-loop-in-python
Enki | Blog - How to Exit a Loop in Python
Learn to manage loops effectively in Python using the break statement to exit for and while loops under specific conditions, optimizing code efficiency.
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
In a for loop, the else clause is executed after the loop finishes its final iteration, that is, if no break occurred. In a while loop, it’s executed after the loop’s condition becomes false.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-while.html
While Loop
Here is a more realistic example of break looping over a string. The while loop goes through the index numbers in the usual way 0, 1, 2, .. len-1. In the loop, an if statement checks for a digit, and breaks out of the loop when found.
🌐
Team Treehouse
teamtreehouse.com › community › how-to-stop-the-while-loop
how to stop the while loop (Example) | Treehouse Community
October 29, 2017 - ... def disemvowel(word): while ... word.remove("U") except ValueError: pass return word ... The python 'break' statement is used to break out of a loop....
🌐
Programiz
programiz.com › python-programming › break-continue
Python break and continue (With Examples)
We can use the break statement with the for loop to terminate the loop when a certain condition is met. For example, ... Note: We can also terminate the while loop using a break statement.
🌐
Python.org
discuss.python.org › ideas
Breaking/continuing out of multiple loops - Ideas - Discussions on Python.org
August 21, 2022 - Hi! SUGGESTION An easy way to break/continue within nested loops. MY REAL LIFE EXAMPLE I am looping through a list of basketball players, each of which has multiple tables, each of which can have up to three different versions. I manipulate data in the deepest loop and, if some key data is ...
Top answer
1 of 6
10

The while loop will match the condition only when the control returns back to it, i.e when the for loops are executed completely. So, that's why your program doesn't exits immediately even though the condition was met.

But, in case the condition was not met for any values of a,b,c then your code will end up in an infinite loop.

You should use a function here as the return statement will do what you're asking for.

def func(a,b,c):
    for a in range(3,500):
        for b in range(a+1,500):
            c = (a**2 + b**2)**0.5
            if a + b + c == 1000:
                print a, b, c
                print a*b*c
                return # causes your function to exit, and return a value to caller

func(3,4,5)

Apart from @Sukrit Kalra's answer, where he used exit flags you can also use sys.exit() if your program doesn't have any code after that code block.

import sys
a = 3
b = 4
c = 5
for a in range(3,500):
    for b in range(a+1,500):
        c = (a**2 + b**2)**0.5
        if a + b + c == 1000:
            print a, b, c
            print a*b*c
            sys.exit()     #stops the script

help on sys.exit:

>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
2 of 6
6

If you don't want to make a function ( which you should and refer to Ashwini's answer in that case), here is an alternate implementation.

>>> x = True
>>> for a in range(3,500):
        for b in range(a+1, 500):
            c = (a**2 + b**2)**0.5
            if a + b + c == 1000:
                 print a, b, c
                 print a*b*c
                 x = False
                 break
         if x == False:
            break
200 375 425.0
31875000.0
🌐
Inductive Automation
forum.inductiveautomation.com › ignition
Command to break while loop if stuck in a script - Ignition - Inductive Automation Forum
June 6, 2013 - A way to break out of a while loop would be nice. Several times while testing a while loop inside a script, the script got stuck in an infinite loop. The only way I found to get out of it is to "End Task", relaunch Des…
🌐
Python.org
discuss.python.org › python help
The while loop isn't breaking - Python Help - Discussions on Python.org
August 24, 2023 - While true : D = input(‘enter 0 to exit’) If D == 0: Break Print(‘loop ended’) This loop isn’t breaking and is asking ‘enter 0 to exit’ again and again. Is there something wrong with the code.
🌐
Coursera
coursera.org › tutorials › python-while-loop
How to Write and Use Python While Loops | Coursera
A Python while loop only runs when the condition is met. Since it checks that condition at the beginning, it may never run at all. To modify a while loop into a do while loop, add true after the keyword while so that the condition is always true to begin with. Then, you can add if statements to check the inside condition and break statements to control the flow of the loop based on your terms.
🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to gracefully exit Python while loop on condition? - LambdaTest Community
October 12, 2024 - How can I exit while loop Python gracefully when a certain condition is met? In the code below, I’d like the while loop to exit as soon as the sum of a + b + c equals 1000. However, when testing with print statements, it…
🌐
PYnative
pynative.com › home › python exercises › python if else, for loop, and range() exercises with solutions
Python if else, for loop, and range() Exercises with Solutions
April 19, 2025 - numbers = [12, 75, 150, 180, 145, 525, 50] # iterate each item of a list for item in numbers: if item > 500: break elif item > 150: continue # check if number is divisible by 5 elif item % 5 == 0: print(item)Code language: Python (python) Run · Write a Python program to count the total number of digits in a number using a while loop.