Python 中的for-else用法

对于条件语句 if- else 我们已经很熟悉了, 但是在Python中,for-else用于处理遍历失败。

比如我们要实现这样一个功能:找出(81,99)中最大的完全平方数并输出,找不到则输出提示。

如果用c++的for循环实现,必须手动的判断for循环是否遍历失败:

[cpp] 
view plain
copy
print
?

  1. #include <iostream>  
  2. #include<math.h>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     int i;  
  7.     float n;  
  8.     for(i=99;i>81;i–)  
  9.     {  
  10.         n=sqrt((float)i);  
  11.         if(n==int(n))  
  12.         {  
  13.             cout<<i;  
  14.             break;  
  15.         }  
  16.     }  
  17.     if(i==81) //边界判断  
  18.         cout<<“didn’t find it!”<<endl;  
  19.     return 0;  
  20. }  

而用Python的for-else则可简单的实现这一功能:

[python] 
view plain
copy
print
?

  1. from math import sqrt  
  2. for n in range(99,81,-1):  
  3.     root = sqrt(n)  
  4.     if root == int(root):  
  5.         print n  
  6.         break  
  7. else:  
  8.     print“Didn’t find it!”  

在for循环完整完成后才执行else;如果中途从break跳出,则连else一起跳出。

特别需要注意的是如果for中有if语句,else的缩进一定要和for对齐,如果和if对齐,则变成if-else语句,会产生意想不到的错误如下:

[python] 
view plain
copy
print
?

  1. from math import sqrt  
  2. for n in range(99,81,-1):  
  3.     root = sqrt(n)  
  4.     if root == int(root):  
  5.         print n  
  6.         break  
  7.     else:  
  8.         print“Didn’t find it!”  

虽然使用for-else节省两行代码同时便于阅读,但是容易和if-else混淆。貌似实际中不会常用,反而更倾向于手动处理

PS.还有while-else......

    原文作者:期待一片自己的蓝天
    原文地址: https://blog.csdn.net/nyist327/article/details/47806549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞