"Gregory Morton" <tyethec...@hotmail.com> wrote

I'm having a problem understanding how this code works
in lesson 4.4 on the python tutorial.

Can you already program in another language? Say VB, Java or PHP?

If not you would be better off with a different tutorial since rthe official
one is really targeted at experienced programmers moving to Python
from another language.

This page offers several choices, including mine:

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers


Can anyone explain it in easy-to-digest details? I kind of know
what most of the stuff means, but I can't comprehend how it
all works in unison.
That, and I'm having a hard time understanding what break does.

OK the overview is that the outer loop tests each number
from 2 to 9 and tests to see if it is a prime number or not.
The test it uses is to divide the number by each number
from 2 to the number itself. If it finds a number that divides
exactly, ie the remainder is zero then it stops, or breaks,
the test and moves on to the next number from the outer loop.

Line by line:

for n in range(2, 10):

This is the outer loop selecting each number in the range from 2 to 9.

...     for x in range(2, n):

This is the test loop dividing by each number from 2 to n.

...         if n % x == 0:

If n divided by x has a remainder of zero

...             print(n, 'equals', x, '*', n//x)
...             break

then it is not a prime number so we stop the test by breaking
out of the loop. and going back to the top for the next number
to test.

...     else:

If we reach the end of the loop without breaking

...         # loop fell through without finding a factor
...         print(n, 'is a prime number')

It must be a prime number so report it as such

Then go back to the top for the next number to test.

You will find more about loops in the Loops topic
of my tutorial.

HTH

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to