Until the inner loop "returns", the condition in the outer loop will never be re-examined. If you need this check to happen every time after i changes, do this instead:
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if i > 10:
break
That break will only exit the inner loop, but since the outer loop condition will evaluate to False, it will exit that too.
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
How to break out of while loop in Python? - Stack Overflow
How do I end a For or While loop without using break?
Use of break in Python
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 Videos
Until the inner loop "returns", the condition in the outer loop will never be re-examined. If you need this check to happen every time after i changes, do this instead:
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if i > 10:
break
That break will only exit the inner loop, but since the outer loop condition will evaluate to False, it will exit that too.
i = 0
x = 100
def do_my_loops():
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if time_to_break:
return
do_my_loops()
where time_to_break is the condition you're checking.
Or in general:
def loop_container():
outer_loop:
inner_loop:
if done:
return
loop_container()
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
I would run the loop until ans is 'Q' like this:
ans = 'R'
while not ans == 'Q':
print('Your score is so far ' + str(myScore) + '.')
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans == 'R':
R = random.randint(1, 8)
print("You rolled a " + str(R) + ".")
myScore = R + myScore