Python Forum

Full Version: for n in range(2, 10)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
See the post just below yours 'Thread-for-n-in-range-2-10' for an explanation of loops.