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

Gracefully Exit While Loop Apr 4, 2015
r/learnpython
11y ago
how to exit loop Oct 30, 2022
r/learnpython
3y ago
As a beginner how do I understand while loops? Apr 10, 2025
r/learnpython
last yr.
break outside of loop? Sep 4, 2022
r/learnpython
3y ago
More results from reddit.com
๐ŸŒ
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

How to break out of while loop in Python? - Stack Overflow
I have to make this game for my comp class, and I can't figure out how how break out of this loop. I have to play against the "computer," by rolling bigger numbers, and seeing who has the More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
Use of break in Python
Break is a valid move. More on reddit.com
๐ŸŒ r/learnpython
14
0
May 11, 2019
Using break statement to end a loop.

Your code works fine, but you should be putting the check for if the user input is quit before the print statement. It should look like below.

while True: 
  user_input = input("Write something") 
  if user_input == "quit": 
    break 
  print(user_input, end = " ") 
print("Bye bye")
More on reddit.com
๐ŸŒ r/learnpython
8
4
June 19, 2018
๐ŸŒ
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.
๐ŸŒ
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
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
TutorialKart
tutorialkart.com โ€บ python โ€บ python-while-loop โ€บ python-while-loop-break
Python While Loop with Break - Examples
October 7, 2024 - Python While Loop with Break Statement - We can break while loop using break statement, even before the condition becomes false. In this tutorial, we write example Python programs for breaking while loop using break statement.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ break-statement
Python Break Statement: Syntax, Usage, and Practical Examples
If youโ€™re a visual thinker, a quick flowchart for this looks like: check the condition, if itโ€™s true then exit the loop, otherwise keep going. It's important not to confuse the break statement with continue. While break exits the loop entirely, continue skips to the next iteration.
๐ŸŒ
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.
๐ŸŒ
PythonHow
pythonhow.com โ€บ how โ€บ break-a-while-loop
Here is how to break a while loop in Python
New: Practice Python, JavaScript & SQL with AI feedback โ€” Try ActiveSkill free โ†’ ร— ... import random # This loop will run forever unless we break it while True: # Generate a random int between 1 and 10 random_integer = random.randint(1, 10) print(random_integer) # Stop the loop if the random int is 5 if random_integer == 5: break
๐ŸŒ
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....
๐ŸŒ
Learn Python
learnpython.dev โ€บ 02-introduction-to-python โ€บ 110-control-statements-looping โ€บ 40-break-continue
break, continue, and return :: Learn Python by Nina Zakharenko
One common scenario is running a loop forever, until a certain condition is met. >>> count = 0 >>> while True: ... count += 1 ... if count == 5: ... print("Count reached") ... break ...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_loop_control.htm
Python Break, Continue and Pass Statements
for letter in 'Python': # First Example if letter == 'h': break print ('Current Letter :', letter) var = 10 # Second Example while var > 0: print ('Current variable value :', var) var = var -1 if var == 5: break print ("Good bye!") ... Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye! The continue statement in Python returns the control to the beginning of the while loop.
๐ŸŒ
Problem Solving with Python
problemsolvingwithpython.com โ€บ 09-Loops โ€บ 09.03-Break-and-Continue
Break and Continue - Problem Solving with Python
An example using break in a while loop is below. ... In Python, the keyword continue causes the program to stop running code in a loop and start back at the top of the loop. Remember the keyword break cause the program to exit a loop.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_break_statement.htm
Python - break Statement
for letter in 'Python': if letter ... Good bye! Similar to the for loop, we can use the break statement to skip the code inside while loop after the specified condition becomes TRUE....
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
๐ŸŒ
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 ...
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Python while Loop (Infinite Loop, break, continue) | note.nkmk.me
August 18, 2023 - If the condition in the while statement is always True, the loop will never end, and execution will repeat infinitely. In the following example, the Unix time is acquired using time.time(). The elapsed time is then measured and used to set the condition for when to break out of the loop. Measure elapsed time and time differences in Python