python - How can I break out of multiple loops? - Stack Overflow
How to break out of while loop in Python? - Stack Overflow
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
Quite a number of my fellow teachers have been saying that we should NEVER use breaks in loops. However in our examination there is often a need to validate an input e.g.
while True:
ID = input("What is the cow's ID code?")
if len(ID) == 3:
CowID.append(ID)
break
else:
print("Cow ID has been entered wrongly.")The break works perfectly well in Python, but it has been suggested to me that I avoid using such constructs. What are your thoughts on this and does anyone have credible sources one way or another? In the age of the Internet my students will quickly find break and I would need a very strong argument as to why they don't use it. Equally, if I go against these other teachers I will need credible evidence as to why I am doing it this way.
Your thoughts, arguments and ideas are very much appreciated. This debate has been rumbling on already for over a month and I would like to get a good answer before I plan next year's lessons.
My first instinct would be to refactor the nested loop into a function and use return to break out.
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.
for a in range(10):
for b in range(20):
if something(a, b):
break # Break the inner loop...
else:
continue # Continue if the inner loop wasn't broken.
break # Inner loop was broken, break the outer.
This uses the for / else construct explained at: Why does python use 'else' after for and while loops?
Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.
The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.
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