ไม่สามารถเล่นวิดีโอนี้
ขออภัยในความไม่สะดวก

Python's creator wishes this feature never existed

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 ส.ค. 2022
  • Guido van Rossum said he would have never put this into Python.
    If he had to make Python again, he would have never put for/else and while/else into the language. Why would a potentially useful feature that saves extra variables be seen as such a mistake? Find out in this video, where we see how for/else while/else work, where they came from, and why you should probably avoid them in your own professional Python code.
    ― mCoding with James Murphy (mcoding.io)
    Source code: github.com/mCodingLLC/VideosS...
    Create custom lint rules: • Python AST Parsing and...
    Guido's 2009 opinion: mail.python.org/pipermail/pyt...
    SUPPORT ME ⭐
    ---------------------------------------------------
    Patreon: / mcoding
    Paypal: www.paypal.com/donate/?hosted...
    Other donations: mcoding.io/donate
    Top patrons and donors: Jameson, Laura M, Vahnekie, Dragos C, Matt R, Casey G, Johan A, John Martin, Jason F, Mutual Information, Neel R
    BE ACTIVE IN MY COMMUNITY 😄
    ---------------------------------------------------
    Discord: / discord
    Github: github.com/mCodingLLC/
    Reddit: / mcoding
    Facebook: / james.mcoding

ความคิดเห็น • 1K

  • @jochem_m
    @jochem_m ปีที่แล้ว +487

    As a non-python web developer, I'd expect an else on a loop statement to run when the loop has had zero iterations. For example, if you were looping over a database result resource that may or may not have any entries, the for could handle the "has entries" clause, while the else would handle the "no results found" clause. A lot of templating languages use this syntax, and it can very handy!

    • @toms75
      @toms75 ปีที่แล้ว +41

      That's what I expected it would do as well. I've had a few times where I had a while loop and code I wanted to run if it didn't happen.

    • @johnny_eth
      @johnny_eth ปีที่แล้ว +9

      I agree that the else should mean that the loop body did not run.
      But the feature of running a piece of code if the loop completes is quite handy as well.
      And i do work with Python nowadays

    • @yansakovich
      @yansakovich ปีที่แล้ว +5

      I am .NET developer and thought the same. Would be nice to have this feature.

    • @SeverityOne
      @SeverityOne ปีที่แล้ว +15

      @@johnny_eth Why can't you just run a piece of code after a loop completes by simply putting it underneath that loop? Why would it have to be part of the "for" loop?

    • @wizard7314
      @wizard7314 ปีที่แล้ว

      I wish people would retire the oxymoron "web developer".

  • @NikitaKaramov
    @NikitaKaramov ปีที่แล้ว +374

    I'd never guess that this is what it does! If I would see it, I would think it's similar to the template engines, where you can add "else" to a loop, which means "loop never ran", i.e. there were no items in the iterable to begin with. Pretty useful for building a UI

    • @mr.rabbit5642
      @mr.rabbit5642 ปีที่แล้ว +19

      Yeah, that would actually be a good use case and usefull feature decreasing boilerplate for handling empty collections and I'd love it implemented in e.g. JS, in which arrays are objects, and therfore are casted do true..

    • @tjbredow
      @tjbredow ปีที่แล้ว +6

      Interestingly, that would be the behavior of a Python loop with this configuration. Since the else clause happens when a for loop completes through the iterable (reaches a raise StopIteration rather than breaking before), and empty iterable would still call that and the else statement would execute.
      EDIT: He covers this in the video, I need to stop reading comments before finishing the video. lol
      EX:
      foo = []
      for item in foo:
      print("in loop")
      else:
      print("done loop")
      In Python 3.10 expected output:
      done loop

    • @laurentverweijen9195
      @laurentverweijen9195 ปีที่แล้ว +1

      if seq:
      for x in seq:
      ...
      else:
      But that doesn't work if seq is an iterable, so I would like this idea, but it probably won't happen.

    • @mage3690
      @mage3690 ปีที่แล้ว +1

      Well, I figured out how you _can_ make the code work that way. The best way (IMHO) is this:
      if 'i' in locals(): del i
      for i in range(0):
      print("did something")
      else:
      if not 'i' in locals():
      print("did nothing")
      Checking for and deleting 'i' before the "for" loop is *probably* the best way, because unlike C, Python chooses to keep its iterators after the "for" loop has terminated. However, Python does _not_ initialize the iterator if the loop never runs, so you have to check for and delete it if it does exist, and just hope that another variable by the same name didn't exist as an important entity somewhere else in the "locals()" library. Of course, if it did, the "for" loop would overwrite it anyways if the loop did run (I think), so how much harm have you really done?

    • @insidetrip101
      @insidetrip101 ปีที่แล้ว

      That is actually how it runs. You're completely on the right track. Think about it, a for loop always checks for some condition before running again. For example:
      for item in list:
      do_something(item)
      means the computer is thinking IF there is another item in the list THEN i will preform an iteration on it. So next we can add ELSE i'll do something else. It is impossible to construct a terminating loop without the computer using some kind of conditional expression, be it a for loop or a while loop. Of course, you can have a loop that doesn't terminate, but those (while they do have some use) are generally undesired.

  • @electra_
    @electra_ ปีที่แล้ว +652

    I always thought this was a neat feature and was nice when searching through loops. Its definitely a bit unclear, would be nice to rename it, but flag variables are just so annoying (esp with nested loops)

    • @NOT_A_ROBOT
      @NOT_A_ROBOT ปีที่แล้ว +1

      fancy seeing you here lol

    • @electra_
      @electra_ ปีที่แล้ว +1

      @@NOT_A_ROBOT oh hi

    • @ian_b
      @ian_b ปีที่แล้ว +1

      GOTO

    • @jessveness
      @jessveness ปีที่แล้ว

      hey! it's that one tetris person

    • @electra_
      @electra_ ปีที่แล้ว +2

      @@jessveness hello lol
      surprised anyone knoes who i am

  • @normalmighty
    @normalmighty ปีที่แล้ว +93

    I've actually found for else to be super useful at times. The name is unintuitive, but I'd never want the functionality to go away

    • @thedopplereffect00
      @thedopplereffect00 ปีที่แล้ว +6

      Future people trying to read your code won't be happy

    • @paulie-g
      @paulie-g ปีที่แล้ว +12

      @@thedopplereffect00 They can just learn the language. There's no need to code to the lowest common denominator, that's what java and javascript are for. *Iff* this is used properly, it is more readable than the alternative.

    • @thedopplereffect00
      @thedopplereffect00 ปีที่แล้ว +3

      @@paulie-g in the real world I need to be familiar with about 4 programming language at once. I don't have time to memorize every corner case of every one of those languages. It's not efficient way to build software. Imagine a car that only needs 4 tools to build vs. 100. Which one will be more reliable and built faster?

    • @paulie-g
      @paulie-g ปีที่แล้ว +2

      @@thedopplereffect00 I write many more than that fluently. It's not hard.

    • @thedopplereffect00
      @thedopplereffect00 ปีที่แล้ว +3

      @@paulie-g you act like every programmer can be in the top 1%. No way everyone is going to memorize 20 years of C++ changes along with proficient usage of several libraries. We all have limited time.

  • @MichaelGrantPhD
    @MichaelGrantPhD ปีที่แล้ว +702

    I'm weird. I like this. I like doing this when I'm searching linearly through an iterable for the first instance of a certain condition. The else clause covers the case where the condition is never met. So yes, I like avoiding the flag variable as discussed here. The "nobreak" rename makes sense to me, and how I think of it. The suggestion to move loops like this into their own function smacks of "Clean Code" dogma that I generally push back against. I do agree that one should not do it for performance!

    • @georgplaz
      @georgplaz ปีที่แล้ว +62

      Without the rename I would vote for not using it. Python is very proud of being a language that is easy to read and "else" at the end of a loop makes no intuitive sense

    • @joseville
      @joseville ปีที่แล้ว +27

      You can also do this in one line with a generator, next, and its default argument
      E.g. to find the first odd numbers in a list nums:
      odd = next(num for num in nums if num % 2)
      throws a StopIteration if there is no odd number in nums
      odd = next((num for num in nums if num % 2), None)
      sets odd to None of there's no odd number in nums

    • @sshilovsky
      @sshilovsky ปีที่แล้ว +43

      @@georgplaz It's only unintuitive for those who don't know what it is. Although python is easy to read even for those who don't know it much, it has a list of "advanced" features that you have to be familiar with in order to understand what's going on. This is just one of them, imho a pretty useful one.

    • @SeanBracks
      @SeanBracks ปีที่แล้ว +72

      @@sshilovsky "It's only unintuitive for those who don't know what it is." If someone knows what it is, then it's a bit past being intuative or not lmao.

    • @shootingstarzzz
      @shootingstarzzz ปีที่แล้ว

      @@joseville this would only return %2 of the first number, and next doesn't have kwargs
      odd = next((num for num in nums if n%2), None)

  • @Rafale25
    @Rafale25 ปีที่แล้ว +34

    One time, i was in something where i needed a else statement on a for loop and i thought it would be crazy if it existed and i tried it and it worked !
    Was very surprised, so i'm happy that it exists

    • @shahram6869
      @shahram6869 ปีที่แล้ว +3

      Did it do what you expected it to do?

    • @Rafale25
      @Rafale25 ปีที่แล้ว +2

      @@shahram6869 Yes

    • @nydydn
      @nydydn ปีที่แล้ว

      what use case can exist for a for-else that is not the perfect use case for a while?

  • @jbaidley
    @jbaidley ปีที่แล้ว +20

    I can't say I consider while..else or for..else particularly unreadable. Once you know what they mean they're just as readable as the equally badly named try..except..else, the problem is simply one of confusing name.

    • @AthAthanasius
      @AthAthanasius ปีที่แล้ว

      In both cases the intent would have been clearer if the keyword was "finally", not "else".

  • @Azullia
    @Azullia ปีที่แล้ว +10

    for-else was something I did use in some scripts, but I've never seen while-else

  • @willmurphy8650
    @willmurphy8650 ปีที่แล้ว +88

    I've definitely used Python's for-else clause. I've found it beneficial in some use cases.

    • @sebastianjost
      @sebastianjost ปีที่แล้ว +5

      Same here. Although the name is really unintuitive.

    • @hashisgod
      @hashisgod ปีที่แล้ว

      same! but as above, it's not really an "else"!

    • @this_is_japes7409
      @this_is_japes7409 ปีที่แล้ว +5

      the definition makes sense when you think about it in terms of the else in the phrase "what else?" which usually means "what more?" you ask someone/the computer to do a bunch of things and the computer goes "what else?" and you say else: this

  • @Pabna.u
    @Pabna.u ปีที่แล้ว +36

    Hmm, I find it generally pretty convenient and clean, but it did kind of derail a coding interview I was doing when the interviewer thought I had made a mistake, so you’re probably right that the obscurity is an issue

    • @rb1471
      @rb1471 ปีที่แล้ว +3

      You should make it clear in interviews of something weird like this, much like you should put a comment where you do something weird like this so someone doesn't go "wtf?" and delete it (or indent it to match with an 'if'). It would show you know how to comment your code properly and be a big plus in an interview.

  • @joseville
    @joseville ปีที่แล้ว +7

    I don't always use the else clause of a for loop, but when I do, I always comment "else: # no-break".

  • @pranavnyavanandi9710
    @pranavnyavanandi9710 ปีที่แล้ว +10

    It is useful to think of else as being a part of the for-loop construct itself, rather than being a separate clause. Breaking from the loop explicitly, will exit both the clauses. However, if the loop terminates naturally, the else part will execute.

  • @Boehoehuahoei
    @Boehoehuahoei ปีที่แล้ว +24

    I think you have just convinced me to use while-else and for-else. I dnt know it exsisted, but now that I do it seems great. As a terrible programmer.. I would need to create a new variable and write an IF statement at the end of a for or while loop (for codes that only have to execute on exit).. this does it in one statement.
    I wil make a point of only using this from now on.

    • @austinbryan6759
      @austinbryan6759 ปีที่แล้ว

      Using less statements doesn't make you a better programmer. Using obscure unintuitive hard to read language features certainly isn't gonna help you

    • @Boehoehuahoei
      @Boehoehuahoei ปีที่แล้ว

      @@austinbryan6759 Well it's only obscure because no one knows about this handy feature. Now we do.
      And for redability, simply adding a comment:
      # following code executes on exit.
      Increases redabily by 1000%.
      Comments: Use them. :)
      Or maybe we can create a function in a different file (module), put it in a class add OOP philosophy, do an import and refuse to put comments like a Boss...

    • @Nikarus2370
      @Nikarus2370 ปีที่แล้ว

      @@Boehoehuahoei TBH, I think the only reason it's obscure, is because it simply isn't brought up in a large portion of tutorials/books. It might just be me, but the guide I learned on used them in many examples... so I just use them in many of my loops.
      As far as readability. I actually feel it makes code more readable in the case of exceptions, than just returning/indenting the return. Perhaps it's just me coming over from C, but that little extra step of structure to the code makes it easier for me to read.

  • @QwDragon
    @QwDragon ปีที่แล้ว +71

    Great explanation about labels and goto!
    But I disagree that the feature shoiuld be avoided.

  • @leroymilo
    @leroymilo ปีที่แล้ว +15

    I use these everytime I do a coding competition, it's pretty usefull to avoid losing time on making functions to call, or when they are a lot of variables that would have to be returned/passed to the function. This case is pretty specific as the readability of the code doesn't really matter, but otherwise I fully agree with what is explained in this video.

  • @EntropyPI
    @EntropyPI ปีที่แล้ว +25

    The 'nobreak' else is incredibly useful. I wish this type of feature existed in other languages and so do others I've shown when they understand and see the simplicity inherent. I came away with readability being the the largest negative. The less code you have to read and understand the better, making this a positive. The less flags code needs the better.

    • @davidwuhrer6704
      @davidwuhrer6704 ปีที่แล้ว +1

      The name is confusing. What if I want to run code in case the loop was never entered? What tells me that a break jumps to the else branch and not beyond it?
      What it does is useful though.

  • @pfcrow
    @pfcrow ปีที่แล้ว +11

    As a C programmer, I *love* this feature. I completely agree that it should be nobreak, and there should also be a yesbreak. In a C for loop, you can avoid the extra flag variable by comparing the index variable to the end value outside the loop, but that means the index variable has to be scoped larger than just the loop, and I like to declare the variable in the for statement. In C, you can do this with goto, which is ugly, but you can make it a little cleaner with macros. Just because the Python implementation is clunky doesn't mean it's a bad feature, it just means it's a bad implementation.

    • @syockit
      @syockit ปีที่แล้ว +3

      Goto is cleaner regardless. What macros would you ever need?

    • @pfcrow
      @pfcrow ปีที่แล้ว

      @@syockit Whether using macros or not, the trick with gotos in C that I really like is that this is legal: if (0) target: { ... }
      With that, you can have a goto target that is only reachable with the goto, which eliminates some of the traditional mess associated with gotos. It also makes it doubly obvious to anyone not expecting a goto that something odd is going on.

  • @rancidbeef582
    @rancidbeef582 ปีที่แล้ว +12

    I actually think it's easier to understand than having a flag variable. I've always hated having a flag to know if a loop terminated early. Or the if (i == end) trick you can use in C. Now it might have made more sense if it had been called "finally" instead of "else". But the way "finally" is used in try blocks always execute unlike the "else" in try blocks. So maybe it wasn't called "finally" for consistency. Also, I don't like putting returns in functions except at the end, unless it's when checking argument bounds and conditions at the top to bail out without having a bunch of nested if() else statements..

  • @oskaraltman
    @oskaraltman ปีที่แล้ว

    it makes a lot more sense if you think of the c syntax
    for (int i = 0; i < n; i++) {}
    because then there is a condition in the for loop, which there isn't in the for x in range syntax

  • @stevie1da_
    @stevie1da_ ปีที่แล้ว +10

    I love the else clause on for loops. Its a feature I always miss when I need it in another programming language

  • @nnirr1
    @nnirr1 ปีที่แล้ว +64

    This feature is one of those things that were unintuitive for me at first, but over time grew on me and now i actually find them readable.
    Do I find myself using it too much? Definitely not. But when i do, it seems readable to me. I don't think of it in terms of "was there a break or not?", instead i think of it in terms of "was the underlying condition determined to be False?", which makes the word "else" intuitive to me.

  • @maxaafbackname5562
    @maxaafbackname5562 ปีที่แล้ว +14

    When I saw a construct like that, I should assume that the else clause was run (only) when the loop condition was never true.
    (For that occurence of the loop.)
    But yeah, Python has more constructs that don't fit in my head....

    • @Nikarus2370
      @Nikarus2370 ปีที่แล้ว

      Think of it as the Else to the If statement of the conditional for the While. It'll run if that conditional is false.

  • @lucbloom
    @lucbloom ปีที่แล้ว

    Thanks for showing me this neat feature and pointing out some good use cases. Will use it from now on.

  • @EvanOfTheDarkness
    @EvanOfTheDarkness ปีที่แล้ว +16

    The else in while-else is usually explained as the "else" branch for the condition of the while loop. And since for loops can be rewritten as while loops, it works there too. "The else is executed when the loop condition becomes false" - if you think like that it's easy to remember.
    And while I almost never use this in python (because while loops in python should be avoided anyway for being slow), ironically it'd be really useful in C/C++/C#/Java etc., where I'd lost count of the times I've used the while (condition) { ... } if (same condition) { } pattern.

    • @screwaccountnames
      @screwaccountnames ปีที่แล้ว +1

      I got to know it looking for a way to avoid having to use a flag variable. For me, the interpretation was always that the else belonged to the if statement inside the loop (if reason_to_stop: break). The indentation levels don‘t match, but in my head that‘s because the else counts for all iterations of the if statement at once.
      I acknowledge that the “actual“ meaning is something else, but this approach actually makes more sense to me.

  • @KiaAzad
    @KiaAzad ปีที่แล้ว +27

    I do often use that else, and I love it. If it allows me to avoid one more variable to keep track of, or one less lines of code, I'm going for it.

    • @yugix_1
      @yugix_1 ปีที่แล้ว +1

      if allowsMeToAvoidOneMoreVariable == true or oneLessLineOfCode == true:
      print("I'm going for it")
      else:
      print("I'm not using it")

    • @KiaAzad
      @KiaAzad ปีที่แล้ว

      @@yugix_1 not usingCamelCase is less_readable_than_snake_case

  • @bereck7735
    @bereck7735 ปีที่แล้ว +4

    i didnt even know if you can use elsr with a while loop, whacky

  • @ytechnology
    @ytechnology ปีที่แล้ว

    Thanks for this. For all the talk surrounding design patterns (and anti-patterns), idioms -- code level patterns -- are just as important for building readable and reliable programs. I never knew about this else for loops, and have no plans to ever use it.

  • @andrewdunbar828
    @andrewdunbar828 ปีที่แล้ว +7

    This is something I've often wanted in many languages over many years but I didn't know Python had it, I wouldn't call it "else", and I had no idea this is what it was going to be until you described it.

    • @BarryRowlingsonBaz
      @BarryRowlingsonBaz ปีที่แล้ว +2

      I might have used "then:" instead of "else:" - "do the "for/while" loop, *then* do this (unless you broke out)"

    • @JoQeZzZ
      @JoQeZzZ ปีที่แล้ว

      @@BarryRowlingsonBaz I'd have to agree, " then" is definitely a better keyword than "else", because IMO "else" only works in while(evaluation) loops, where it's sort of short hand for:
      do
      if (evaluation==True)
      do one thing;
      else
      do another thing;
      break;
      end do
      But in a "for a in list:" context "else" seems really off, after the list is fully evaluated the loop should end, it doesn't feel like there should be an "else" clause.
      That being said, this is incredibly incredibly useful because it comes up pretty often, e.g. in cases where you're searching for the first occurrence in a list and don't know if it's even in there. I think the following example is much more legible than any other way:
      # insert in sorted list
      for pos, num in enumerate(sorted_list):
      if to_insert < num:
      sorted_list.insert(pos, to_insert)
      break
      else:
      sorted_list.append(to_insert)

  • @doctortroels
    @doctortroels ปีที่แล้ว +202

    It's one of the python features I miss most in other languages. "But you can just have a named helper function" is great pavement on the road to unreadable code.

    • @RAN-os5gz
      @RAN-os5gz ปีที่แล้ว +14

      Doesn't that depend of what is in the "else"? Production code will have a colossal amount of code inside the "else", I'd much rather see a properly named function that basically describes itself instead of the "else".

    • @Plajerity
      @Plajerity ปีที่แล้ว +10

      @@RAN-os5gz I don't get why production code would have "a colossal amount of code inside the else". My last usage was to just notify, that collected enough data, some cleanup and exit.
      For sure it depends on use case. You should use a tool that makes your code more readable :)

    • @kilianvounckx9904
      @kilianvounckx9904 ปีที่แล้ว

      Zig has the while else and for else as well. They can even be used to turn loops in expressions instead of statements. I find it useful in some cases

    • @georgplaz
      @georgplaz ปีที่แล้ว +13

      why unreadable code? if the function has a good name, I find it often makes code easier to read to put functionality in separate functions (unless the function then needs like 10 parameters)

    • @Plajerity
      @Plajerity ปีที่แล้ว +7

      @@georgplaz I found it easier to read script-like code than reading a lot of 2-4 line nested functions.

  • @b_kind
    @b_kind ปีที่แล้ว +43

    There are loops you don't want in a separate function for the complexity they carry is too important to be accidentally missed. The else feature is quite nice, it just needs that urgent rename.

    • @AllenLantz
      @AllenLantz ปีที่แล้ว

      If you have a loop longer than 20 something lines, you're doing it wrong entirely

    • @MindlessTurtle
      @MindlessTurtle ปีที่แล้ว +4

      @@AllenLantz - obviously, it depends on what you're processing; sometimes you need to loop on heavy work that may or may not need a break.

    • @AllenLantz
      @AllenLantz ปีที่แล้ว

      @@MindlessTurtle no, break it down into functions if it's that long

    • @MindlessTurtle
      @MindlessTurtle ปีที่แล้ว +5

      @@AllenLantz - I don't know, sometimes I'd rather have a long loop than a dozen functions with tons of parameters. Really depends on how convoluted your logic can be.

    • @AllenLantz
      @AllenLantz ปีที่แล้ว

      @@MindlessTurtle that's unreadable and hard to maintain in almost all cases

  • @lachlanstanding7386
    @lachlanstanding7386 ปีที่แล้ว

    these videos are so interesting and well explained and your jokes are just *chef's kiss*

  • @TinyDeskEngineer
    @TinyDeskEngineer ปีที่แล้ว +2

    More languages need this kind of thing. I can't believe how many times I've needed to exit a loop but remember that it exited via a break after the function and can't just do something like return a specific value from a function. Sure, I can just create a boolean variable that's set when the loop terminates prematurely, but that's completely unnecessary.
    If I ever manage to create my own programming language, this'll be one of the features.

  • @ITR
    @ITR ปีที่แล้ว +9

    I've always wanted more languages to have this feature, but I also always forget if it executes if I break or if I _don't_ break. So I think it just shows that it should have different syntax to make it more readable.

    • @scoreunder
      @scoreunder ปีที่แล้ว

      My mental model for it is that it treats the loop as a kind of "find" operation, and the "else" executes if it didn't find the element you want (i.e. if you didn't break or return)

  • @JonnyPowell
    @JonnyPowell ปีที่แล้ว +6

    Function calls are not cheap in Python (although 3.11 does partially support inlining), so if you’re in a situation with the following constraints:
    - very limited memory
    - python version

    • @AyushGupta-wn6zd
      @AyushGupta-wn6zd ปีที่แล้ว

      wow. I hope i never use it

    • @gari5961
      @gari5961 ปีที่แล้ว

      Well thanks you sir ! Since i don't do Python my first thought was "why don't you do it recursively ?" and now i know better if some day I have to code some Python

    • @JoQeZzZ
      @JoQeZzZ ปีที่แล้ว

      Also I think functions that are only called at one place aren't always the bastions of legibility that people think they are. The for else statement is pretty useful and plenty legible. I think people are just hung up on the fact that python does a thing that no other language does and therefore that makes it illegible, but if that were the case people should also be against list comprehension, or really just the way for loops work in general (looping over a list rather than the C three argument for loop).

  • @matthewrease2376
    @matthewrease2376 ปีที่แล้ว

    Does it also run the else block if you call return from the for/while?

  • @pyes
    @pyes ปีที่แล้ว +1

    Regarding the text at 7:05, I'm confused as to what point is being made here? Is it just that you're only supposed to have the necessary code in the "try" block and have the other lines in the "else" block or is using "except Exception: pass" bad habits?

  • @kreuner11
    @kreuner11 ปีที่แล้ว +4

    I would love this in C, I always have to have an extra bool if an iteration finished successfully or no

  • @NoName-kt6ly
    @NoName-kt6ly ปีที่แล้ว +5

    Thanks for the good video. But i actually use the for else construct for the following scenario:
    for _ in range(retries):
    try:
    try_something
    except Exception as e:
    print("try_something didn't work, trying again")
    time.sleep(0.1)
    else:
    break
    else:
    print("try_something didn't work after some retries. handling this case")
    actually i was never very happy with this solution because it's not that readable but it works.
    do you find somehting wrong with this solution? if yes: do you have a better idea?

    • @LittleLily_
      @LittleLily_ ปีที่แล้ว +1

      Logic like this should definitely be put into a well named function instead of being buried in the implementation of something else imo, so I would rewrite it as:
      def retry_something(something, retries=1, delay=0.1):
      for _ in range(retries):
      try:
      return something()
      except Exception as e:
      print("something didn't work, trying again")
      time.sleep(delay)
      print("something didn't work after some retries. handling this case")
      ...

    • @MrTyty527
      @MrTyty527 ปีที่แล้ว

      you can use a package called retry

    • @NoName-kt6ly
      @NoName-kt6ly ปีที่แล้ว

      @@LittleLily_ totally agree! I just wanted to see if this is an anti pattern or if i just found the one true use case for "for ... else"
      Anyway, i just found the library tenacity which does exactly what i need with a decorator. Pretty neat.

    • @NoName-kt6ly
      @NoName-kt6ly ปีที่แล้ว

      @@MrTyty527 true, although it's not maintained anymore. So tenacity is the better choice :)

  • @HAWXLEADER
    @HAWXLEADER ปีที่แล้ว

    Thanks for the new feature!
    Will surely use it!

  • @stanstevey2785
    @stanstevey2785 ปีที่แล้ว

    Your recommendation has been discarded. I will most certainly be using this feature if I ever find a use for it.

  • @unperrier5998
    @unperrier5998 ปีที่แล้ว +190

    Quite an opinionated video.
    Since we're in the opinion realm, here's mine: I quite like the for... else precisely because it avoids using a flag variable (and only in this context)
    Everyone will agree that in the end what matters is readibility. So it's a tradeoff between 2 things:
    1) a for... else where a comment can explicit what it means
    2) a for loop in a separate function
    I personally favor the first approach for readability because I already have too many functions to look-up and one less is an improvement.

    • @skaruts
      @skaruts ปีที่แล้ว +8

      If I'm reading someone else's code, I rather see an extra flag there. You don't need another function, just about 3 extra lines of code (probably less total characters than that comment you'd trade it for), and the flag is probably named after what it's for, so it takes just about zero brain effort to unpack its meaning.
      Python is the odd one out with this kind of thing (among others), and so on top of the above, that means people who code more often in other languages, or people who ditched this practice into oblivion, will have to stop to think about wtf you're doing there; maybe even have to waste time googling it. I mean, it's not even semantically obvious what for-else or while-else is supposed to mean.

    • @unperrier5998
      @unperrier5998 ปีที่แล้ว +3

      @@skaruts sure but you ignored half of what I've written: with a comment that explains what else does (just like Muprhy did in his video).
      In any case it's a topic subject to opinionated arguments.

    • @skaruts
      @skaruts ปีที่แล้ว +1

      @@unperrier5998 I have to really wonder if YOU ignored what I wrote, because I addressed pretty much everything you said, and you're kinda sounding like you missed my points.

    • @unperrier5998
      @unperrier5998 ปีที่แล้ว +4

      @@skaruts I don't think I have. You said you like seeing a flags. And I replied that the else construct is superior when you add a comment remaining what the else cause does.
      If we follow best practice, as explained here for example th-cam.com/video/rrBJVMyD-Gs/w-d-xo.html then 3 extra lines of code is about a third of the size of the function. Personally I prefer without a flag but I also understand you prefer flags. That's why I wrote it's an opinionated topic, because it boils down to personal preferences.

    • @skaruts
      @skaruts ปีที่แล้ว +2

      @@unperrier5998 ​ and I addressed that. I'm not speaking from opinion: the 2 (not 3, actually) short lines of flag code will take less brain effort and less characters than a comment, be self explanatory, etc. mCoding actually hit the nail in the head at the 3:38 segment. 99.9% of the time the else is redundant.

  • @amaze2n
    @amaze2n ปีที่แล้ว +58

    I find for-else to be useful. I have used it in my code several times. It's only confusing if you don't bother researching what it means, and I find it makes for cleaner code.

    • @georgplaz
      @georgplaz ปีที่แล้ว +5

      if you have to lookup what it means, you know the name has been chosen really poorly

    • @dhkatz_
      @dhkatz_ ปีที่แล้ว +3

      @@georgplaz Why is that? Do you say the same for Kotlin's let, apply, etc. I had no idea when they meant but they are amazing tools of the language.

    • @twrk139
      @twrk139 ปีที่แล้ว +1

      @@dhkatz_ Because it's unintuitive, and once you read what it does, the phrasing still doesn't make any logical sense. Run and apply on the other hand do.

    • @JackDespero
      @JackDespero ปีที่แล้ว +1

      @@georgplaz What a stupid thing to say. As if you don't need to learn the language in order to use the language.

  • @MeNowDealWIthIt
    @MeNowDealWIthIt ปีที่แล้ว +2

    I haven't seen "try except else" before. Do you have a video on that, or can you make one?

  • @finlee98
    @finlee98 ปีที่แล้ว

    good stuff mCoding I was wondering whether this feature has a high impact on performance, you save me time and research!

  • @joergsonnenberger6836
    @joergsonnenberger6836 ปีที่แล้ว +3

    To be fair, this is consistent with try/except. It is quite useful to have especially for nested loops.

  • @redaceFR
    @redaceFR ปีที่แล้ว +6

    I used the functionality multiples times and I like it.
    I wasn't sure it meant what I thought it meant the first time so I looked it up to be sure and it seems I understood the intended behavior but I've had remarks from other devs about it in my code. It probably needs a rename for sure but I still find it usefull in certain situations !
    I did some coding in assembly so it wasn't too far fetch but I can see that other devs might find it confusing. Python is meant to be simple and unambiguous so I don't mind it changing it's name.
    However the problem is that you would need to add a new keyword to Python because it seems like no other keyword is better, or closer, to the meaning of the functionality than "else".
    The only thing I could think of would be using the new "case" keyword like : "case break:" and "case not break" or something ...
    That's just an idea

  • @GreyHak
    @GreyHak ปีที่แล้ว

    This is awesome! I'm totally using it. Subscribed!

  • @Tomyb15
    @Tomyb15 ปีที่แล้ว

    I learned about the for-else and other unexpected else: clauses a couple days ago reading the Cython docs. Was wondering why you hadn't made a video on the topic!

  • @rustkitty
    @rustkitty ปีที่แล้ว +7

    Having an else would be amazing, if it meant "if the condition was never True" for while-loops and "if the iterable was empty" for for-loops. This is a feature I keep wishing for in every language I use but I have never seen it in practice. I knew about the meaning we actually have in Python for a long time but I never had a good use for it. If you have a mindset that you want to use it you can find reasons, but then it goes away during the next time you refactor.

    • @emiljohansson7574
      @emiljohansson7574 ปีที่แล้ว

      just put an if statement before the loop

    • @rustkitty
      @rustkitty ปีที่แล้ว

      ​@@emiljohansson7574 That only works with stuff like array, list or dict where you already have everything in place and you can count or peak.. It won't work with generators (e.g. list comprehensions or yielding functions), and likely won't work with anything using async for either.

    • @JoQeZzZ
      @JoQeZzZ ปีที่แล้ว

      I use it all the time when I need to find the first occurrence of something in a linear list and I don't know if it's in there.
      For example, inserting a value at the correct place in an already sorted list. If it's not the biggest value insert it at the right place, if it is the biggest value insert it at the very end. Another great use of it is in crawling through XML files.

  • @curtmcd
    @curtmcd ปีที่แล้ว +30

    I also have to disagree. I used the feature many times in production code and it was not at all confusing or difficult to read -- likely because the use cases for it are so natural.

    • @kayakMike1000
      @kayakMike1000 ปีที่แล้ว +1

      U write bad python then. Har har har.

  • @neilbrideau8520
    @neilbrideau8520 ปีที่แล้ว

    Thank you for introducing me to this. I will definitely start using it.

  • @hottoniapalustris1541
    @hottoniapalustris1541 ปีที่แล้ว

    What is the font that you use in this video?

  • @swolekhine
    @swolekhine ปีที่แล้ว +4

    I knew about for-else, but not while-else. As someone who doesn't know C or C++, thanks for explaining why the keyword in question was "else" instead of something like the "nobreak" you suggested. I was always wondering about that. 🤔

    • @rossjennings4755
      @rossjennings4755 ปีที่แล้ว +1

      It kind of makes sense to me given the context of try/except/else. Just like the "else" clause of a "try" block, which runs if the "try" exits without producing an exception, the "else" clause of a loop runs if the loop exits without breaking. It's not something I've ever felt the need to use, though.

  • @nickwood21
    @nickwood21 ปีที่แล้ว +32

    Hey James, love your work! You mentioned that "for, else" might make a difference inside of a "hot loop". I've never heard this term before. What's a hot loop?

    • @NicolasChanCSY
      @NicolasChanCSY ปีที่แล้ว +36

      Imagine your code has a heat map, where lines of code are hotter if they are executed more frequently, and not so hot if otherwise.
      A hot loop is basically a loop that is iterated many times, and thus it is morely likely to affect your performance, because you are effectively executing one part of the code many times, and any small differences can add up to make a big difference.
      James was referring that the flag variable assignment may slow things down in a hot loop, because that's at least one more assignment step to do than the for-else counterpart.

    • @MechMK1
      @MechMK1 ปีที่แล้ว +5

      Basically, a loop that iterates a lot, really quickly. Imagine iterating through each pixel of an image, then the innermost loop is a "hot loop"

    • @nickwood21
      @nickwood21 ปีที่แล้ว +3

      @@NicolasChanCSY Thanks for the info!

  • @vresod
    @vresod ปีที่แล้ว

    How is this different than just running the code in the same scope as the original while/for statement? For try/except/else too, I don't see the differences

  • @343N
    @343N ปีที่แล้ว +2

    saw the thumbnail, thought it was a joke.

  • @guiorgy
    @guiorgy ปีที่แล้ว +28

    Personally, I think the feature itself is fine, having more options and ways to express intent is nev-rarelly bad, however, the keyword is just straight up confusing, "else"? WTF?! I'd have gone with "then" or "nobreak" if it was my choice

    • @white_145
      @white_145 ปีที่แล้ว +1

      as far as I understand, the while loop stops if its condition is not met, and by analogy with if, the code continues in else. But if you stop it with break, the condition is still (with a few exceptions) true, so else is not executed. and it's stupid to come up with a separate keyword for for loop

  • @calebmoore1582
    @calebmoore1582 ปีที่แล้ว +8

    Flag variables isn’t a performance pitfall, it’s a correctness pitfall.
    Essentially, when you have a mutable flag variable, it’s not clear where it is set, how many times it is set and it can be easily omitted in one path without noticing.
    Else is explicitly saying one thing, that the loop terminated because the loop condition evaluated to false. If it’s not the first time you’ve seen it, it’s far more readable.
    In fact, it’s my favourite feature of Python. I use Rust these days and I think it would be a perfect addition, since it would allow bounded loops to evaluate to a value.

  • @jonathandawson3091
    @jonathandawson3091 ปีที่แล้ว +2

    I find these very useful and use them often.
    I find it much cleaner than using an unnecessary variable, and when you don't want to pull a small for loop in a function.

  • @anguswett
    @anguswett ปีที่แล้ว

    What font do you use?

  • @mynameis9817
    @mynameis9817 ปีที่แล้ว +33

    Awesome Explanation.
    But for me, this feature is awesome because this help me to save a lot of time.
    For me this feature should not be avoided.

    • @brdrnda3805
      @brdrnda3805 ปีที่แล้ว

      A lot of time? Isn't that a little exaggerated?

    • @mynameis9817
      @mynameis9817 ปีที่แล้ว

      @@brdrnda3805 nope, it depends of what project i'm working on. but most of the time it helps me save literally ton of time.

  • @OfficialMGMusic
    @OfficialMGMusic ปีที่แล้ว +11

    I agree with all the upvoted majority of comments here: for ... else is in my opinion quite readable and I really like using it. It just saves much time writing and looks much cleaner than the boolean. Most of the time I also use it to search through an iterable, in which case the "else" reads naturally as "not found".

    • @dhkatz_
      @dhkatz_ ปีที่แล้ว

      Yeah I can understand not using while ... else but I think for ... else is very readable when you're specifically searching in loops and you **don't** want to break it out (very funny) into another function.

  • @dannygjk
    @dannygjk ปีที่แล้ว

    What does 'for x in y' mean? Is it a set operation?

  • @robinkuster1127
    @robinkuster1127 ปีที่แล้ว +2

    Regarding while loops being rare: It's because in python you would iterate through a list with for x in list: where other languages would do stuff like while iterator.next(): so one of the few use cases where other languages make good use of a while loop is also covered by for loops.

  • @cH3rtzb3rg
    @cH3rtzb3rg ปีที่แล้ว +3

    I barely code in Python, but coming from C/C++ I never think of for/while loops as goto-constructs. If at all, I imagine how they would translate to assembler code.

    • @sebastiangudino9377
      @sebastiangudino9377 ปีที่แล้ว +1

      Don't they just do a jump (So, a go-to) in ASM as well?

    • @cH3rtzb3rg
      @cH3rtzb3rg ปีที่แล้ว

      @@sebastiangudino9377 Sure, an assembler jump could be expressed as a C/C++ goto, but I skip the step of the goto-construct when imagining how a loop will translate to assembler.

  • @matheusaugustodasilvasanto3171
    @matheusaugustodasilvasanto3171 ปีที่แล้ว +61

    try...except...ELSE? Okay, time to search documentation

    • @eta3323
      @eta3323 ปีที่แล้ว +14

      Time to learn about it... _finally_.

    • @guiorgy
      @guiorgy ปีที่แล้ว +1

      Just did, and, from on top of my head, I don't see much of a benefit to having it besides for putting the "except" block closer to the code that threw it 🤔

    • @michael_p
      @michael_p ปีที่แล้ว +5

      ​@@guiorgy The benefit of the else clause is, that the try clause can only contain the line of code where an exception is expected. Other code that should be run if no exception is found can be placed in the else clause, therefore, no other errors/exceptions would be catched accidentally.

    • @b_kind
      @b_kind ปีที่แล้ว +2

      It's quite useful.
      Try stuff()
      except: it didn't work*
      else: it worked*
      finally: always runs, good for cleanup
      *Assuming you used/caught the relevant exception(s) properly

  • @johannes-euquerofalaralema4374
    @johannes-euquerofalaralema4374 ปีที่แล้ว +1

    Thanks for the explanation! That was so confusing for me that I was scared of using "else" in while / for loops when I started learning python. I only used "if" and "elif". hahaha

  • @5ucur
    @5ucur ปีที่แล้ว

    Your voice reminds me so much of jan Misali (Conlang Critic) that I was confused when I just opened the video :D The video is interesting, here's a sub :D

    • @mCoding
      @mCoding  ปีที่แล้ว

      Thanks! And I enjoy jan's videos as well!

  • @mage1over137
    @mage1over137 ปีที่แล้ว +4

    I always liked for/else. I use it quite a bit, I always thought it was pretty intuitive. But like a lot of python less used idioms, it has a time and place and knowing when that is, separates the general practitioners and from the experts. Don't create a linter rule, this is why we have code reviews.

  • @lucky-segfault4219
    @lucky-segfault4219 ปีที่แล้ว +3

    Seems like a weird behavior. It would make more sense if the else: clause was invoked if the while or for loop exited on the first check. Like either loop through this list, but if the list is empty, do the else clause.

    • @lucky-segfault4219
      @lucky-segfault4219 ปีที่แล้ว +1

      Or just don't have it. It's behavior is too obscure for pythons readability gosls

  • @stavros222
    @stavros222 ปีที่แล้ว

    Else on loops? What is this used for? The commands on the else will run anyways

  • @kiraleskirales
    @kiraleskirales ปีที่แล้ว +1

    Yesterday I needed a check over an iterable inside of a while True loop. In case the check failed, I wanted to continue the while loop, but I could not use continue in a for loop for the iterable. There having the else statement would have allowed me to break the while loop in case that all check were made and continue otherwise. Instead of adding a boolean, which I find not very elegant, I replaced the for loop with a any(check in iterable) so that continue works in the while loop. Luckily enough, elegant solutions always exists if you think about it.

  • @augusto256
    @augusto256 ปีที่แล้ว +11

    Except/try/else is actually very useful because it let's you control the errors that could affect the execution of some critical parts of the code, even if the exception is handled.

    • @georgplaz
      @georgplaz ปีที่แล้ว +2

      this video is not about try/except/else. in this case, the else makes intuitive sense

    • @incremental_failure
      @incremental_failure ปีที่แล้ว +1

      He literally says in the video that try-except-else is very useful.

  • @user-hb8nl3ct1g
    @user-hb8nl3ct1g ปีที่แล้ว +7

    I've actually used for-else a lot in my final school IT state exam (ЕГЭ, your score greatly helps to enter a university) when I had to find a value of a constant that would make an equation true for any variable. It looked like a double for-loop with the inner one having an else statement that would tell me that the current value fits. I thought this was a really cool feature.

    • @georgegerasev8874
      @georgegerasev8874 ปีที่แล้ว

      That's a miracle, that this answer was accepted.

    • @zecuse
      @zecuse ปีที่แล้ว

      ... So something like:
      for x in constants:
      for eq in equations:
      if not eq(x):
      break
      else:
      Print(x)
      break

    • @user-hb8nl3ct1g
      @user-hb8nl3ct1g ปีที่แล้ว +1

      @@zecuse something like that. The outer loop had values of the constant, the inner had xs in a certain range that I wanted to check. If all x values fit, the constant was considered suitable.

    • @user-hb8nl3ct1g
      @user-hb8nl3ct1g ปีที่แล้ว

      @@georgegerasev8874 it executed in less than a second and was simple to type out. It's not like your code is reviewed there, you only have to get the answer right.

  • @test-rj2vl
    @test-rj2vl ปีที่แล้ว

    Thanks! Didn't know this before. Gonna use this at work now....

  • @lLenn2
    @lLenn2 ปีที่แล้ว

    I'm going to start using that. So brilliant!

  • @danielrhouck
    @danielrhouck ปีที่แล้ว +13

    I regularly program in C++, and I’m fluent in C as well. I know how to implement the various loop types with gotos, and I have heard of the for…else and while…else loops.
    And *even given all that*, I find it unintuitive and if I decided I needed it, I expect I’d have to look up exactly what it did. Maybe I’ll remember after this video, but I haven’t before.

    • @yaroslavpanych2067
      @yaroslavpanych2067 ปีที่แล้ว

      You for about while-switch loop shenanigans :D

    • @danielrhouck
      @danielrhouck ปีที่แล้ว

      @@yaroslavpanych2067 Duff and his stupid Device are not worth the headache unless you need every cycle and even then the compiler’s probably better at optimizing it than you are.

  • @gJonii
    @gJonii ปีที่แล้ว +3

    I really enjoy for...else. The naming is a bit confusing tho. If I had full control to modify Python, I think I'd rework the whole continue/break/else so for-loops always return a value. That way, I'd change "break" to "return" and "else" would make sense since you hit that if you haven't returned anything else.
    Old notation without assignment would be a shorthand for
    "_ = for x in y: ..."

    • @zokalyx
      @zokalyx ปีที่แล้ว

      that would be cool. one issue is that return means returning from the function and not the loop (in all languages I know), so maybe another keyword would be better

    • @gJonii
      @gJonii ปีที่แล้ว

      Thinking this more, another idea on how to do it would be to have this returning loop be "from".
      x = from x in y:
      if x == 2:
      return True
      else:
      return False

    • @gJonii
      @gJonii ปีที่แล้ว

      @@zokalyx You could just treat it the same as function def, its own namespace etc. Like, if you define a function inside a function, you can't exit from parent function from inside the child function

  • @XCanG
    @XCanG ปีที่แล้ว +1

    In an early ages of Python coding I use it because of misunderstanding. As example I have cleanup after for loop, I expect that "for ... in ...: code() else cleanup()" - will call cleanup when iterable have at least 1 element and there is no errors or breaks.
    Honestly if they change it into this behavior this would be better, because if iterable is iterator, you can't get it's length easily, so this would help to just use for-else without needing adding bools and checks.

  • @insidetrip101
    @insidetrip101 ปีที่แล้ว +1

    When I learned about else in loops, it made sense because in both a for and else loop there is an implicit check, or "if" statement. In fact, many languages (javascript, php, C, C++, )off the top of my head, all have the formulation of if (i=0;i

    • @davidwuhrer6704
      @davidwuhrer6704 ปีที่แล้ว +1

      If you think of the elements being iterated over as inherently parallel, you wouldn't think of the loop as something with a counter and more in terms of a vector multiplication. (SIMD in assembly.)
      The idea that there is a check after every element is no longer intuitive then. In compiled languages the compiler would remove it if possible by unrolling the loop.
      Functional languages use things like filter, map, and reduce to iterate over lists or list-equivalent things, the check is implicit in that an empty list doesn't need to recurse further. An "else" would be unintuitive because either there is no "if" or if there is, it is in a different scope and does something already.
      So the "else" after the loop really only makes sense if you grew up with C or Fortran, and neither of those has that feature themselves:
      If you think of code as constructive proof of a mapping between the input and the output, rather than a serial sequence of virtual steps, it stops making sense even then.

  • @qexat
    @qexat ปีที่แล้ว +7

    When I first discovered for/else syntax, I thought that the else block was executed if the for loop has not iterated at least once. I was surprised and confused when I discovered its actual meaning

    • @tokeivo
      @tokeivo ปีที่แล้ว

      Django (and Jinja, I think) does exactly this. for...else means "for each...but if empty, then instead..."

  • @theHaPK
    @theHaPK ปีที่แล้ว +8

    I love that feature and use it whenever I can. The use of "else" keyword I assume to reduce number of keywords used (which is always a consideration when designing a language), but once you know what it is and how it works, it allows saving some hustle here and there. Except for references to dated Guido's posts I see no reason not to use this little syntax sugar!

    • @austinbryan6759
      @austinbryan6759 ปีที่แล้ว

      They could've used contextual keywords, where it's only a keyword if you use it in a unique context that you wouldn't use an identitifier. C# has like 100 or 200 keywords with contextuals without breaking any code

    • @theHaPK
      @theHaPK ปีที่แล้ว

      ​@@austinbryan6759 Building a context aware parser is an order of magnitude harder task than a context free parser and benefits rarely outweight the increase in complexity. Also, context aware grammar will make it much harder for text editors to implement proper syntax highlight as most of them do not do real parsing and instead use simple regex matches (or even just highlight all words from keywords list as keywords).

  • @deatho0ne587
    @deatho0ne587 ปีที่แล้ว

    Unless I am confussed, since I am not that decent with Python. Could not you just
    if random_error():
    print("handle error...")
    return
    ... // after the while loop
    print("done!")
    return // not sure if this is even needed

  • @humanperson8418
    @humanperson8418 ปีที่แล้ว

    Thanks for teaching me a new python feature to use.

  • @alerighi
    @alerighi ปีที่แล้ว +6

    I always liked the for ... else of python, and I miss it when I program in C: you have to either introduce a flag variable (that adds extra clutter of the code), check the condition again after the loop is done (which means you cannot declare the iteration variable directly in the loop as you can do from C99), or use a goto instead of a break to exit the loop. In either situation having an else for the for would be useful.
    Also it's not even complicated what it means: else refers to the iteration condition, when it's false the else branch is executed, as it would do in an if. If you exit with a break, the condition never evaluates to false and thus the else branch is not executed. If you think in this way it is very obvious.

    • @bloodgain
      @bloodgain ปีที่แล้ว +1

      @@squishy-tomato #define nobreak else
      😁😁

    • @shmubob
      @shmubob ปีที่แล้ว

      I also know the pain. It was the day I had nested three loops and had to check which of those I had hit break in that I finally gave in and used goto's instead of an army of flag variables.

  • @lexer_
    @lexer_ ปีที่แล้ว +3

    I've always liked the loop else clause. You rarely need it but if you do its super satisfying to use. Another keyword might have been better but lots of keywords are much worse. It's specifically useful if the break case does not require any additional behavior but only the no-break case does. You can always solve this with a function of course but there are real cases in which a function is much more messy and makes a generally simple algorithm much less readable by interrupting the code flow.
    I really dislike this ideological daemonization of language features that can be abused. Especially python is a perfect example of a language that allows you to do all kinds of horrendous things but nonetheless you almost never find any of this anywhere in actual code.
    Use your language features responsibly and be aware of its dangers.
    And in case you say its only this way because of linter discipline etc. I present you ruby in which even the biggest and most popular frameworks have adopted all the worst practices you could also do in python but for some reason nobody does.
    It's not a question of blanket bans on language features but because of the way python is taught.
    Teaching features along side with their dangers is all that is needed.

    • @paulie-g
      @paulie-g ปีที่แล้ว

      I wouldn't call them 'dangers' as they don't cause incorrect execution. Python has a strong culture of writing clear, nearly self-documenting code, and is usually taught this way, so you see better results. It's important to teach the principle, and demonstrate it with code in popular projects. Real programmers (not monkeys and hacks) will figure out on their own how to apply the principle, so dogma is unnecessary. I'm still not a fan of widespread hidden-code or hidden-control-flow usage, eg decorators, unless they're absolutely necessary. I learned Python one day long ago because I needed to write something on top of Twisted (a monitor for a master-(n)slaves db system). It took me a couple hours to run through the syntax, then I read Twisted's reactor code to make sure it was using epoll properly, a few protocol implementations, and understood *everything*. The readability is what sold me on the language (I had been prejudiced against significant whitespace beforehand), and I dare say that's true for a lot of others. I had a fully working bespoke async monitoring system with web interface ready in 2 days, from knowing none of the language or a complex, fully-featured framework in Twisted to feature-complete and stable. Clever programmers in perl compete to write the most terse, unreadable code; clever programmers in ruby compete in making everything into a DSL; clever programmers in python compete to write the most accessible, readable code. There is a reason there are so many popular frameworks in pyland - people can read them and understand them, rather than using them as black boxes and feeling constrained rather than empowered.

  • @anywallsocket
    @anywallsocket ปีที่แล้ว

    Why does everyone enumerate with idx like that? Either for i in iterable if you don’t need the index, or for i in range(len(iterable)) if you do?? And then you can just iterable[i] if you need both. I see this as easier and clearer than carrying around enumerate all the time. Please tell me why I’m wrong!

  • @richardfredlund8846
    @richardfredlund8846 ปีที่แล้ว

    well you've increased my chance of using this significantly as I had never heard of it before.

  • @Pystro
    @Pystro ปีที่แล้ว +3

    The only issue I have with this feature is that the else is not named very intuitively. I don't think I'll ever be able to remember if the else runs if the loop is exited with a break, or when it is exited by running out of elements. Something like "onFirstFalse" would have been a better name.
    Why can we not change the else though?
    Implement a "nobreak" reserved word in the next Python 3.X version and have it do the exact same thing as the else currently does. And then successively declare the "else" in for and while loop contexts as more and more strictly "deprecated". This won't remove it's functionality, but will make code with this rare feature more readable. And then IF we ever get a Python 4.0, either the "else" variation of writing it can be fully phased out, or the whole concept can be removed.
    The only problem occurs when someone uses the exact same name of that new keyword as a name in their current version code.
    Also, it shouldn't be too hard to have a python 3 to python 4 translation code replace else cases in those loops. Just automatically introduce "break_on_level_1" "..._2", ... flags before each such loop; set it to true everywhere where any break applies to that loop; and insert the "if not break_on_level_3 [content of any else or nobreak block]" after the loop.

  • @TomsonTheOne
    @TomsonTheOne ปีที่แล้ว +7

    I quite enjoy this feature to be honest... Your point of refactoring the loop into a function does only make sense in some cases for me; when the funftionality is used in multiple places. Moving code into functions for the sake of having tiny, tiny functions and jumping back and forth in my class file, is usually what I try to avoid. Unless unit testing this part would make sense. I definitely prefer it to creating flag variables before the loop. Excellent content as always!

    • @JoQeZzZ
      @JoQeZzZ ปีที่แล้ว

      In my opinion functions should either be for things that you need to do more than one place or for complicated self contained things. Using a function call instead of a for .. else .. is much more illegible to me, especially when doing things like recursion or building an algorithm. In these situations self contained functions are much nicer to me.

  • @farpurple
    @farpurple ปีที่แล้ว

    Is console prints that you shouldnt use while else?

  • @tw11tube
    @tw11tube ปีที่แล้ว +1

    I agree on the "while" example you provide: The "else" doesn't help readability there. But I really like it in the case where "break" is the success case, and exhausting the loop condition is the error case. Your "for" example is a good example where "else" handles the error. A while example that is more in spirit with how I understand would look like:
    while not timeout_exceeded:
    data = try_to_obtain_data
    if data is not None:
    break
    sleep(sensible amount)
    else:
    print("Timeout")

  • @areal935
    @areal935 ปีที่แล้ว +3

    i use it and its great

  • @mathgeniuszach
    @mathgeniuszach ปีที่แล้ว +5

    5:39 - This whole situation would never happen like so, as with error flags a good programmer will let the error propogate (or raise one themselves) into an outer try-except clause, instead of using while-else.
    In general though, In my opinion, I find while-else and for-else easier to read and simpler than carrying a boolean around; the performance gain is only a benefit, but not the reason I choose to use it. To each his own, though.

  • @monkey_noises
    @monkey_noises ปีที่แล้ว +1

    Now this makes me wonder... can you have an elif after a loop too?

  • @billy65bob
    @billy65bob ปีที่แล้ว +1

    Since you asked... I think I have seen an else paired with a loop before. but I believe that was for a 'loop ran 0 times' case.. I cannot remember which language it was though.
    The python definition of "loop finished without a break" just seems horribly superfluous by comparison; you don't need an else if you're just going to run the code after it anyway.
    Unless there's maybe some weird catch here, which there doesn't seem to be.
    EDIT: in C# terms, I'd expect a rough transformation like this:
    var collection = new List { 1, 2, 3, 4 };
    bool hasRun = false;
    for(int i = 0; i < collection.Count; i++, hasRun = true) { /*do stuff*/ }
    if (!hasRun) { /*do stuff*/ }

  • @schlopping
    @schlopping ปีที่แล้ว +14

    I'm going to have to disagree with this one. I use for-else / while-else in my code all the time! It's something I wish was in other languages too. The alternative implementations you've described are very situational and often times less readable. For-else is clean and consistent, isn't that the dream when writing Python?

  • @joseville
    @joseville ปีที่แล้ว +3

    4:10 you're probably aware, but you can do all that in one or a few lines depending on how you want to handle the not found case:
    Using a generator, next, and its default argument
    idx = next(i for i, num in enumerate(nums) if num == target)
    throws a StopIteration if not found. You catch it and throw a ValueError.
    idx = next((i for i, num in enumerate(nums) if num == target), default=None)
    sets idx to None if not found. Ofc, you can use whichever sentinel you wish (None, -1, etc.)

  • @MindlessTurtle
    @MindlessTurtle ปีที่แล้ว +2

    Used to be one of my favorite features, but I haven't used it in forever. Would be better as `nobreak` complimented by `else` as the alternative exit route for if / when there are breaks in the loop.

    • @orangenostril
      @orangenostril ปีที่แล้ว +1

      a 'yesbreak' would be fantastic for getting out of nested loops

  • @incremental_failure
    @incremental_failure ปีที่แล้ว

    This is quite exotic, now I have to find a way to use it somewhere.