[Tutor] Prime Numbers

Rafael Knuth rafael.knuth at gmail.com
Mon Dec 16 09:49:23 CET 2013


Hej there,

>> number = 9
>> for element in range(2,9):
>> 3 % 2 != 0:
>> My assumption is that the program should end the loop after the first
>> iteration again and it then should return True.
>
> No. If it did that, it wouldn't be a *loop* at all, would it? The whole
> reason loops (for and while) exist is to run the code repeatedly. If
> they only ran once, no matter what, they would be useless.
>
> Unless you exit a loop early (with a return, a break, or by raising an
> exception) the loop will jump back to the beginning until such time as
> the loop is completed. Then it will jump to the code following the loop.
>
> So, here's a simple example:
>
> for element in range(5):
>     print(element)
>
> With your assumption, you might think it will print 0, then stop. But
> it doesn't. It prints 0, then 1, then 2, then 3, then 4. Each time
> through the loop it jumps back to the beginning, gets the next value
> from the range, and only when there are no more values to get does the
> for-loop finish.

That's actually a good example. Let me explain what I feel confused about.
Print actually runs through the entire loop. But let's change the
program like this:

def RangeOfNumbers (n):
    for i in range(n):
        return i

print(RangeOfNumbers(5))

When you run this program, your result is:

>>>
0

So, return only returns the first value within the loop.
If you want the loop run over the entire range of values, you have to
change it like this:

def RangeOfNumbers (n):
    List = []
    for i in range(n):
        List.append(i)
    return List

print(RangeOfNumbers(5))

>>>
[0, 1, 2, 3, 4]

Let's get back to my original program:

def is_prime(number):
    for element in range(2, number):
        if number % element == 0:
            return False
    return True

I was assuming that the for loop ends after the first round, just like
in my first example above.
But as you explained the for loop iterates through the entire range
and only stops if a. there are no more values left to iterate through
or b. the condition is met (return False if number % element == 0).
That's the tiny little detail I am confused about: What does return
exactly do? Does it return only the first value within a loop or does
it iterate through all values within a loop? (unless a given condition
is met)

Rafael


More information about the Tutor mailing list