-4

I am a C guy. These days i am learning python for my latest project requirement. Now my question is : What is the significance of Else statements with Loops[While, For..]. Do we really need them ??

SJ26
  • 29
  • 7
  • 4
    See this http://nedbatchelder.com/blog/201110/forelse.html and this http://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – The6thSense Dec 29 '15 at 07:43

2 Answers2

0

Editted from Else clause on Python while statement :

The else clause is only executed when your [Loop]'s condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

In other words, its just a way to check if the loop was run without any problems, and everything that was suppoused to be done is done. If you had to break or throw an exception in the middle, then the else statement won't execute since the loop didn't finish "properly".

EDIT: an example from a linked thread explains this well. The else statement checks if the loop was executted completely - and if it was not broken out of and there wasn't an exception raised, you can do a certain action. for example:

...

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.)

...

Notice, that's just for syntax. Of course you can do it without the for-else statement, like so:

...

flagfound = False
for i in mylist:
    if i == the flag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.)

...

but syntax-wise, the first way often looks better.

Community
  • 1
  • 1
A. Abramov
  • 1,823
  • 17
  • 45
0

Python has the ability to execute code when a for loop has exhausted its list or when a while loop becomes false.

It's actually quite nice if you want to do special handling if the loop was "unsuccessful". For example, searching a list for a number:

for testVal in listOfVals:
    if lookingFor == testVal:
        print("Found one")
else:
    print("Not in the list")

With other languages (such as C), it's common to keep a found boolean variable to indicate that it was found, then check that variable after the loop, something like:

int found = 0;
for (int i = 0; i < size; i++) {
    if (lookingFor == listOfVals[i]) {
        puts ("Found one")
        found = 1;
    }
}
if (!found) {
    puts ("Not in the list")
}

There are probably other ways you could acheive the same end in C but the Python method seems more natural to me.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953