Python Forum
Python Tutorial 4.4 Loop Explained
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Tutorial 4.4 Loop Explained
#1
New to Python and working thru the tutorials.

In the example of "for" loops that determines prime numbers. It uses the "%" to determine if there is a remainder of a division. So why does the number 2 become a prime number in the example below?

I know that 2 is a prime number, but I'm probably not seeing how the program works for the number 2, since when I calculate in Python 2 % 2 the result is 0. t\Thus the condition "if n % x == 0" should be True. Correct? Thereby not treating 2 as a prime number in the example.
Thanks for your help

Tutorial 4.4 explaining "break" and "for" loops
Example:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
ets.......
Reply
#2
Please wrap code in python tags. For code this long you should be typing into a file and running the file (python myprogram.py) instead of typing it in the python shell directly. In a file, your program looks like this:
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, "equals", x, "*", n // x)
            break
    else:
        # loop fell through without finding a factor
        print(n, "is a prime number")
The code body following "else:" only runs if the for loop runs to completion.
2 is a prime number because the "for x in range(2, n):" runs to completion. The "if n % x == 0" test is never performed.
4 is not a prime number because "for x in range(2, n):" ends with a break because 4 % 2 == 0.

When testing if 2 is prime, the body of the for loop is never executed. This is because of the way range() works. These are roughly equivalent.
for x in (start, end, increment):
    # do stuff

x = start
while x < end:
    # do stuff
    x += increment
If start >= end, range(start, end) ends without providing any values. If range provides no values, for range(start, end) doesn't execute the body of the for loop.
Reply
#3
Thanks for the forum posting advice and the explaination
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort Differences in 2.7 and 3.10 Explained dgrunwal 2 1,330 Apr-27-2022, 02:50 AM
Last Post: deanhystad
  Newbie - code solution explained Stjude1982 2 1,790 Sep-16-2021, 08:54 AM
Last Post: Stjude1982
  tutorial series python directx hsunteik 2 5,715 Jan-12-2017, 09:06 AM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020