[Tutor] Nested for loops

Joel Goldstick joel.goldstick at gmail.com
Wed Nov 27 17:27:34 CET 2013


On Wed, Nov 27, 2013 at 11:08 AM, Rafael Knuth <rafael.knuth at gmail.com>wrote:

> Hej there,
>
> I am trying to figure out how exactly variables in nested loops are
> generated, and don't get it 100% right yet. Here's my 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')
>
> And here's what I assume happens inside these for loops:
>
> #1 Round:
> n = 2
> x = no result
> >>>
> 2 is a prime number
>
> #2 Round:
> n = 3
> x = 2
> >>>
> 3 is a prime number
>
> #3 Round:
> n = 4
> x = 3
> >>>
>

Round 3 would be n = 4, x = 2.  The inner loop starts from its own
beginning (x = 2) and repeats as often as necessary to get the break
condition or complete to the x  = n condition

> My assumption about the way these two for loops work is wrong, because
> the output cannot be "4 is a prime number" for obvious reasons.
>
> Can anyone help me understand?
> I am using Python 3.3.0. Thank you!
>
> All the best,
>
> Raf
>

I copied your code into a python 2.7 shell and got this:


>>> 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')
...
(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)

What exactly do you get when you run the code?


Since print is a function in python 3, my output will look slightly
different than yours

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131127/9e372918/attachment.html>


More information about the Tutor mailing list