Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for n in range(2, 10)
#1
xHey, I just started learning python (my first programming language) and I apologize if this question comes up often. I didn't find anything with the forum search.

I'm at this part of a tutorial: https://docs.python.org/2/tutorial/contr...s-on-loops

What bothers me is that I don't completely understand how it works. I know that 2 is a prime number, but why doesn't this sequence output "2 equals 2 * 1".

As far as I understand it, inputting
for n in range 2, 10:
means that  n = every integer from 2 through 9, while

for n in range 2, 10:
     for x in range(2, n):
means that x = every range of integers from (2, 2) through (2, 9), i.e.

for n in range(2, 10):
    print range(2, n)
[]
[2]
[2, 3]
[2, 3, 4]
[2, 3, 4, 5]
[2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 8]
Now, if n were only modded (%) by the x value ranges that occupy the same position in both lists, e.g.

2 % []
3 % [2]
4 % [2, 3]
5 % [2, 3, 4]
6 % [2, 3, 4, 5]
7 % [2, 3, 4, 5, 6]
8 % [2, 3, 4, 5, 6, 7]
9 % [2, 3, 4, 5, 6, 7, 8]
I think I would understand the result. But this doesn't seem to be the case, as, when I enter

for n in range(1, 3):
     for x in range (1, 4):
            print n % x
I get 6 values, indicating that each value of n was modded by each value. So if this is the case, why, in the tutorial example, isn't every value of n modded by every value of every range of n until a product is possible? If this were the case, I'd expect "2 equals 2 * 1" to be printed.

I don't see an edit option... I left out something from the first sentence of the last paragraph. Should be:

(Oct-03-2016, 07:29 AM)diemildefreude Wrote: I get 6 values, indicating that each value of n was modded by each value of x. So if this is the case, why, in the tutorial example, isn't every value of n modded by every value of every range of n until a product is possible? If this were the case, I'd expect "2 equals 2 * 1" to be printed.
Reply
#2
See the post just below yours 'Thread-for-n-in-range-2-10' for an explanation of loops.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x axis range goes over the set range Pedroski55 5 3,111 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  Define a range, return all numbers of range that are NOT in csv data KiNeMs 18 6,877 Jan-24-2020, 06:19 AM
Last Post: KiNeMs

Forum Jump:

User Panel Messages

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