473,326 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Noob: Loops and the 'else' construct

I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

Example:

for i in range(10):
print i
else:
print 'the end!'

0
1
2
3
4
5
6
7
8
9
10
the end!

Oct 19 '07 #1
7 1528
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <pa*******@comcast.net>
escribió:
I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).
A `while` loop tests a condition: if it evaluates to true, keep cycling;
if it is false, stop. The `else` clause is executed when the condition is
false, as in any `if` statement. If you exit the loop by using `break`,
the `else` part is not executed (because you didn't get out of the loop by
determining the condition falseness)

You can think of a `for` loop as meaning `while there are remaining
elements to be iterated, keep cycling` and the `else` clause applies when
there are no more elements. A `break` statement does not trigger the else
clause because the iteration was not exhausted.

Once you get the idea, it's very simple.

--
Gabriel Genellina

Oct 19 '07 #2
* Gabriel Genellina (Fri, 19 Oct 2007 00:11:18 -0300)
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <pa*******@comcast.net>
escribió:
I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

A `while` loop tests a condition: if it evaluates to true, keep cycling;
if it is false, stop. The `else` clause is executed when the condition is
false, as in any `if` statement. If you exit the loop by using `break`,
the `else` part is not executed (because you didn't get out of the loop by
determining the condition falseness)
So a for/else loop is exactly the same thing as a for loop with the
else clause outside the loop (except for "break")? Guess that's why I
never used that...

Thorsten
Oct 19 '07 #3
On Oct 19, 3:12 am, Thorsten Kampe <thors...@thorstenkampe.dewrote:
So a for/else loop is exactly the same thing as a for loop with the
else clause outside the loop (except for "break")?
Am I missing something here? It sounds to me like you just described
two identical constructs.
Guess that's why I
never used that...

Thorsten

Oct 19 '07 #4
On 19 Okt, 13:39, Dustan <DustanGro...@gmail.comwrote:
On Oct 19, 3:12 am, Thorsten Kampe <thors...@thorstenkampe.dewrote:
So a for/else loop is exactly the same thing as a for loop with the
else clause outside the loop (except for "break")?

Am I missing something here? It sounds to me like you just described
two identical constructs.
Think of the loop-plus-else construct as behaving like this:

while 1:
# Get next element (in a for loop)
if loop_condition: # eg. whether we have an element
# Loop body statement
else:
# Loop else statement
break

Taking the example...

for i in range(10):
print i
else:
print 'the end!'

This is equivalent to...

while 1:
# Get next element (from the range iterator)
if next element: # yes, it's more complicated than this
print i
else:
print 'the end!'
break

Now consider what happens if you put a break statement inside the for
loop.

Paul

Oct 19 '07 #5
On Oct 19, 4:11 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnel...@comcast.net>
escribió:
I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.
At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...
A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

A `while` loop tests a condition: if it evaluates to true, keep cycling;
if it is false, stop. The `else` clause is executed when the condition is
false, as in any `if` statement. If you exit the loop by using `break`,
the `else` part is not executed (because you didn't get out of the loop by
determining the condition falseness)

You can think of a `for` loop as meaning `while there are remaining
elements to be iterated, keep cycling` and the `else` clause applies when
there are no more elements. A `break` statement does not trigger the else
clause because the iteration was not exhausted.

Once you get the idea, it's very simple.
It's useful when you want to search for an item and to do something if
you don't find it, eg:

for i in items:
if is_wanted(i):
print "Found it"
break
else:
print "Didn't find ir"

Oct 19 '07 #6
* Dustan (Fri, 19 Oct 2007 11:39:04 -0000)
On Oct 19, 3:12 am, Thorsten Kampe <thors...@thorstenkampe.dewrote:
So a for/else loop is exactly the same thing as a for loop with the
else clause outside the loop (except for "break")?

Am I missing something here? It sounds to me like you just described
two identical constructs.
#
for i in range(10):
print i
else:
print 'the end!'
#

is the same else

#
for i in range(10):
print i
print 'the end!'
#
Oct 20 '07 #7
MRAB schrieb:
On Oct 19, 4:11 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
>En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnel...@comcast.net>
escribió:
>>I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.
At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...
A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).
A `while` loop tests a condition: if it evaluates to true, keep cycling;
if it is false, stop. The `else` clause is executed when the condition is
false, as in any `if` statement. If you exit the loop by using `break`,
the `else` part is not executed (because you didn't get out of the loop by
determining the condition falseness)

You can think of a `for` loop as meaning `while there are remaining
elements to be iterated, keep cycling` and the `else` clause applies when
there are no more elements. A `break` statement does not trigger the else
clause because the iteration was not exhausted.

Once you get the idea, it's very simple.
It's useful when you want to search for an item and to do something if
you don't find it, eg:

for i in items:
if is_wanted(i):
print "Found it"
break
else:
print "Didn't find ir"
Wrong. It's not:

for i in []:
print i
else:
print "I'm reached, too"

prints out "I'm reached, too"

The else will ONLY not get executed when the loop is left prematurely
through a break:

for i in [1]:
print i
break
else:
print "I'm reached, too"

won't print the "I'm ..."
Diez
Oct 20 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
3
by: Sergej Andrejev | last post by:
Not long ago I was asked to give PHP lections to some private IT school. I'm on second lection now, and will be teaching my :) students conditional statements (if..else and switch) and loops (while...
4
by: foker | last post by:
I have an array with 50 elements in it, and a huge document with like 35,000 words on it. What I want to do is count the number of times each element has appeared in the document. This is what I...
2
by: Holger | last post by:
I needed a tool for extracting patches from CVS based on the log messages. I.e. we mark our fixes and features with a "Bugdb XYZ" And sometimes you need to move a fix/feature to another branch or...
29
by: mike_wilson1333 | last post by:
I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235),...
6
by: Wijaya Edward | last post by:
Can we make loops control in Python? What I mean is that whether we can control which loops to exit/skip at the given scope. For example in Perl we can do something like: OUT: foreach my $s1...
19
by: Zach Heath | last post by:
I'm just starting C and haven't done programming for a few years...could you guys please take a look at this? Thanks for your time! I have an input file that looks like: 1.5 2.5 Bob, Joe...
0
by: Ixiaus | last post by:
I have just come across a site that discusses Python's 'for' and 'while' loops as having an (optional) 'else' structure. At first glance I interpreted it as being a bit like the 'default'...
50
by: John Salerno | last post by:
I know it's popular and very handy, but I'm curious if there are purists out there who think that using something like: for x in range(10): #do something 10 times is unPythonic. The reason I...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.