Python Tutorial range function question - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Python Tutorial range function question (/thread-13087.html) |
Python Tutorial range function question - HawkeyeKnight - Sep-27-2018 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- 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. RE: Python Tutorial range function question - buran - Sep-27-2018 (Sep-27-2018, 05:19 AM)HawkeyeKnight Wrote: I am guessing it results in a null [] valueTo be precise, that is not null, but empty list (in python2) or empty range object in python3. on line 3 it try to iterate over empty object, so it just skip the whole body of the loop (i.e. it does not iterate at all) and goes to line 6 RE: Python Tutorial range function question - ThiefOfTime - Sep-27-2018 like buran said, sry had to correct my post |