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.
June 23, 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

Exit while loop in Python - Stack Overflow
To avoid this problem, you can add explicit break statements to the for loops (and as Sukrit Kalra points out, the while loop becomes unnecessary). More on stackoverflow.com
๐ŸŒ stackoverflow.com
Ending While True Loop
You use list as a variable name. This masks the list constructor which can cause weird problems. I changed list to l everywhere. Don't know if using list caused problems. You are changing the list you are iterating over in the for loop. Bad idea. Don't know if doing that causes problems, but it's a bad idea. You use while list != None: in an attempt to check if the new list is empty. Trouble is, an empty list looks like [] and never equals None. Use python "truthiness": while list: More on reddit.com
๐ŸŒ r/learnpython
18
3
August 17, 2023
How can I break out of a while loop immediately and at any point during the while loop.
Literally, this is what the break statement does. More on reddit.com
๐ŸŒ r/learnpython
32
0
June 23, 2023
Is using a while(true) loop bad coding practice?
Iโ€™m with you, I think itโ€™s totally fine. I mean you could misuse it, but then that goes for anything, especially in programming. I wouldnโ€™t bat an eye if a candidate did it in an interview. More on reddit.com
๐ŸŒ r/learnprogramming
124
391
May 13, 2021
๐ŸŒ
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.
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
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ break-statement
Python Break Statement: Syntax, Usage, and Practical Examples
The Python break statement is a valuable tool for controlling loop execution. It allows you to exit for or while loops as soon as a condition is met, making your code cleaner, faster, and easier to understand.
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
Coursera
coursera.org โ€บ tutorials โ€บ python-break
How to Use Python Break | Coursera
When working with loops, remember that indentation tells Python which statements are inside the loop and which are outside the loop. Your break statement should follow your if statement and be indented. ... 1 2 3 4 5 6 7 8 9 10 # break statement for for loop for item in iterable: if some_condition: break # exit the loop # break statement for while loop while condition: # code block if some_condition: break # exit the loop
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-while.html
While Loop
Given that we have if/break to get out of the loop, it's possible to get rid of the test at the top of the loop entirely, relying on if/break to end the loop. We do this by writing the loop as while True:...
๐ŸŒ
Medium
sibabalwesinyaniso.medium.com โ€บ mastering-while-loops-break-and-continue-in-python-controlling-program-flow-efficiently-e3a7512b3710
Mastering While Loops, Break, and Continue in Python โ€” Controlling Program Flow Efficiently | by Sibabalwe Sinyaniso | Medium
February 4, 2025 - password = "" while password != ... the correct password until the user enters "python123". The break statement immediately exits a loop, regardless of its condition....
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ break-continue
Python break and continue (With Examples)
i = 0 while i < 5: if i == 3: break print(i) i += 1 ... The continue statement skips the current iteration of the loop and the control flow of the program goes to the next iteration.
๐ŸŒ
Coursera
coursera.org โ€บ tutorials โ€บ python-while-loop
How to Write and Use Python While Loops | Coursera
This loop will print the numbers 1 to 5, which is equivalent to the behavior of a do while loop that iterates from 1 to 5. We use a break statement to exit the loop once we have printed all the numbers, since the while condition is always True ...
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-break-statement
Python Break Statement - GeeksforGeeks
The break statement in Python is used to immediately terminate a for or while loop when a specified condition is met.
Published ย  June 5, 2026
๐ŸŒ
Jobtensor
jobtensor.com โ€บ Tutorial โ€บ Python โ€บ en โ€บ While-Loop
Python While Loop, break, continue, else | jobtensor
i = 1 while i < 10: print(i) if i == 3: break i += 1 ยท The continue statement can stop the current iteration, and continue with the next. i = 1 while i < 10: i += 1 if i == 3: continue print(i) The else statement can run a block of code once when the condition no longer is true. i = 1 while i < 5: print(i) i += 1 else: print("i is no longer less than 5") Using the while loop, modify the code to print x as long as x is less than 9 but do not print the number 5.
๐ŸŒ
Quora
quora.com โ€บ What-is-the-method-for-breaking-out-of-a-for-loop-in-Python
What is the method for breaking out of a for loop in Python? - Quora
Answer: In Python, you can break out of a [code ]for[/code] loop using the [code ]break[/code] statement. Once the [code ]break[/code] statement is executed, the loop terminates immediately, and control moves to the next statement after the loop. Syntax: [code]for element in iterable: if co...
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ asyncio-task.html
Coroutines and tasks โ€” Python 3.14.6 documentation
import asyncio import datetime as dt async def display_date(): loop = asyncio.get_running_loop() end_time = loop.time() + 5.0 while True: print(dt.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1) asyncio.run(display_date())
๐ŸŒ
Quora
quora.com โ€บ How-can-I-break-out-of-the-innermost-while-loop-while-True-on-Python-without-breaking-the-outer-while-loops
How to break out of the innermost while loop (while True) on Python without breaking the outer while loops - Quora
Answer (1 of 3): Hello! What will Ramesh Kummar's program achieve? For each value of the number i (ranging from 0 to 4 ) we should print the number i and then let J vary by values โ€‹โ€‹0 through 3. And also print all the j values. We have here an iteration of i values โ€‹โ€‹and each sequence ...
๐ŸŒ
Udemy
udemy.com โ€บ development
Python Mega Course: Build 20 Real-World Apps and AI Agents
June 9, 2026 - Master the for loop by iterating over lists and strings, printing and capitalizing each item, with on-the-fly variables and the key difference from while loops. ... Learn how Python uses CPython as the interpreter to translate Python code into machine language, enabling your computer to run and display results. ... We recap yesterday by showing a todo app that uses a match case block to handle add, show, and exit commands, strips user input, and breaks the loop on exit.
Rating: 4.6 โ€‹ - โ€‹ 73.6K votes
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ whatsnew โ€บ 3.14.html
Whatโ€™s new in Python 3.14
If you need to run something in an event loop, then run some blocking code around it, use asyncio.Runner.