Nested for loop problem

Don Low m_tessier at sympatico.ca
Sat Nov 8 17:22:04 EST 2003


Hi,

I'm studying the python tutorial at python.org. In introducing the
concept of *break* and *continue* Statements, and *else* Clauses on
Loops, there's an example that goes as follows:

#!/usr/bin/python

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'

I have a problem with this nested for loop, because the answer it yields
doesn't make sense to me. Here is the answer:

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

Where I have the problem is as follows:

n = 2 in the first iteration of range(2, 10); therefore x = [] in the
first iteration of range(2, n). More specifically:

>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]
>>> range(2, 2)
[]

>>> for x in range(2, 2):
...     print x
... 

Since x prints nothing, I guess x = NULL. If I try:

if 2 % NULL or blank, I get an error message.

So the question is when I run the script, why doesn't it produce an
error message?

OK, I'm sure I'm misunderstanding something, but could someone explain?


-- 
Thanks,

Don




More information about the Python-list mailing list