Continue statement in while loop python - Stack Overflow
How to break out of while loop in Python? - Stack Overflow
How can I break out of a while loop immediately and at any point during the while loop.
Can't understand "Continue" function in Python statement(for loop, while loop) !!
Videos
The continue statement ignores the rest of the loop and returns back to the top for the next iteration.
In your example count is 0 at the beginning. Since it is not equal to 5, the if statement is not executed and count is printed in incremented by one. When count finally reaches 5 after 5 iterations or the loop, the if statement is executed. Since the only instruction is continue, the print and increment are never executed: the rest of the loop body is ignored. After this point count always has a value of 5 and this state continues indefinitely.
It does not break the loop, the loop is still running forever, doing nothing.
count = 0
while count < 15:
if count == 5:
continue
# The following is ignored after count == 4
print(count)
count += 1
I think you need to use a pass statement instead of continue and change your indentation (this is assuming you want to print numbers from 0-15 but not 5).
pass is the equivalent of doing nothing
count = 0
while count <15:
if count == 5:
pass
else:
print(count)
count += 1
continue takes the code to the end of the loop. This means that when count is 5, the loop goes to the end and the value of count never increments and gets stuck in an infinite loop.
Take a look at break, pass and continue statements
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
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