[Tutor] nested "for" loops

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon May 5 14:35:02 2003


On Fri, 2 May 2003, Peter Jakubowicz wrote:

> Hi,
>
> I've been slogging along learning Python for a while now. Nested "for"
> loops confuse me (I have trouble trying to run through them in my head).


Hi Peter,

Don't worry: they confuse me too.  *grin*



> For example, does the following code generate (albeit redundantly) all
> Pythagorean triples up to 20: i.e., all integers less than or equal to
> 20 for which i * i + j * j == k * k
>
>
> for i in range(1, 21):
>      for j in range(1, 21):
>          for k in range(1, 21):
>              if (i * i) + (j * j) == (k * k):
>                  print "Pythagorean triple: %d, %d, %d" % (i, j, k)


Hmmm... How about this?


###
def main():
    for i in range(1, 21):
        check_triples_with_i_fixed(i)

def check_triples_with_i_fixed(i):
    for j in range(1, 21):
        check_triples_with_i_and_j_fixed(i, j)

def check_triples with i_and_j_fixed(i, j):
    for k in range(1, 21):
        check_triple(i, j, k)

def checkTriple(i, j, k):
    if (i * i) + (j * j) == (k * k):
        print "Pythagorean triple: %d, %d, %d" % (i, j, k)
###


Does this make more sense?  Let's see if looking at the program in a
different perspective will help.



Good luck to you!