Python Forum
Python Tutorial range function question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Tutorial range function question
#1
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.
Reply
#2
(Sep-27-2018, 05:19 AM)HawkeyeKnight Wrote: I am guessing it results in a null [] value
To 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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
like buran said, sry had to correct my post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Question on "define function"; difference between return and print extricate 10 4,717 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  Function question JimBob9432 2 2,434 Oct-02-2019, 02:49 AM
Last Post: JimBob9432
  How can I run a function inside a loop every 24 values of the loop iteration range? mcva 1 2,137 Sep-18-2019, 04:50 PM
Last Post: buran
  Questions on lists, the range function & concatenation fad3r 7 4,337 Jan-25-2018, 03:11 PM
Last Post: fad3r
  python 3.4.3 Question a defining function student8 1 4,319 Oct-02-2017, 07:59 PM
Last Post: nilamo
  need help with tutorial question vincelim99 4 4,678 Mar-24-2017, 01:15 AM
Last Post: vincelim99

Forum Jump:

User Panel Messages

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