I know a lot of people debate on break
vs. if condition: quit == True
in while
and until
loops. I've heard a common opinion of break
is that it isn't verbose and it can lead to terrible code structure. Though I was working on a project for CS110, and I needed to make a menu, that would cycle though until a user entered 'Q'
, and would add commands onto a list until 'X'
was inputted, then it would execute those commands. If the command started with 'X'
, you can do other stuff, like play a song, but I didn't want that to be obvious to the user. This is my code in Python
usrCommands = []
def menu():
global usrCommands
# Take user input
quit = False
while not quit :
print("Please enter a command for the Finch :")
print("\tW - Move Forward")
print("\tS - Move Backward")
print("\tA - Turn Left")
print("\tD - Turn Right")
print("\tX - Execute Commands")
print("\tQ - Quit")
usrIn = input("> ").upper()
print()
# Parse for valid input
contains = False
for letter in 'WSADQ' :
if usrIn.find(letter) != -1:
contains = True
# execute if command is invalid unless the command starts with 'X'
if not( (contains and len(usrIn) == 1) or (usrIn.find('X') == 0) ):
displayInvalid()
continue
if usrIn == 'Q' :
quit = True
continue
if usrIn != 'X':
usrCommands.append(usrIn)
print(usrCommands)
My question is in the
if usrIn == 'Q' :
quit = True
continue
block. Here I've got the same syntax as an if
terminating a while
loop the normal way, but instead of including it at the end, I have the same effect as using a break statement. However, here you can easily see that quit
is now equal to True
. Is this an effective medium between break
and the standard way of doing this, for lack of better words? Are there any foreseeable problems with this in other projects?
This has essentially a very similar effect to break
, in terms of semantics. You are aborting the loop early using a keyword. So for the same reason you wouldn’t use break
, you wouldn’t use continue
there.
That being said, your structure does complicate things: First, it introduces an additional loop condition variable that has no other responsibility other than providing a work-around for break
. It does make the code more complicated though (e.g. you don’t immediately see that quit
is only changed where the continue
happens). Second, it requires reevaluation of the loop condition although you already know its result. So if we were to look at the byte code, instead of jumping to the end of the loop (as with break
), we jump to the start, recheck the condition and then jump to the end.
So, just to make it easier, I would absolutely use break
there. Note though that the common reasoning for not using break
is not the keyword itself but the fact that it introduces an additional exit from your loop (just like using returns
early in functions); and you are not changing that at all with using continue
there. So either use break
, or don’t interrupt the loop at all.