[Tutor] nested "for" loops
Peter Jakubowicz
beyondthezero@earthlink.net
Fri May 2 23:59:07 2003
At 09:42 PM 5/2/2003 -0600, you wrote:
>At 07:43 PM 5/2/2003 -0700, 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).
>>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
>>
>>TIA,
>>Peter
>>
>>
>>
>>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)
>
>Did you run the program? Did it deliver the desired results? There's your
>answer. Is that what you wanted to know? Or are you needing a way to
>comprehend nested loops?
Thanks. Yes, I did run the program, which is what made me wonder is the
results were correct; I am trying to understand how nested loops work. I
get a list of triplets, but I was wondering how I could be sure that I'd
covered all of the possible combinations. I don't have a mental picture of
how or if this code runs through all the combinations of integers through
20 and outputs all possible correct answers.