Тёмный

Python's creator wishes this feature never existed 

mCoding
Подписаться 232 тыс.
Просмотров 327 тыс.
50% 1

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/mCo...
Create custom lint rules: • Python AST Parsing and...
Guido's 2009 opinion: mail.python.or...
SUPPORT ME ⭐
---------------------------------------------------
Patreon: / mcoding
Paypal: www.paypal.com...
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/mCo...
Reddit: / mcoding
Facebook: / james.mcoding

Опубликовано:

 

9 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 1 тыс.   
@jochem_m
@jochem_m 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
I am .NET developer and thought the same. Would be nice to have this feature.
@SeverityOne
@SeverityOne 2 года назад
@@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 2 года назад
I wish people would retire the oxymoron "web developer".
@NikitaKaramov
@NikitaKaramov 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
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.
@normalmighty
@normalmighty 2 года назад
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 Год назад
Future people trying to read your code won't be happy
@paulie-g
@paulie-g Год назад
@@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 Год назад
@@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 Год назад
@@thedopplereffect00 I write many more than that fluently. It's not hard.
@thedopplereffect00
@thedopplereffect00 Год назад
@@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 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
@@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 2 года назад
@@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 2 года назад
@@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)
@electra_
@electra_ 2 года назад
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 2 года назад
fancy seeing you here lol
@electra_
@electra_ 2 года назад
@@NOT_A_ROBOT oh hi
@ian_b
@ian_b 2 года назад
GOTO
@jessveness
@jessveness 2 года назад
hey! it's that one tetris person
@electra_
@electra_ 2 года назад
@@jessveness hello lol surprised anyone knoes who i am
@nnirr1
@nnirr1 2 года назад
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.
@Rafale25
@Rafale25 2 года назад
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 2 года назад
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?
@willmurphy8650
@willmurphy8650 2 года назад
I've definitely used Python's for-else clause. I've found it beneficial in some use cases.
@sebastianjost
@sebastianjost 2 года назад
Same here. Although the name is really unintuitive.
@hashisgod
@hashisgod 2 года назад
same! but as above, it's not really an "else"!
@this_is_japes7409
@this_is_japes7409 2 года назад
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
@Boehoehuahoei
@Boehoehuahoei 2 года назад
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.
@jbaidley
@jbaidley 2 года назад
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 2 года назад
In both cases the intent would have been clearer if the keyword was "finally", not "else".
@Pabna.u
@Pabna.u 2 года назад
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 2 года назад
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.
@QwDragon
@QwDragon 2 года назад
Great explanation about labels and goto! But I disagree that the feature shoiuld be avoided.
@joseville
@joseville 2 года назад
I don't always use the else clause of a for loop, but when I do, I always comment "else: # no-break".
@Azullia
@Azullia 2 года назад
for-else was something I did use in some scripts, but I've never seen while-else
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
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.
@guiorgy
@guiorgy 2 года назад
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 2 года назад
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
@EntropyPI
@EntropyPI 2 года назад
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 2 года назад
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.
@EvanOfTheDarkness
@EvanOfTheDarkness 2 года назад
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 2 года назад
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.
@leroymilo
@leroymilo 2 года назад
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.
@matheusaugustodasilvasanto3171
@matheusaugustodasilvasanto3171 2 года назад
try...except...ELSE? Okay, time to search documentation
@eta3323
@eta3323 2 года назад
Time to learn about it... _finally_.
@guiorgy
@guiorgy 2 года назад
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 2 года назад
​@@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
@pfcrow
@pfcrow 2 года назад
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 2 года назад
Goto is cleaner regardless. What macros would you ever need?
@pfcrow
@pfcrow 2 года назад
@@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 2 года назад
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..
@doctortroels
@doctortroels 2 года назад
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_red
@ran_red 2 года назад
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 2 года назад
@@ran_red 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 2 года назад
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 2 года назад
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 2 года назад
@@georgplaz I found it easier to read script-like code than reading a lot of 2-4 line nested functions.
@amaze2n
@amaze2n 2 года назад
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 2 года назад
if you have to lookup what it means, you know the name has been chosen really poorly
@dhkatz_
@dhkatz_ 2 года назад
@@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 2 года назад
@@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 Год назад
@@georgplaz What a stupid thing to say. As if you don't need to learn the language in order to use the language.
@maxaafbackname5562
@maxaafbackname5562 2 года назад
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.
@stevie1da_
@stevie1da_ 2 года назад
I love the else clause on for loops. Its a feature I always miss when I need it in another programming language
@b_kind
@b_kind 2 года назад
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.
@duckner
@duckner 2 года назад
If you have a loop longer than 20 something lines, you're doing it wrong entirely
@MindlessTurtle
@MindlessTurtle 2 года назад
@@duckner - obviously, it depends on what you're processing; sometimes you need to loop on heavy work that may or may not need a break.
@duckner
@duckner 2 года назад
@@MindlessTurtle no, break it down into functions if it's that long
@MindlessTurtle
@MindlessTurtle 2 года назад
@@duckner - 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.
@duckner
@duckner 2 года назад
@@MindlessTurtle that's unreadable and hard to maintain in almost all cases
@TinyDeskEngineer
@TinyDeskEngineer Год назад
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.
@KiaAzad
@KiaAzad 2 года назад
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 Год назад
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
@andrewdunbar828
@andrewdunbar828 2 года назад
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 Год назад
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)
@JonnyPowell
@JonnyPowell 2 года назад
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 2 года назад
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).
@bereck7735
@bereck7735 2 года назад
i didnt even know if you can use elsr with a while loop, whacky
@unperrier5998
@unperrier5998 2 года назад
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 2 года назад
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 2 года назад
@@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 2 года назад
@@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 2 года назад
@@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-rrBJVMyD-Gs.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.
@curtmcd
@curtmcd 2 года назад
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 2 года назад
U write bad python then. Har har har.
@mynameis9817
@mynameis9817 2 года назад
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 2 года назад
A lot of time? Isn't that a little exaggerated?
@mynameis9817
@mynameis9817 2 года назад
@@brdrnda3805 nope, it depends of what project i'm working on. but most of the time it helps me save literally ton of time.
@calebmoore1582
@calebmoore1582 2 года назад
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.
@kreuner11
@kreuner11 2 года назад
I would love this in C, I always have to have an extra bool if an iteration finished successfully or no
@rustkitty
@rustkitty 2 года назад
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 2 года назад
just put an if statement before the loop
@rustkitty
@rustkitty 2 года назад
​@@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.
@joergsonnenberger6836
@joergsonnenberger6836 Год назад
To be fair, this is consistent with try/except. It is quite useful to have especially for nested loops.
@insidetrip101
@insidetrip101 2 года назад
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 2 года назад
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.
@ITR
@ITR 2 года назад
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 2 года назад
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)
@oskaraltman
@oskaraltman 2 года назад
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
@redaceFR
@redaceFR 2 года назад
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
@billy65bob
@billy65bob 2 года назад
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*/ }
@nickwood21
@nickwood21 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
@@NicolasChanCSY Thanks for the info!
@kiraleskirales
@kiraleskirales 2 года назад
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.
@schlopping
@schlopping 2 года назад
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?
@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.
@lucky-segfault
@lucky-segfault 2 года назад
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-segfault
@lucky-segfault 2 года назад
Or just don't have it. It's behavior is too obscure for pythons readability gosls
@tw11tube
@tw11tube 2 года назад
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")
@alerighi
@alerighi 2 года назад
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 2 года назад
@@squishy-tomato #define nobreak else 😁😁
@shmubob
@shmubob 2 года назад
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.
@augusto256
@augusto256 2 года назад
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 2 года назад
He literally says in the video that try-except-else is very useful.
@swolekhine
@swolekhine 2 года назад
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 2 года назад
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.
@jhuyt-
@jhuyt- 2 года назад
I don't think {for,while}-else is any less readable than flag variables. Maybe you think it's less readable because you don't see it very often?
@NoName-kt6ly
@NoName-kt6ly 2 года назад
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_ 2 года назад
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 2 года назад
you can use a package called retry
@NoName-kt6ly
@NoName-kt6ly 2 года назад
@@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 2 года назад
@@MrTyty527 true, although it's not maintained anymore. So tenacity is the better choice :)
@thediaclub4781
@thediaclub4781 2 года назад
I actually knew how low level loops work and I've used exactly the shown pattern with startlabel, goto, endlabel last week in assembly. Still I never understood this python "feature" and I still think it's not intuitive even if you know low level loops.
@user-hb8nl3ct1g
@user-hb8nl3ct1g 2 года назад
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 2 года назад
That's a miracle, that this answer was accepted.
@zecuse
@zecuse 2 года назад
... So something like: for x in constants: for eq in equations: if not eq(x): break else: Print(x) break
@user-hb8nl3ct1g
@user-hb8nl3ct1g Год назад
@@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.
@jonathandawson3091
@jonathandawson3091 Год назад
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.
@cH3rtzb3rg
@cH3rtzb3rg 2 года назад
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 2 года назад
Don't they just do a jump (So, a go-to) in ASM as well?
@cH3rtzb3rg
@cH3rtzb3rg 2 года назад
@@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.
@KilgoreTroutAsf
@KilgoreTroutAsf 2 года назад
The feature makes perfect sense and I wish something like it existed in other programming languages. Whether or not it should be named "else" is a question I would leave to the surface-level fetishists that believe that things like indentation-as-scoping are actually important.
@OfficialMGMusic
@OfficialMGMusic 2 года назад
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_ 2 года назад
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.
@TheDarkOne629
@TheDarkOne629 2 года назад
Somebody had once told me that else runs if the loop-body was not exectured because the condition (in while) was never executed or the inpuut range (in for) was empty. This could be nice if you used a functional style and used "for" only to create lists. I come from a functional background, where such checks are less nice to write. (let ((lst (for ((x xs)) (+ x 1))) (if lst )) Having something like (let ((lst (for ((x xs)) (+ x 1) :else )))
@Pystro
@Pystro 2 года назад
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.
@343N
@343N 2 года назад
saw the thumbnail, thought it was a joke.
@theHaPK
@theHaPK 2 года назад
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).
@MrGeometres
@MrGeometres 2 года назад
I really like for-else for numerical iterative methods. you'd typically have a body like x = x_next = initial_value() for i in range(maxiter): x = x_next x_next = f(x) if abs(x_next - x) < rtol*abs(x) + atol: break else: warning(f"No convergence is {maxiter} iterations!") Having the if: break right next to the else also makes the code relatively clear.
@qexat
@qexat 2 года назад
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 2 года назад
Django (and Jinja, I think) does exactly this. for...else means "for each...but if empty, then instead..."
@JackDespero
@JackDespero Год назад
I use this functionality constantly and it is both super useful and much clearer and concise than the alternatives to get the same effects.
@danielrhouck
@danielrhouck 2 года назад
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 2 года назад
You for about while-switch loop shenanigans :D
@danielrhouck
@danielrhouck 2 года назад
@@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.
@TinyDeskEngineer
@TinyDeskEngineer 2 года назад
I never knew Python had an equivalent to continue in C. Makes me wish Lua had an equivalent to it as well, because as far as I'm aware the only way to skip a loop's iteration in Lua is to use a goto statement.
@mage1over137
@mage1over137 2 года назад
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.
@stanstevey2785
@stanstevey2785 2 года назад
Your recommendation has been discarded. I will most certainly be using this feature if I ever find a use for it.
@gJonii
@gJonii 2 года назад
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 2 года назад
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 2 года назад
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 2 года назад
@@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
@MarioFanGamer659
@MarioFanGamer659 2 года назад
Originally, I thought that the else in while-else was basically like the else in if-else i.e. code which gets executed when the loop condition initially failed. The actual interpretation i.e. "whenever the condition for all iteration fails" also makes sense (and I think may be the best way to explain it without a GOTO way) but at the same time, I agree, it really isn't very useful.
@joseville
@joseville 2 года назад
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.)
@cheaterman49
@cheaterman49 2 года назад
It's a construct I use all the time, literally the "not found" condition for a linear search ; possibly useless in the age of walrus operator, but we didn't always have it, and I for one prefer the Pythonic looks of for..else to the C-ey looks of the same thing using while and walrus.
@TomsonTheOne
@TomsonTheOne 2 года назад
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.
@aajjeee
@aajjeee Год назад
having no background except TI basic, else was very natural and wraping my head around what exactly what ''while'' meant was the hard part
@areal935
@areal935 2 года назад
i use it and its great
@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 2 года назад
a 'yesbreak' would be fantastic for getting out of nested loops
@wizard7314
@wizard7314 2 года назад
Best part about programming for a hobby is that you don't have to deal with gatekeepers who decide what is 'good' and 'bad' programming practise. The for-else construct is great. I'll be using it, thanks.
@lucbloom
@lucbloom 2 года назад
Thanks for showing me this neat feature and pointing out some good use cases. Will use it from now on.
@mathgeniuszach
@mathgeniuszach 2 года назад
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.
@lukerichards22
@lukerichards22 Год назад
After watching this video I actually used this feature in a project I'm working on. r.values is a set. Each element, e, in the set is a 3-element tuple. e[0] is a hash key for a value. I wanted to know if a tuple containing a certain hash key already existed in the set. If it did, I need take no action. If it didn't, I needed to add a new 3-element tuple. So: for e in r.values: if e[0] == hashkey: break else: r.values.add((hashkey, element1, element2)) Did the trick!
@lexer_
@lexer_ 2 года назад
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.
@XCanG
@XCanG 2 года назад
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.
@0xCAFEF00D
@0xCAFEF00D 2 года назад
It's not a cost in my eyes. I think it's more readable in any case I can think of right now. The 'cost' is that you demand python programmers to be familiar and confident in the use of for else loops. Which can be a problem just because other languages don't have it. Depending on your programmers that can be enough entirely. But imagine a world where C had for else and while else. I think we'd see you recommend them instead. Flags can be used in so many ways it's nice to just have a block where this one use of flags is contained. Similar arguments could be had with list comprehension. They also defeat a customization point in code for the most part.
@illustratum42
@illustratum42 2 года назад
I was taught to use While, else: for error handling of user input queries... def user_input(): weight = input("What is your Weight?") while weight.isnumeric(): #code to excecute else: print(colored("Enter a numerical value!","red")) This makes the code keep querying the user until the input type requirements are met... and the else can be used to tell the user the error.
@MithicSpirit
@MithicSpirit 2 года назад
Discord gang
@bereck7735
@bereck7735 2 года назад
Ello mithic
@bunchofcells3333
@bunchofcells3333 2 года назад
Hmmm
@dotmashrc
@dotmashrc 2 года назад
@@bunchofcells3333 kpop fan spotted
@user-hk3ej4hk7m
@user-hk3ej4hk7m 2 года назад
Early returns can be a superpower to make branching functions way more readable
@TheLostBijou
@TheLostBijou 2 года назад
A programming language should be declarative - expressing the intent as purely and easily as possible; Python's creator messed up by naming it after an implementation level detail.
@fazzitron
@fazzitron 2 года назад
I'd never heard of this and it works in the exact opposite way than I'd expect.
@lachlanstanding7386
@lachlanstanding7386 Год назад
these videos are so interesting and well explained and your jokes are just *chef's kiss*
@jeronimo1338
@jeronimo1338 2 года назад
Basically the else at the end of the loop is just the else to the if condition inside the loop, bracketed out for all iterations. This condition always leads to the break statement, otherwise the else branch wouldn't make sense to exist there.
@ArthurKhazbs
@ArthurKhazbs Год назад
Honestly, I kinda get it with the while-else clause: it's like if-else, but loops. If-else is only executed once: either the if block if the condition is true, or the else block if the condition is false. While-else is similar, except executed repeatedly: either looping the while block while the condition is true, or finishing with the else block if the condition is false. If the condition check doesn't result in false, the else block is not executed.
@kjkardum
@kjkardum Год назад
Actually I've used else in loops quite often, when it made my code more concise because that would be the exact behaviour that I needed. But I would happily trade it for introducing named loops in py
@hantuchblau
@hantuchblau Год назад
For me the full syntax is else: # didn't break Which admittedly is not great. Still better than an extra mutable flag, though. I mostly use it if for nested loops and fixpoint computations: # shrinker returns an iterator of smaller candidates # find the smallest value which satisfies the oracle function until no smaller candidate matches def local_min(shrinker, oracle , initial): best = initial while True: for candidate in shrinker(best): if oracle(candidate): best = candidate break else: # did not break return best
@SwordQuake2
@SwordQuake2 2 года назад
Seems useful. You can leave your normal condition in the while and break at some other miscellaneous condition and the else will distinguish between them.
@richardfredlund8846
@richardfredlund8846 2 года назад
well you've increased my chance of using this significantly as I had never heard of it before.
@Tsskyx
@Tsskyx Год назад
Today I found a use for this feature: I was running a while loop and it could break at unexpected/incalculable moments. I needed a written confirmation of "nominal behavior", meaning, to write something when there was no such unexpected break. So in my case, this feature came in handy. But yes, I do wish it had a different name, "else" is kinda misleading.
Далее
21 MORE nooby Python habits
9:55
Просмотров 116 тыс.
Python 3.12 is HERE!
12:37
Просмотров 157 тыс.
Dropping In from the Clouds 🌁
00:17
Просмотров 1,5 млн
8 things in Python you didn't realize are descriptors
14:21
Naming Things in Code
7:25
Просмотров 2,1 млн
My 2 Year Journey of Learning C, in 9 minutes
8:42
Просмотров 603 тыс.
Modern Python logging
21:32
Просмотров 183 тыс.
The Flaws of Inheritance
10:01
Просмотров 938 тыс.
Python Generators
15:32
Просмотров 136 тыс.
WHY IS THE STACK SO FAST?
13:46
Просмотров 151 тыс.
Dropping In from the Clouds 🌁
00:17
Просмотров 1,5 млн