How The Program Has Control With The Break Statement
Solution 1:
I'll add some comments:
for n inrange(2, 10): #Loops from 2 to 9, inclusive. Call this Loop A.for x inrange(2, n): #Loops from 2 to n-1, inclusive. Call this Loop B.if n % x == 0: #If n is divisible by x, execute the indented codeprint n, 'equals', x, '*', n/x #print the discovered factorizationbreak#Break out of loop B, skipping the "else" statementelse: #If the loop terminates naturally (without a break) this will be executed# loop fell through without finding a factorprint n, 'is a prime number'
Solution 2:
The break
statement leaves the loop without entering the else
clause. If the loop terminates without reaching the break
, the else
clause will be entered. In other words, the loop searches for a possible divisor; if it finds one it prints it and leaves the loop using break
. If no divisor is found, the for loop terminates "normally" and thus enters the else
clause (in which it then prints that it has found a prime).
Solution 3:
Obviously, this program is trying to identify prime numbers. A prime number, has no factors (i.e. when you divide a prime number by x, there is always a remainder), other than 1 (obviously!) and itself. So, we need to test every number from 2 (i.e. not 1) up to the number before our test to see if it is a factor of our test number.
The test that is running, steps through like this:
# S1 is a setof numbers, and we want to identify the prime numbers within it.
S1 = [2, 3, 4, 5, 6, 7, 8, 9]
# test a whether n is PRIME:
for n in S1:
# if n / x has no remainder, then it isnot prime
for x in range(2, n):
if...
I have NO REMAINDER, then x is a factor of n, and n isnot prime
-----> can "BREAK" out of test, because n is clearly not PRIME
--> move ontonext n, and test it
else:
test next x against n
if we find NO FACTORS, then n is PRIME
Solution 4:
Break leaves the inner most loop directly and goes to the next step of the outer for loop.
Post a Comment for "How The Program Has Control With The Break Statement"