Sorry to have come off as a noob or something but I’m struggling with this very basic question since a long time, especially in Python. My if blocks are slowly but surely growing into gigantic logical monsters in one Python program I’m writing!
Now, I know the wisdom offered here is to just take that functionality to a different function or library and just call it. However, it’s not always feasible without doing an extensive effort (for example, my IF block is inside another while loop and depending on several counter and line variables, now I’ll have to pass all of this to another function which makes the whole thing cumbersome, isn’t it?)
For some reason, I’m thinking that allowing a break from an if block should be something very intuitive which programmers have missed, I think it used to be there in the old Basic language (perhaps C and Foxpro as well?). The alternative here is to create another monstrous IF block within that which means another indentation which kinda sucks in Python, isn’t it?
A loop keeps repeating itself until a condition is met. Sometimes you have a race condition which forces you to break outside that loop because it’s going to have problems.
An IF statement on the other hand is a singular execution. It either runs if a condition is met, or it doesn’t, so if nothing is supposed to happen if a condition is not met, then empty code is not needed. So in your example, the best way to code it would simply be
m = re.match("(.) quick brown fox", str)
There are those which think ALWAYS having an else is more readable, but I’m not one who prescribes to that theory. To me, simpler, cleaner code is always preferable.
The ONLY exception I make to that is if there is a complex race condition where if five or ten race conditions are checked. If all are good, do nothing otherwise do something. In that case, I would write the if statement which does nothing if true and all the actions if false rather than trying to run the inverse.
if (a or (b and c) or (c and (d or e))) and g > 10:
# do nothing
if ((!a and (!b or !c) and (!c or (!d and !e)) or g <=10
I get what you’re saying, but that’s not the point I was trying to make.
For readability sake I may, at times, use an empty block and perform all the actions on the else. It’s rare and few and far between, but it typically comes in when there is a complex race condition with multiple business rules all having to be met. Even then, I often try to refactor it into a manner which is more readable and maintainable.
Shorter isn’t always better. Readability and maintainability is the end goal for me.
I guess what the TO is searching for is not a break in the if but a goto.
To be honest if you are a really good structured programer, a goto can be a very good tool to make more readable code, but when I remember the end 70th when I started programming, 99% of the goto were a big mess.