对于条件语句 if- else 我们已经很熟悉了, 但是在Python中,for-else用于处理遍历失败。
比如我们要实现这样一个功能:找出(81,99)中最大的完全平方数并输出,找不到则输出提示。
如果用c++的for循环实现,必须手动的判断for循环是否遍历失败:
[cpp]
view plain
copy
print
?
- #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;
- }
而用Python的for-else则可简单的实现这一功能:
[python]
view plain
copy
print
?
- 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!”
在for循环完整完成后才执行else;如果中途从break跳出,则连else一起跳出。
特别需要注意的是如果for中有if语句,else的缩进一定要和for对齐,如果和if对齐,则变成if-else语句,会产生意想不到的错误如下:
[python]
view plain
copy
print
?
- 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!”
虽然使用for-else节省两行代码同时便于阅读,但是容易和if-else混淆。貌似实际中不会常用,反而更倾向于手动处理
PS.还有while-else......