A looping statement can have an else clause , when the (for) loop iterates through the entire listor (while) the loop condition becomes false, rather than by the break statement. The Else statement is executed. the following code, which loops through the search for prime numbers, illustrates this:
>>>
>>>ForNInchRange(2,10):...ForXInchRange(2,N):...IfN%X==0:...PrintNx ' * ' n/x ... breakelse: ... # loop fell through without finding a factor ... print n ' is a prime number ' ...< Span class= "Go" >2 is a prime Number3 is a prime Number4 equals 2 * 25 I s a prime Number6 equals 2 * 37 is a prime Number8 equals 2 * 49 equals 3 * 3
(yes, this is the correct code.) Look carefully: theelse clause belongs to the for loop and is not part of the if statement. )
The Else statement usage of the Python loop statement, which executes the else statement when the loop condition becomes false and the cut is not terminated by Breakbreak.