Use Else statement in Python for and break loop structures

Source: Internet
Author: User
Normally we take the else statement in the IF structure as a matter of course, however, Python's powerful syntax sugar allows the Else statement to be used in the for and while loops! Let's take a look at the tips for using the Else statement in Python's for and break loop structures

You can also have an else clause after a while or for loop in Python, in which the IF condition is not satisfied in the for loop, and the Else statement is executed last.

For I in range (5): if i = = 1:  print ' in for ' else:print ' in Else ' print ' after For-loop ' # in for# in else# after For-lo Op

But we find that the IF condition is formed in the process of looping, and ultimately the content of the Else statement is executed, which is why?

OK, let's look at the following procedure:

For I in range (5): if i = = 1:  print ' in for '  Breakelse:print ' on Else ' print ' after For-loop ' # in for# after for-l Oop

We added a break in if, because else is executed after for, but only if the for loop exits normally the Else statement is executed (not by the break end loop). The else is not executed when the loop is interrupted by a break statement.

For/else is equivalent to the following code, which can add a flag like the C language:

Found = FalseFor I in range (5): if i = = 1:  found = True  print ' on ' if not found:print ' not found ' print ' after For-loop ' # in for# after For-loop

Similar to the For statement, the ELSE clause usage in the while statement is the same, and the else block executes when the loop ends normally and the loop condition is not true.

We are already familiar with conditional statement if-else, but in Python, For-else is used to handle traversal failures.

For example, we want to implement a function: Find out (81,99) the largest total square number and output, can not find the output hint.

If implemented in a for loop with C + +, you must manually determine if the For loop has failed to traverse:


#include <iostream> #include <math.h> using namespace std; int main () {  int i;  float N;  for (i=99;i>81;i--)  {   n=sqrt (float) i);   if (N==int (n))   {    cout<<i;    break;   }  }  if (i==81)//boundary Judge   cout<< "didn ' t find it!" <<endl;  return 0; }

With Python's for-else, you can simply implement this function:

From math import sqrt to n in range (99,81,-1):  root = sqrt (n)  if root = = Int (root):   print n break   else:
  print "didn ' t find it!"

The else is executed after the for loop is complete, and if you jump out of a break, the even else jumps out.

It is important to note that if there is an if statement in for, the indent of else must be aligned with the for, and if aligned with the IF, it becomes a if-else statement, which produces an unexpected error as follows:

From math import sqrt to n in range (99,81,-1):  root = sqrt (n)  if root = = Int (root):   print n break  els E:   print "didn ' t find it!"

While For-else saves two lines of code and is easy to read, it is easy to confuse with If-else. Seemingly not used in practice, but more inclined to manual processing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.