# Python的for和break迴圈結構中使用else語句的技巧

``````
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-loop
``````

``````
for i in range(5):
if i == 1:
print 'in for'
break
else:
print 'in else'
print 'after for-loop'
# in for
# after for-loop
``````

for/else等效於下面這段程式碼，可以類似C語言那樣新增一個flag：

``````
found = False
for i in range(5):
if i == 1:
found = True
print 'in for'
print 'after for-loop'
# in for
# after for-loop
``````

``````
#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) //邊界判斷
cout<<"didn't find it!"<<endl;
return 0;
}
``````

``````
from math import sqrt
for n in range(99,81,-1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print"Didn't find it!"
``````

``````
from math import sqrt
for n in range(99,81,-1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print"Didn't find it!"
``````