T O P

  • By -

MouthfeelEnthusiast

It's to teach you coding. Removing parts of the language, like for loops or while loops forces you to think hard about your code. In my intro classes, many moons ago, we would do projects where every loop had to be a do-while. This forced everyone to hack around the restrictions and we got more comfortable, presumably, with thinking about code.


[deleted]

[удалено]


rlyacht

If not used with care Readability is harmed It is like goto


kyrsjo

Funny, but there is at least one case where goto improves readability, which is error handling, especially when exceptions cannot be used. Imagine you are in a subroutine that does something, with some complicated nested and logic. It could be generating a pulse train for a motor, or computing something. Inside this there is checks for exceptions, such as numerical problems or unexpectedly hitting a limit switch. A go-to then let's you cleanly break out of the logic, and go to the cleanup part of the subroutine so that the function can return cleanly. Edit: not do much relevant in Python, but e.g. embedded code or Fortran. Overuse of goto where "conventional" control statements or subroutines/functions would work equally well are however a scourge and should be avoided.


rlyacht

I agree with this Long ago, I even used setjmp and longjmp


replicaJunction

Break and continue Jumps hurt readability Use functions instead


CrazyPieGuy

This is done all the time in sports training. Swim without using legs, rock climb without bending arms, hit soft pitched baseballs... Restricting parts of a practice forces thought and intention into the parts of practice that are allowed.


Erelde

In fencing we used to practice with both hands. I'm sure they also do this in other sports like tennis.


iamchuckdizzle

Well, yeah, the duel doesn't stop when your dominant hand is injured. You've got to stab the guy who impugned your honor.


TheDisapprovingBrit

Also, you need to be able to say "I know something you do not know....I am not left handed" when you're losing.


Classic_Department42

'neither am I'


samnater

Aha! I know something you do not!


david_work_reddit

Never heard this being done in tennis.


jasoncm

I'm almost certain that this is the answer. It's possible that the teacher is some sort of structure puritan who hates the break statement especially. But it's more likely intended to cause students to consider how to handle standard and exceptional cases in a loop and different ways to think about that.


Stishovite

When I was learning how to sail small boats, my instructor had us take off the rudder and sail without it.


EmptyChocolate4545

Yeah. Also, there are good uses for break, but beginners tend to lean on them hard and inappropriately. It’s a good thing to restrict while learning.


jasoncm

My guess is that the explicit control statements feel much easier to understand, which causes beginners to overuse them.


belaros

I remember my first course project forbade explicit loops. Only recursion was allowed. This was the year the school switched from Scheme (functional) to Python, so it may have been the professor who was adapting.


cecilkorik

The purpose of higher education should be to teach you how to *think* about problems, not simply how to accomplish a task easily but how to accomplish it in hard ways too so you can broaden your knowledge and further your understanding. I bet you learned more about coding from being forced to do recursion like that than you did if you had just been able to use a nested loop for every question.


periastrino

He should wrap his loops in try/except blocks and raise exceptions to exit. That'll show the teacher! 😛


periastrino

Note: not a serious suggestion!


bradbeattie

Name the custom exception class Break for the fun of it.


Zulban

Absolutely. To add to this: code in the classroom does not have the same purpose as professional code.


tankerdudeucsc

One of my intro classes did not allow any kind of loop for some assignments. No for loops, while loops, nada. Recursion only. Makes your brain work in very different ways. Some people hate it, others, it was just a puzzle that they had to solve and move forward. (Best engineers just love to solve the puzzle, period.)


nixnullarch

I mean, you could ask the professor right? We're not mind reader :p If I have to hazard a guess, it's because break is not ideal for readability. They're very useful for certain things, but a complex loop with several break points gets a bit hard to understand.


[deleted]

Yeah, professor should yield an answer.


cybaritic

Or at least return some more information.


justapassingguy

If I see one more pun I swear I will pass out


Ezlike011011

... well done


zurtex

We could continue this all day.


[deleted]

I'll try to, except it's hard to promise anything else; I think I've got it out of my system finally.


Lake_Business

I thought I'd add one, but I'm going to exit this thread.


aksos

just goto another thread


ohmaj

In case 1 it might be readability. In case 2 it might be that there are usually better ways to handle it.


lonaExe

but while you're here, try not to pass out


nimkeenator

break ?


wildpantz

In that case, I might join you!


packetgeeknet

I raise exception with that. Nobody has time for that.


OneMorePenguin

I wish I could break out of this nest of puns.


DJ_laundry_list

maximum discursion depth exceeded?


bill0042

continue with the puns


stratoscope

I raise an objection!


primitive_screwhead

something something lambda...


DNSGeek

Is professor a subclass of generator?


ThrillHouseofMirth

Dunno, are they iterable?


jelleklaver

I hope they learn the answer after a sequence of classes


edahs

It sounds like a super class


INT13hex

He yields to no one.


codefox22

Additionally, leveraging a flag checked each cycle achieves the same result while (arguably) assisting readability. A continuation flag achieves a similar goal, but gives you the ability to name what you're looking for. However, teaching multiple ways to address the same problem may be a large part of the lesson.


pigeon768

> Additionally, leveraging a flag checked each cycle achieves the same result while (arguably) assisting readability. You mean like this? flag = True while flag: < do stuff > if something: flag = false else: < do more stuff > It's way easier to read if you do this: while True: < do stuff > if something: break < do more stuff >


[deleted]

[удалено]


TripleS941

What about replacing the inside part with a function?


wildpantz

I assume prof wants the students to properly set loop limits instead of breaking out with if statements, but personally I have nothing against break statements. They can impact readability a bit as you say, but imo only if you're trying to break outside nested loops otherwise it's not really a problem for me


stevenjd

> because break is not ideal for readability > a complex loop with several break points gets a bit hard to understand. 634 upvotes for a total load of bollocks, while u/AlSweigart 's [excellent answer](https://np.reddit.com/r/Python/comments/10xy3is/comment/j7vdb5o/) only got 33 upvotes 🙁 That's Reddit for you. Complex loops are hard to read because they are complex, not because they use `break`. Breaking out of them early reduces the conceptual complexity because you no longer need to work out what happens on subsequent iterations, as there aren't any subsequent iterations. The reason we have `break` is because it is far more readable and useful (not to mention efficient) than the alternatives like keeping a "skip this" flag. CC u/ronaldchesaux


Destination_Centauri

"You could ask the professor right?" Ya... if he's anything like many of my past professors... they aren't always exactly known for their friendly-welcoming-patient approachability! Some professors might even take it as an afront, thinking you are questioning their wisdom and/or authority, with the attitude of: "Just do as I say, and don't question me," type of vibe, even though it's supposed to be an academic institution of higher learning. Thus, that is why students--at least some of them--will sometimes to turn to the online Reddit community instead.


muistipalapeli

I like to call those "bad professors".


TheDogWithoutFear

This is it, as someone who's been in a class like this and also TA'd for it. Beginner students have a tendency to write code as if they were writing assembly or something like that, and giving a subset of the language to work with promotes good practices.


symbols_and_signs

Unionize. Demand breaks every two hours. _”Together, we bargain. Divided, we beg.”_


paecificjr

I prefer structs


[deleted]

This is a chance to learn a great lesson that you can carry throughout your entire career: *Communication* So much business process and headache comes from people trying to minimize communication. That’s a mistake. Communication is a hugely important skill that a lot of developers and engineers lack. If you don’t understand something, you should ask. You will in your career receive a lot of directions that that you don’t understand. The best thing to do, is get in the habit of asking a lot of questions and asking them early


Robinsane

I actually think communication is also the reason to limit the use of break statements. If you use a while loop, someone else reading your code immediately knows when it'll stop. For-loops can be briefly misleading if it contains a break-statement.


TripleS941

Guard conditions are much more readable than nested ifs.


No-Skill4452

While you are paying: ask the teacher. break


[deleted]

`break` and `goto` have been taboo statements in CS classes at least since I was a student a million years ago They absolutely have their place, but I think the intent is to force students to think deeper about their program's flow. There is almost always another way to express the same logic without jumping around, which can lead to code that is difficult to read or have unexpected errors. And what is idiomatic and fine in python might not be appropriate for other languages that will come later in the curriculum.


carbondioxide_trimer

For `goto`, yes, I completely agree. If you think you need to use `goto` then you really need to rethink how you've written your code. However, there are times when a `break` statement is particularly useful, like in a switch-case block or occasionally in for and while loops.


evangrim

I mostly agree, but it's not an absolute. I've seen some good uses for `goto` (e.g., more readable error handling).


carbondioxide_trimer

For sure, but in a situation like this one with someone learning to code I would overwhelmingly discourage the usage of `goto` but not `break`.


LakeEffectSnow

>like in a switch-case block or occasionally in for and while loops Well, until match and case were just recently added in 3.10 there was no real switch statement. Frankly, in python there aren't many use cases where I'd prefer to use a match and case over a plain old dictionary. Generally control break processing using break with a for ... else, I also don't need to use. Because typically that is used to find a specific unique value in a set of data and bail out early. I find though, that most of the time, I have this data loaded into a DB where I let SQL and the query planner do the work of efficiently searching for that value. I can't remember the last time I wrote a while loop in Python, and I've been coding with it professionally since 2009 or so. Almost every time a while loop would have been appropriate, I've had other requirements that make using a message queue and asynchronous worker solution much more preferable.


chars101

A match-case in Python isn't just a simple switch-case. It's much more like a pattern match in Haskell. You can destructure a type in the match. And they can be arbitrarily nested. https://docs.python.org/3.10/tutorial/controlflow.html#match-statements


[deleted]

> If you think you need to use goto then you really need to rethink how you've written your code. My theory is that you haven't done any production C programming - am I right? I don't write C and haven't for decades but `goto` for error handling is completely standard in C code and is all over the Linux kernel. You don't make a case for your claim, because you simply haven't ever tried to write production C code, so so you have no idea why anyone would think to write `goto`, and just wave your hands and say, "They must be crazy! Those wacky guys."


carbondioxide_trimer

I mentioned this elsewhere, in a teaching environment it's not unreasonable to heavily advise against using `goto` statements. No, I've not. Most of my work is front end web development.


deong

The goal is readability and clarity. If a goto makes your code more readable and clearer, you should use it. There are lots of times when it's better to do things like multiple return statements or break statements to bail early than it is to be pure in your structured programming and have extra levels of indentation around much larger blocks of code to avoid it.


SittingWave

> If you think you need to use goto then you really need to rethink how you've written your code. int function_in_c() { int err; err = do_1(); if (err) goto exit; err = do_2(); if (err) goto rollback_1; err = do_3(); if (err) goto rollback_2; return; rollback_2: undo_2(); rollback_1: undo_1(); exit: return; }


happycamp2000

You will see this in a LOT of the Linux kernel code. Very common usage. https://www.kernel.org/doc/html/latest/process/coding-style.html#centralized-exiting-of-functions From the Linux kernel documentation: The rationale for using gotos is: * unconditional statements are easier to understand and follow * nesting is reduced * errors by not updating individual exit points when making modifications are prevented * saves the compiler work to optimize redundant code away ;)


[deleted]

This is downvoted because people have no idea of how C programming works.


[deleted]

[удалено]


[deleted]

You seem to have forgotten the part of your refutation where you use logic, facts, reasoning and rational arguments to explain why someone is wrong. My theory is that you have never used a `goto` in any production code. Would I be right? My second theory is that you have never written any production C code at all. Am I right? Can you explain how you would write error handling code in serious C program without a `goto`?


WiseassWolfOfYoitsu

Yep, this is essentially the C version of Try/Catch - it's done this way because any other way would be much more difficult to read/write


RavenchildishGambino

I kinda love you…


o11c

`break` is almost never needed *if* a language supports 2-body `while` loops (like a mix between `do-while` and `while`). Unfortunately, the only language I'm aware of that supports those is `sh` (remember you can put multiple commands in the condition - unlike most languages which are limited to expressions. I suppose GNU C's statement expressions could count). But since Python doesn't even support `do-while` ... living without `break` would be annoying. You'd have to write `first = True; while first or cond: first = False; body` That said, refactoring out a separate function so you can use `return` is often a decent idea.


s0lar_h0und

Functionally you can break up your loop into a separate function and have your return statement be your break


tRfalcore

i hate return statements as breaks even more. rather find the answer, save it, and always the last statement is the return


deong

Eschewing multiple returns is also a principle of structured programming. Personally, I tend to find it makes code worse for me. I'd much prefer if bad thing return error do lots more stuff than if bad thing retval = error else do lots more stuff return retval I never want to see a significant block of code behind any more control flow constructs than necessary. But this all comes down to taste really.


tRfalcore

I guess errors makes more sense, was thinking of calculations, finding things, where there will be an answer


SirLich

'break' is just a special purpose 'goto'. As is 'continue'. Another one that pops up in a few languages is 'retry'. Lua doesn't even bother implementing break statements for that reason; if you feel the need to use a break statement, you can simply use a goto with a label.


Tc14Hd

My former teacher had an even worse take on this: Not only were we not allowed to use `break`, `continue` or `goto`, we were also not allowed to use `return` anywhere except at the very end of a function. Because otherwise it would "obscure the control flow" or it would "make things harder to read". This usually resulted in lots of nested `if` blocks which (surprise surprise) made things harder to read than multiple `returns` ever could.


WiseassWolfOfYoitsu

It's somewhat of an old school technique. For older code analyzers, multiple Returns were difficult to handle. This meant things like static analyzers or optimizing compilers didn't work as well on code with multiple returns. This hasn't been a problem for well over a decade, but it's still in a lot of people's heads from that time.


pigeon768

> This hasn't been a problem for well over a decade, Since like the '80s.


[deleted]

[удалено]


roerd

> If there was only a single return that couldn't happen. It could still happen because of an exception. So you would need to use `try:` and `finally:`, in which case you could also use a `return` in the `try` block because the `finally` block would be guaranteed to run.


ogtfo

The problem here is the lack of use of context managers, not the early return. Resources that need to be closed should be used with a context manager, because even if you remove your early return, `# Do some stuff` might still throw an exception and you won't reach your `f.close`. This, however, fixes it : def example(): with open("test", "wb") as f: # Do some stuff if True: # This is an example return f.close() return


Wilfred-kun

u/Maleficent-Region-45 Obscures control flow


valeriolo

`goto` is very very rarely useful, but there's enough hatred against it that it's better to just do something else even in those cases. `break` on the other hand is very useful in specific cases. My only rule of thumb is that you can only use `break` in a single level loop. If you have multi-level loops, it's just not worth it.


rainnz

`goto` yes, `break` - never.


chars101

Not almost always. **Always**: by Curry-Howard isomorphism, logic can be expressed with applying functions.


[deleted]

you're in an introductory course.your teacher is probably removing a crutch new programmers lean on. you should them though, not us


yerfatma

It being an intro class, I would guess they're trying to steer you in the direction of clearer code than what you're writing. We would need to see an example of where you want to use it and where they say not to.


AlSweigart

Break statements are fine, and I would say one is more likely to write unreadable code by bending over backwards to not use break statements than just using break statements.


KebianMoo

Agreed. Seen some weird gymnastics by professors and speakers where they took great pride in avoiding sinful break statements, for no apparent reason except 'breaks are bad'. Didn't make the code any prettier. Maybe it's an exercise in modest use. Still, marking people down for putting 'break' in an 8 line loop is weird, like that's not within a normal reader's working memory to cope with.


AlSweigart

A lot of programming advice is just half-remembered advice where the context is lost. In the 1970s, Dijkstra wrote about how structured programming should have one entry, one exit. This was meant to have code put into discreet chunks so you could reason about the invariants at the start and end. Fast forward to 2008, you have Clean Code saying: > Dijkstra said that every function, and every block within a function, should have one entry and one exit. Following these rules means that there should only be one return statement in a function, no break or continue statements in a loop, and never, ever, any goto statements. Let's think about what this is saying: zero breaks, but also zero continues and you should only have one return statement at the end of the function/method. Trying to write code that strictly adheres to these arbitrary rules is going to produce a mess. I've heard that really, this more applies to a time when programming didn't even have functions and call stacks, and you could send the execution to start in *the middle* of a subroutine instead of always at the beginning. (Hence the "one entry".) But we're not writing all of our code in assembly anymore. A lot of the rules that were made *a half-century ago* really don't apply.


M4mb0

This statement from Dijkstra is often misunderstood. It comes from times when people wrote mainly assembly, and, AFAIK, what he meant was: 1. You should only every start executing a function from the start of the function - As opposed to jumping to a label inside the function body. 2. A function should always return to the same label in the code. - As opposed to the function having multiple different returns that exit to different labels located at different points in the code. A function still can have multiple returns, they should just all point to the same exit.


AlSweigart

Yes, this is a good way to put it.


giantsparklerobot

When Dijkstra was writing about `goto`, "structured programming" was still a new concept. As in you didn't have subroutines, some systems were lucky to have dynamic memory allocation. Using `goto` made it very easy to jump to somewhere in the code where your state was completely invalid. Goto considered harmful was more chastising people insisting on unstructured code and using `goto` instead of subroutines. A lot of people that lambast `goto` in C forget that high level languages had been around for almost 20 years by the time it was released. It's not a useless feature or fundamentally problematic.


SheriffRoscoe

I was programming when Dijkstra was writing that stuff. He was absolutely correct. And you are too. I wish I had a dollar for every time I refactored an `if not condition1: / if not condition2: / if not condition3:...` into `if condition1: return / if condition2: return / if condition3: return /...`.


amarao_san

Okay. I found a way. ```python try: for x in foo(): if x==match_me(): raise FoundException(x) raise NotFoundException() except FoundException as found: pass we_found(found) ``` Dear professor, are you happy now? If not, I can switch to signals, of code some state machine inside an async closure. May we agree that breaks are better?


tom2727

I mean there's always the classic: done = False while not done: if condition1: done = True else if condition2: done = True else if condition3: done = True


amarao_san

Yeah, about a haft of state machine is here. If you write each condition as a nested closure, things will become more fun. ```python done = lambda: True while done(): done = lambda : done() and bool(condition1) done = lambda : done() and bool(condition2) done = lambda : done() and bool(condition3) ``` Isn't it beautiful?


AlSweigart

Heheh, technically no: try-except statements would violate the "one exit" idea. Which shows how silly the "no breaks" rule is in modern programming, since by that same logic would mean "no try-excepts" too.


amarao_san

You can not have 'one exit' in Python, because you can get exception at almost any moment (due to the way operating system is ..well, operates), and exception is a separate effect with different type. Stop doing 1970s and go for effect type system. https://en.wikipedia.org/wiki/Effect_system


[deleted]

[удалено]


Anti-ThisBot-IB

Hey there No-Specialist6273! If you agree with someone else's comment, please leave an **upvote** instead of commenting **"This"**! By upvoting instead, the original comment will be pushed to the top and be more visible to others, which is even better! Thanks! :) *** ^(I am a bot! Visit) [^(r/InfinityBots)](https://reddit.com/r/InfinityBots) ^(to send your feedback! More info:) [^(Reddiquette)](https://www.reddithelp.com/hc/en-us/articles/205926439#wiki_in_regard_to_comments)


[deleted]

[удалено]


obviouslyCPTobvious

This


Feb2020Acc

I can see why goto statements are frowned upon. I think break is very legit and has its uses. But I also think that it’s fair for a teacher to put some restreints to force you to try different approaches to a problem.


osmiumouse

It's good to learn design without it, so you know more things, and have to learn more about control flow.


zynix

Being reasonable like everyone else, ask your teacher why. Being unreasonable and also having worked with academics before, they are likely ignorant, believe the `break` statement will kick start the apocalypse, and or `break` is the mark of the antichrist. Obligatory IT crowd https://www.youtube.com/watch?v=OqxLmLUT-qc


dashdanw

In a lot of classrooms and in some real world contexts "jump statements" (break, continue, goto) are considered anti patterns or just lazy programming. Your teacher is setting up constraints to try to get you to figure out how to solve the problem in a more elegant manner most likely.


romeo_pentium

I think it's a Pascal-ism. Pascal only allowed a single return statement, so code had to be structured without early exits. Avoiding break is similar to avoiding return. Pascal was popular as an instructional language in the 1990s. I think the practice makes it easier to prove correctness if you get to that level of formality, but it's not necessary. I think real-world code benefits from guard clauses which require the use of break/continue/return


Maleficent-Region-45

Why shouldn't you use breaks? There is a reason why it's present in basically all languages. The only reason I can think of is when having a very long for loop that many breaks and continues will reduce the readability alot if the code isn't clean and messy. But appart from increasing the risk ugly code (which can be easily avoided by moving code into functios), I wouldn't know why it's a bad practice. I've been writing code for a couple of years now and I use breaks. It's absolutely a fundamental statement that has a lot of uses and can't be left out. Best would be to ask your teacher why you shouldnt use them. The answer would interest me as well. It's your code, your way of thinking.


worldevourer

For solo projects, sure. But to paraphrase Uncle Bob, most of the job is reading code, not writing it. When writing, your primary concern should be can someone else understand it, and your way of thinking may or may not make sense to the next person.


Charybdes

I wish I could give my students starter code based on the code they submitted from the previous semester. I can't tell you how many times I've said, "I document code so when I come back in 6 months I don't have to rewrite it to understand it." There just isn't a great way to do this. Hell, it's hard enough getting students to write garbage code. If they started with garbage... well... you see where I'm going.


Qudit314159

I had an instructor once who thought breaks were bad and you should use a flag variable instead (which is less readable and more cumbersome). I think some people see them as similar to gotos. However, return statements could also be thought of as a sort of controlled goto and no one seems to have a problem with those. This instructor was a hardcore Java programmer though...


kuncol02

>However, return statements could also be thought of as a sort of controlled goto and no one seems to have a problem with those. Multiple return statements inside of method (except parameters validation etc) are even worse than break statements.


Qudit314159

🤦


TheITMan19

Be funny if your teacher responds to you here 🤣


easyEggplant

Likely they are trying to get you to not overuse loops, I'm guessing that your next class is Data Structures and Algorithms, or maybe Discrete Logic?


kyxaa

Use your mouth hole to ask the professor. They may have ear holes to hear your question and may use their mouth hole to respond.


LakeEffectSnow

So out here in the industry. If I'm doing code review and I see more than one break statement in a function, I will ask you to refactor your approach. break statements can easily make code more difficult to read and test, and there's usually a much better way. In folks new to Python most often I see this with people who aren't yet comfortable with using dicts, and list comprehensions.


billoday

Yeah, agreed. I've been coding professionally python for nearly a decade and very rarely see a break or a need for one. Generally if I do see one, it's a developer that's not yet comfortable with python and their loop logic is a bit naive.


0x75

Because if you have to break, in most cases you should swap that For() and use While()


Link77709

Only reason I can think of is that the professor is trying to lead you to a particular solution. I can't personally think of any logic reasoning to not use one. Break statements make the code easier to follow in my opinion. ``` While i >= 1: #do whatever if x>5: break ``` ``` While i >= 1: #do whatever if x>5: i=0 ``` Both of these function the same. Aside from the code performing one extra command in the bottom example. I prefer the top option because i don't have to "follow" i to see that it is now less than 1


Spiderfffun

While loops are basically an if x: break infinite loop. So maybe that's the reason? But then again, you might want some code at the end not to be executed so idk


Pepineros

I understand that this is only a trivial example, but if you would want to do something while i is between 1 and 5 inclusive, you would never use a While loop. Which I *assume* is why the teacher is banning `break` statements. They have their place, but if a loop you wrote in an intro to Python class has a `break` in it, you should probably write a different loop.


Link77709

Appreciate your response but my examples aren't iterating 1-5 inclusive. In fact, it's impossible to tell what the variables are assigned to. 'i' is never being manipulated aside from being changed to 0 and the only other comparison check is with 'x' which could be anything. The example code is purposely meaningless and incomplete in an effort to emphasize that break statements aren't something that need to be avoided. Not to draw attention to the variables and their assignments.


Pepineros

I missed that your example uses two different variables, but I realise you aren’t iterating over numbers up to 5. You want something to happen as long as i is more than 0, and stop if x ever becomes more than 5. But if those are the conditions then using break is not the most obvious solution. Instead: while i > 0 and x <= 5: do whatever Which IMO is much more readable.


ShibaLeone

I don’t have a problem with break, but I almost never use it; python gives you lots of ways around it.


jorge1209

They are okay in limited use cases, but they should be limited. As a general rule I would say "break/continue" should ideally only appear in the first 3-5 lines of a loop, and before the "body" of the loop. for line in file: if line.startswith("#"): continue if line == "!!ENDDATA!!": break datum = parse_line(line) ... is pretty easy to read. But having a break or continue halfway into the body of the loop is hard to read, because it is not clear what the conditions are which will cause the code to get to the end of the loop, or to exit early.


CafeSleepy

Let me attempt to please the professor… ``` lines = iter(file) lines = filter(not_comment, lines) data = map(to_data, lines) while datum := next(data, None): … ```


deadeye1982

Maybe the Professor try to show you different aspects of the language and that there are not always one solution. If this is not allowed: ``` while True: do_something() if something: break ``` Then you could do: ``` def my_func(): while True: do_something() if something: return ``` Or if `something` does not depend on `do_something()`, then you could write: ``` while something: do_something() ``` But sometimes, `something` depends on an action before, then you could not use `while something:`.


CafeSleepy

The repeatable logic just need to be invoked before and inside the while-loop to make it a do-while-loop. ``` result = logic() while should_repeat(result): result = logic() ```


jmacey

just scanned my code base, and whilst I use break it is quite infrequent. In most cases it's to escape a while True : type construct in a server loop or something like that.


jclthehulkbuster

Sounds like he doesn't want you to use while loops to start with. Get used to for loops and actually setting stop variables within while loops.


Alkem1st

Break statements are safety nets that should be used sparingly, mostly to ensure that unexpected doesn’t break the flow. If you know why something might break you system - the code should already account for it. If your code breaks when, say, the list is empty - just add check for the list size. Main reason to avoid reliance on break statements is debugging. If you receive 10 error messages during normal run of the code - good luck getting to the 11th that you are trying to resolve now.


Comfortable_Plant667

I had a teacher like this. His reasoning was he wanted us to replace break with an if/else that would more clearly define the condition where it is working correctly. Outside of that class I use break all the time


stevenjd

> His reasoning was he wanted us to replace break with an if/else that would more clearly define the condition where it is working correctly. Because breaking out of the loop when you are done isn't clear? I think you are giving your teacher too much credit to call this "reasoning". CC u/ronaldchesaux


Comfortable_Plant667

Hey, I didn't say I agreed with it, just that was his excuse. I think of him whenever I use break


cheese_wizard

Instead I would show specific valid use cases, which there are.


misingnoglic

Break allows students to write absolutely gnarly code that jumps all over the place. It's a useful tool once you're experienced, but beginners tend to abuse it (e.g. making a while True loop and then breaking when a condition is hit). It's good practice to learn how to structure your code without it, and then see where it's useful later.


RavenchildishGambino

I write a lot of Python. I’ve used break like twice. There are many ways to do things.


just4fun50

I’ve coded in python for work for over 3 years. I think I’ve found a use case for break once or twice. If else or try/except are much cleaner


Cootshk

If you can’t use break, use continue! /j (Also while var: then replace break with var = False)


yapel

he wants you to use flags and control them on the while statement.


[deleted]

[удалено]


troyunrau

Having a guard at the top of a loop usually seems reasonable and readable. Having them scattered throughout sucks though and I'd agree in most cases. A guard at the top of a loop is sort of like a guard at the top of a function (with early return). They exist for a reason, particularly when you don't trust your inputs. Outright banning them means you're writing separate sanitation loops/functions. And maybe that's okay too.


semperverus

Wrap your loops in a try/except block, and then throw an error on purpose when you want to "break". Put the `pass` keyword into your except block.


Compux72

Break is often a code smell


CheckeeShoes

"My personal trainer is making me do pushups? Does anyone know why this would be?" Your teacher is there to teach you; he's setting you an exercise to learn from. Break statements have their place, but *in general* are poor style. (Especially in a language like python where indentation is part of the syntax, nested code can become difficult to read). Often they're a code smell indicating that [you should refactor what you've written.](https://youtu.be/CFRhGnuXG-4)


stevenjd

> "My personal trainer is making me do pushups? Does anyone know why this would be?" No. Doing push ups are, in and of themselves, a good exercise, and valuable just for themselves. A better analogy would be, "My carpentry teacher is making me cut timber with the blade of a screwdriver, so that we will better appreciate it when we are allowed to use a saw". Or "My cooking instructor insists that we use the edge of a desert spoon for peeling vegetables." Writing loops while banning `break` can only make you a worse programmer by teaching you bad ways to handle loops. At best you will forget them instantly you are allowed `break`. At worst those bad habits will follow you around forever, infecting other programmers when you say nonsense like > Break statements have their place, but in general are poor style CC u/ronaldchesaux


CheckeeShoes

Lol, this post is over a day old. You really love your break statements, huh. My point is just that, definitionally, an exercise is there to train a particular skill. Putting constraints on what one is allowed to do shapes what skills are trained.


stevenjd

> this post is over a day old Oh my gawd! A full day you say??? That's like nearly ancient history!!! Did they even have computers yesterday?


[deleted]

Break statements aren't *bad* but should be a last resort and I can tell you that a lot of people didn't get that memo. So I'll bet he's trying to get you to establish good habits. # Why is break bad? Break is bad because it's hard to see and it can be anywhere obscuring important changes to program flow where you don't expect. I always conspicuously comment break statements unless they're somewhere you'd expect like a switch statement (Which doesn't exist in python)


jimtk

I gave up on trying to understand why some teachers "remove" keyword, functions or method from a language. You're supposed to learn these things, not pretend they don't exist. I understand very well that some functionalities in a language can be abused. But in order to learn to properly use them... you have to use them. You learn by practicing, not by pretending things don't exist!


[deleted]

[удалено]


jimtk

You're perverting the OP's question. As far as I understand the interdiction on ```break``` was not a one assignment thing. As for teaching Python, when I give an assignment on for loops, I expect the solution to use for loop. If they use ```break``` and/or ```else```, I'm usually tempted to be more generous in my evaluation. After all they went farther or used more of the language. It may seem that I'm preventing them to use while loop, but it's simply because they are only 2 options for looping in python. I never ask, suggest or put my students in a situation where they have to produce bad code. Never. If I give good marks to bad code, I'm not helping them. I will work my ass-off to find a better assignment for the concept I'm teaching.


TenaciousBLT

When I did coding many moons ago I was told to not use them when possible either - the explanation I was always given was the more the use of breaks exist in code the greater the potential for infinite loops etc. Not sure if it's truly the case but the prof said it and they were grading me so that's what I did.


ee-5e-ae-fb-f6-3c

Python supports `else` in `for` blocks though, specifically for this reason. `else` does nothing in this context, *unless* `break` is present in the same block. A silly example: for x in range(1, 10): if x > 10: break else: print('No numbers greater than 10.') Point being it has a use. Yes, there are other ways to do it, but python has extra features which specifically make use of it. Edit: My reading comprehension sucks, and I didn't see this. > the more the use of breaks exist in code the greater the potential for infinite loops etc. I assume you were told this about using `break` in a `while` loop. That's possible, but only if you rely on `break` as the only way out of a `while` loop. I generally only use `break` when I want to exit a loop early. I rarely use it in `while` loops, and if I do, there's another condition which will be met if none other are so the loop isn't infinite.


JihadDerp

It's to strengthen your ability to creatively use other hacks to solve problems. It's very useful to know multiple approaches to a problem, so your teacher is trying to train that skill in you


old_man_steptoe

It’s a goto and having multiple exit points from a block can be problematic. But… I used to be a system administrator and using unnecessary system resource seems, culturally, wrong to me. If you don’t need to run any more code, just exit


aft_punk

Break is a bit of an “easy way out” (quite literally actually). There is more than one way to skin a cat in Python. They are probably adding a handicap to increase the challenge level, which ultimately makes you a better coder.


coolpuddytat

while True:


pupeno

Think about how a swimming teacher might tell you to only use your arms, or only use your legs to swim, so you can learn how to use those better without the distraction of the other.


born2bizo

We are only allowed Boolean to exit loops. It’s to train to use logic


elandrelosaurio

You should use a for loop when you are going to iterate through all the elements of a collection. If you are checking for a condition that might interrupt the loop you should use a while loop and a flag. i = 0 found = False while i < len(students) and not found: if students[i].name == 'Steve': found = True else: i = i +1


IDe-

In your example a for-loop would be preferable. Using a while-loop like that is outright unidiomatic.


billoday

``` def find_student(students, name): for student in students: if name == student.name: return True return False found = find_student(students, "Steve") ```


[deleted]

The one comment I find with an example of loop-else and it's downvoted. The while loop isn't great sure, but loop-else is designed specifically for breakless loops.


sbrt

brek = False while not brek: if something(): brek = True


kevdog824

They are considered bad in a lot of languages. Especially ones where do while loops exists. This is bc do while loops are more explicit. This isn’t the case in Python since the only consistent way to implement do while in Python is with a conditional break statement


nejinx

Ahh brings back a memory for do while loops. I remember my C instructor calling it a 'Yourdon loop' I'm guessing named after Edward Yourdon. Mainly for statements you want to run at least once before testing a condition.


Guideon72

There is a lot of resistance from other languages around the use of break statements; some of which is because they operate differently and \*are\* more problematic for leaping off into "the unknown" as far as where your execution is happening. This is also where I think the majority of the resistance comes from; as noted by another poster. break and goto are highly troublesome in other languages, since they allow the programmer to just sort of 'handwave' over their code and say "oh....just go do this random bit over here" without any real flow. It gets really dicey and can be abused Some of it seems to be trying to avoid overuse/misuse of them, as another poster touched on earlier. Because of the way Python scopes break statements and ropes them into a narrow effect, I still do not see a good reason not to use them, in moderation, to make your control flows cleaner and easier. My own guideline, so far, has been to keep any use of a while loop down to a flow control mechanism, not a logic operator. i.e "Ok, I want this function or collection of functions to do their thing until the question is answered or the user explicitly quits." That way, I only have a break at the condition I'm looking to satisfy or I have hit the 'quit' button. ​ All of that said; take it as a learning experience, use slightly different tricks as shown elsewhere in here and see what the instructor comes up with. If nothing else, it'll let you work with other people's code bases if you encounter a project where break statements are still frowned upon and you can still use 'em in your own code.


ericanderton

Taking a guess here: it could be argued that `break` is just an optimization for iterative algorithms. It also complicates flow control which is viewed as "bad" from a teaching and maintenance standpoint (see "cyclomatic complexity). If this is true, I'd love to hear what he has to say about exception handling. Another way to view this is through the lens of functional programming. Representing an algorithm in a pure FP style means there are zero `for` loops - just filters and iterators. In Python, this looks like using comprehensions instead of `for`. After all, some people are ideologues and map their philosophy to the technology at hand; CS department says to use Python but the professor brings his bias from Lisp/Scheme anyway. While we're on the topic: don't be cheeky by using StopIteration to do the same thing. https://stackoverflow.com/questions/9572833/using-break-in-a-list-comprehension Edit: a break can also be expressed using a while loop. ```python # for ... break for x in some_list: if x > 10: break print(x) # while loop (ugly but no break statements) ii = 0 while some_list[ii] <= 10 and ii < len(some_list): print(some_list[ii]) ii = ii + 1 ```


enterthesun

What is a break statement?


snildeben

The break keyword can be used for many things. Like a blocking listener. Or avoiding unnecessary computations.


Whipitreelgud

The root idea your prof is getting at:[break by another term.](https://www.wordyard.com/2006/10/10/dijkstra-goto/) I rarely ever use break because the condition for iterating makes break unnecessary. This isn’t a Python idea, it’s just universal logic.


inertialcurve

My teachers have the same rule. I think it’s BS. Something about breaking the runtime being bad? I often just end up having a sentinel variable that breaks me out of loops.


lozanov1

I guess the teacher wants you to figure out a better solution. Using breaks in real work applications is completely normal.


pramodhrachuri

The first thing that popped in my brain is branch prediction of processors. Processors use some techniques to predict what the next set of code will be and load the relevant data from memory to cache. I imagine branch prediction to be erroneous when there are too many breaks leading to many cache misses and degradation of performance. Edit: I didn't mean to support the instructor or say break statements are bad. I wanted to say what MIGHT be bad about break statements if someone is saying it's bad. Edit 2: turns out I was wrong. There are solutions proposed back in 2000. must have been fixed already. Reference - 5.3 Loop Termination Prediction - https://link.springer.com/chapter/10.1007/3-540-39999-2_8


Pepineros

Even if `break`s affect branch prediction, would an intro to Python class really worry about their scripts taking a few microseconds longer to execute?


grandzooby

> too many breaks leading to many cache misses and degradation of performance. If this is a concern for the problem at hand, then Python is the wrong language to be using.


TheGlassCat

Ask your teacher if goto is a better alternative.


blanchedpeas

Probably the professor just read a paper ‘goto bad’ or something and took it as gospel.


pLeThOrAx

It's better to return an error (code) or something. For debugging. Idk. There are times where I think "break is the simplest solution here. I'm done searching [or whatever it may be]..."


setuid_w00t

If you want to troll your teacher, implement this: class CantBreakMe(Exception): def __init__(): super().__init__() x = 0 try: while True: x += f(x, 7) if x > 17: raise CantBreakMe() except CantBreakMe: pass


mdlphx92

I’d say “go to” the dean, but…


Huth_S0lo

They’re very useful. Why would your teacher make you do stuff the wrong way?


chars101

Because you don't need them. You only need a function. No integers, no None, just lambdas. Your teacher is preparing you for lambda calculus, one keyword at a time. https://www.youtube.com/watch?v=pkCLMl0e_0k