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.
Videos
Is there a break function in Python?
How do you write a break in Python?
What is the break statement in Python?
Usually, this is done by returning some value that lets you decide whether or not you want to stop the while loop (i.e. whether some condition is true or false):
def stopIfZero(a):
if int(a) == 0:
return True
else:
print('Continue')
return False
while True:
if stopIfZero(input('Number: ')):
break
A function can't break on behalf of its caller. The break has to be syntactically inside the loop.