Home  >  Article  >  Backend Development  >  What you don’t know about else in python loops

What you don’t know about else in python loops

高洛峰
高洛峰Original
2016-10-19 15:16:371122browse

Many languages ​​​​have the if else conditional selection combination, but there are more places where else is used in python, such as loop for or while, which can be combined with else.

The following is a brief introduction to the for-else while-else combination

When the else in the loop combination is executed, the loop ends normally (that is, it does not exit using break). For example, the following code:

numbers = [1,2,3,4,5]
for n in numbers:
    if (n > 5):
        print('the value is %d '%(n))
        break
else:
    print('the for loop does not end with break')
     
i = 0
while(numbers[i] < 5):
    print(&#39;the index %d value is %d&#39;%(i, numbers[i]))
    if (numbers[i] < 0) :
        break
    i = i + 1
else:
    print(&#39;the loop does not end with break&#39;)
   
numbers = [1,2,3,4,5]
for n in numbers:
    if (n > 5):
        print(&#39;the value is %d &#39;%(n))
        break
else:
    print(&#39;the for loop does not end with break&#39;)
    
i = 0
while(numbers[i] < 5):
    print(&#39;the index %d value is %d&#39;%(i, numbers[i]))
    if (numbers[i] < 0) :
        break
    i = i + 1
else:
    print(&#39;the loop does not end with break&#39;)

The execution result is as follows:

C:\Python27>python.exe for_else.py
the for loop does not end with break
the index 0 value is 1
the index 1 value is 2
the index 2 value is 3
the index 3 value is 4
the loop does not end with break


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn