I am learning python and was looking at this problem: Python - Prime Number exercise Here are my questions: When n=2, the range will be (2,n), in the other words the range is between 2 and 2-1=1.
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print(n, "is a prime number")
return True
a. Will it be 2%2?
b. If the number is even, it will print
A equals B x C
will the loop break once the condition is true or it will finish the loop?
c. is the else outside the loop? what if statement does it correspond? (i know it is the if n % x == 0:
) but howcome it is seems like it is outside the loop?
I tried to run it, and understand, but then I got confused.
You seem to be confused by else
which is part of the for
loop.
You are not the only one.
In Python, for
loop might have at the end else
section, which is executed after all the loops are finished, unless there was break
statement. Yes, it is not very intuitive.
So you shall read the else
section as last part of the for
loop.
def looptest(loops=5):
for i in range(loops):
print "i", i
if i == 3:
print "in if"
return
else:
print "in else of the loop"
and try it for loops == 5:
>>> looptest(5)
i 0
i 1
i 2
i 3
in if
For number of loops 2 we do not expect return, we shall run through else
of the loop:
>>> looptest(2)
i 0
i 1
in else of the loop
Note, that return
must be within function, trying return on console would result in error.
Trying on Python console:
>>> range(2, 2)
[]
return ends up current function or run in the whole module. So after return
, no further code in the same part of your code is executed (with exceptions like try
, finally
, context managers etc, but this is not relevant to your code).