Sep-27-2018, 05:19 AM
I am working though the Python Tutorial. In the section after the section on the range function, which covers using "break", there is the following code-
Which results in the following -
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
My problem is the second line of code where n == 2. The range function start and stop values are equal, i.e. range(2,2), which I would have expected to result in an error. Since it does not, I am guessing it results in a null [] value. If so, I do not understand how the modulus operation in the next line does not result in an error. Can someone walk me through this. I know it works, just cannot see how.
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')
Which results in the following -
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
My problem is the second line of code where n == 2. The range function start and stop values are equal, i.e. range(2,2), which I would have expected to result in an error. Since it does not, I am guessing it results in a null [] value. If so, I do not understand how the modulus operation in the next line does not result in an error. Can someone walk me through this. I know it works, just cannot see how.