Python Forum

Full Version: break Statements and else Clause on Loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Python Masters,
I am an absolute beginner in Phyton, trying to teach myself, and first time member of this forum. Pardon me for asking for help with the example below as I am completely out of your league with regards to knowledge of python. Can someone please explain in simple terms line by line how the output are arrived at? I am doing self tutorial and I am stuck in this section and I dont want to proceed without understanding the logic behind the input lines because I'm sure I will come across this topic again later. Also if you can recommend an online site that provides tutorials for beginners. Thank you so much for your help.


#Input
for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
            print n, 'is a prime number'
#Output
Output:
2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
for n in range(2, 10):
this is going to iterate over a range from 2 to 10
so n will be equal to 2, 3, ... up to 9 (1 less than final number because range is zero based)
    for x in range(2, n):
this does the same from 2 to n, and will fully execute for each iteration of the outer loop
but this time terminates on n - 1, and output goes to x
if n % x == 0:
this statement used the '%' modulo operator.
It says, if n mod x == 0 which is true if both x and n are equal
modulo division yields the remainder from the division of the first argument by the second

print n, 'equals', x, '*', n/x
so if n and x are the same, above gets printed

     else:
            print n, 'is a prime number'
and if not equal prints this
Small correction to Larz explaination
n % x == 0 that will be True if n is divisible by x, i.e. remainder is 0
if it finds such x, it prints that n is equal to x multiplied by the result of the division and breaks (i.e. exit the loop)
else clause of the loop is executed when NO break was executed. So if it finish the loop and no such x was found that n is divisible by x (thus the break statement was NOT executed) it will print that n is prime number