简体   繁体   中英

How does the 'for' function work if it is used in a 'for' loop?

I'm using the python documentation to begin learning everything, and it introduces the 'for' loop with the 'for' function inside the said 'for' loop. I'm doing an awful job of explaining because I'm having such a hard time keeping up with the terminology, so I'll just show you:

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'

I understand the if/else loops, and the break statement. I see that it somehow generates prime numbers between 2 and 10. Other than that, I'm kinda lost with this example. The documentation is becoming intolerably verbose, and I am barely able to comprehend very much of it at this point. I was just hoping someone could explain this in slightly simpler terms

for n in range(2, 10):

means that n will take on the values of 2 - 10, one at a time, and each time it takes on a new value, run the inner loop.

The inner loop,

for x in range(2, n):

means that x will take on the values of 2 - n, one at a time, and execute its innards, the if/else.

So the outer loop starts at 2, so n = 2. The inner loop iterates from 2-n, n=2, so 2-2, so one time.

Then control passes back to the outer loop, n is incremented, and the inner loop is now executed from 2-n, n being 3. So x takes on the values of 2, then 3, and since n is 3, passes back to the outer loop, and so on.

Here is some flow:

:start outer, n = 2
:goto inner, x will range from 2 - 2, so x = 2, x hits max for the inner loop
:goto outer, n = 3
:goto inner, x will range from 2 - 3, so x = 2, iterate once, x = 3, x hits max for inner loop
:goto outer, n = 4
:repeat

First things first for is not a function but a construct. Also, if/else is not a loop but a branching construct

Consider the labeled code

for n in range(2, 10): # this is the outer loop
    for x in range(2, n): # this is the inner loop 
                          #(this is where the code is checking whether n is prime)
        if n % x == 0: #checking is x divides n
            print n, 'equals', x, '*', n/x
            break
        else:

            print n, 'is a prime number'

next, the outer for loop iterates from 2 to 10. Each iteration of the loop has another inner for loop. This inner loop iterates from 2 to that number and checks for divisibility to check of the variable n (outer loop) is a prime number or not.

For example:

For the first iteration
n=2
x=nothing

,then

n=3
x=2

and

n=4
x=2,3

and so on.

just to add in python, unlike other popular languages the for loop does not increment the variable. Instead it just selects a value at a time from a list/array of values that you specify (for ex: range(2,10) in this case is an array [2 3 4 5 6 7 8 9]

I'm going to definitely agree with @Josh and @gddc's answer here, but there's a bit more that needs to be explained to understand the for loop construct, and what its power really is. But to get that, I'd have to talk just a little bit on what an iterable object is.


Python's for loops don't work the same way they would in another language,like Java for instance. The for loops here require something they can iterate over. This means three datatypes (in general): lists, tuples, and dictionaries. All three of these have values that can be iterated over, and as such, a for loop will work fine with them.

The range(a, b, s) function will generate a list of values in the range [a, b), optionally with a skip value s. Since a list is iterable, we can use it with the for statement.

When you nest for statements, you are performing a nested loop . The furthest for statement in will operate the most often. You can compare a nested loop to an analog time piece - the second hand is the innermost for , the minute hand is a level above that, and the hour hand is a level above that.

Now, onto this example. In the outside for loop, we bind every value we get from the iterable list to a variable - in this case, n . When we start the loop, n == 2 . We come to the inner for loop, and notice that we bind the variable x to the list [2, 2) , which would be empty - having the same start and end point in a range() doesn't return anything. So the first time through, we would skip the inner loop.

Once we're done with the inner level loop, we come back and repeat the outer loop. So now, n == 3 . We come to the inner loop, and bind x to the first value in the iterable range [2, 3) , which would be 2 . We then perform the inner operations, as expected of the if statement.

When we finally get to a point when n == 9 (maximum value; remember, n can never equal 10 in this example due to the range limits), x will be bound to the first value of the iterable range [2, 9) . So x will start at 2, then move to 3, and so forth.

If you want to learn more on how for loops work, then I recommend looking into list comprehensions , and even referencing Dive into Python's section on lists .

When you nest for loops the inner loop gets repeated for every round of the outer loop. So, for your example, it starts like this:

for x in range(2, 2):

Then proceeds to

for x in range(2, 3):

and so on. Each inner loop grows one step longer for each step of the outer loop. Because the break is within the inner loop, the outer loop will run in its entirety regardless of how many times the inner loop break s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM