For/Else Loop
Python
Today I encounter python snippet code and something take my attention. And the concept is similar to below code.
1 2 3 4 5 6 7 |
for i in range(7): print("for") if i == 10: print("if") break else: print("else") |
1 2 3 4 5 6 7 8 9 |
Output: for for for for for for for else |
And I recognize else statement is not given an error. After some research, I found the miracle, for/else loop. The concept of this loop is when for is finished without break else statement run if break else statement is passed. Bellow code is an example of usage.
1 2 3 4 5 6 7 8 |
for n in range(2, 10): for x in range(2, n): if n % x == 0: print( n, 'equals', x, '*', n/x) break else: # loop fell through without finding a factor print(n, 'is a prime number') |
1 2 3 4 5 6 7 8 9 |
Output: 2 is a prime number 3 is a prime number 4 equals 2 * 2.0 5 is a prime number 6 equals 2 * 3.0 7 is a prime number 8 equals 2 * 4.0 9 equals 3 * 3.0 |
This tip is can be helpful you can check for loops in for loops it can be more efficient in some cases