Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105087
| From | "Sven R. Kunze" <srkunze@mail.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: empty clause of for loops |
| Date | 2016-03-17 13:01 +0100 |
| Message-ID | <mailman.269.1458216120.12893.python-list@python.org> (permalink) |
| References | (8 earlier) <56E9902F.9080103@mail.de> <56E99159.70501@mail.de> <1458148134.113764.551096586.28A85FDB@webmail.messagingengine.com> <mailman.237.1458151523.12893.python-list@python.org> <56e9fa05$0$22141$c3e8da3$5496439d@news.astraweb.com> |
On 17.03.2016 01:27, Steven D'Aprano wrote: > That post describes the motivating use-case for the introduction > of "if...else", and why break skips the "else" clause: > > > for x in data: > if meets_condition(x): > break > else: > # raise error or do additional processing > > > It might help to realise that the "else" clause is misnamed. It should be > called "then": > > for x in data: > block > then: > block > > > The "then" (actually "else") block is executed *after* the for-loop, unless > you jump out of that chunk of code by raising an exception, calling return, > or break. > > As a beginner, it took me years of misunderstanding before I finally > understood for...else and while...else, because I kept coming back to the > thought that the else block was executed if the for/while block *didn't* > execute. That's true. I needed to explain this to few people and I always need several attempts/starts to get it right in a simple statement: 'If you do a "break", then "else" is NOT executed.' I think the "NOT" results in heavy mental lifting. > I couldn't get code with for...else to work right and I didn't > understand why until finally the penny dropped and realised that "else" > should be called "then". That's actually a fine idea. One could even say: "finally". Best, Sven
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: empty clause of for loops Steven D'Aprano <steve@pearwood.info> - 2016-03-17 11:27 +1100 Re: empty clause of for loops "Sven R. Kunze" <srkunze@mail.de> - 2016-03-17 13:01 +0100
csiph-web