473,786 Members | 2,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1543
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <pa*******@comc ast.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*******@comc ast.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...@thors tenkampe.dewrot e:
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...@g mail.comwrote:
On Oct 19, 3:12 am, Thorsten Kampe <thors...@thors tenkampe.dewrot e:
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.a r>
wrote:
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnel...@comc ast.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...@thors tenkampe.dewrot e:
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.a r>
wrote:
>En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnel...@comc ast.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
1793
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 dict() print combo2(5)
3
1612
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 and for). That was my story, now the question. Can you give me an advise on some geeky use of those statements to stir up some enthusiasm in students. Thanks in advance
4
1897
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 have, what am I doing wrong? int search(ifstream& inFile, string keywords, int SIZE) { int counter = 0, k; string target; inFile >> target;
2
1243
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 maybe you just want to inspect exactly what changes were related to a specific bugdb issue. Now I've searched hi and low for this and I now it's out there somewhere bleeding obvious - can't imagine I'm the first to have this thought. I just...
29
1859
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), (55554) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks,
6
1573
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 ( 0 ...100) { IN:
19
1808
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 4.5 5.5 Bob, Jolene The first time through the do while loop it works fine but the second
0
881
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' 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...
50
2540
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 ask is because the structure of the for loop seems to be for iterating through a sequence. It seems somewhat artificial to use the for loop to do something a certain number of times, like above.
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8992
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.