In many languages, if else is a combination of conditions, but there are more places in Python where else is used, such as loop for, or while can be combined with else.
Here is a brief introduction to For-else While-else combination
In the case of the else execution in the loop combination, the loop ends normally (that is, it is not exited with break). such as the following code:
numbers = [1,2,3,4,5]for N in Numbers: if (n > 5): print (' The value is%d '% (n)) Breakelse: print (' The For loop does not end with break ') i = 0while (Numbers[i] < 5): print (' The index%d value is%d '% (I, numbers[i]) if (Numbers[i] < 0): Break i = i + 1else: print (' The loop does not end with break ') numbers = [ 1,2,3,4,5]for N in numbers: if (n > 5): print (' The value was%d '% (n)) Breakelse: print (' The For loo P does not end with break ') i = 0while (Numbers[i] < 5): print (' The index%d value is%d '% (I, numbers[i]))
if (Numbers[i] < 0): break i = i + 1else: print (' The loop does not end with break ')
The results of the implementation are as follows:
C:\python27>python.exe for_else.pythe for loop does not end with Breakthe index 0 value is 1the index 1 value is 2the I Ndex 2 value is 3the index 3 value was 4the loop does not end with break