471,123 Members | 897 Online

How to run 3 loops?

145 100+
How would I write 3 for loops in the same code?

Expand|Select|Wrap|Line Numbers
1.
2. for i in range(1,11):
3.          i +=1
4.          print i
5.
6.
Fine for one loop, but how do I get 2 more in there? I've tried this:

Expand|Select|Wrap|Line Numbers
1.
2. for i in range(1,11):
3.         i +=1
4. j=1
5. for j in range(1,11):
6.        j +=1
7. k =1
8. for k in range(1,11):
9.        k +=1
10.        print i,j,k
11.
12.
Doesn't work :( It can run either of this ways

1 1 1
2 2 2
3 3 3, etc

or this way, which I'd prefer:
...
8
9
10
....1 <---dots were just needed just to move the columns over in here
....2
....3...etc
.........1
.........2
.........3.....etc

maybe something like this:
Expand|Select|Wrap|Line Numbers
1. print i
2. if i ==10:
3.      print j
4. if j==10:
5.      print k
6.
???
Feb 21 '07 #1
3 988
Hiya TheKid,

Try this:
Expand|Select|Wrap|Line Numbers
1. for i in range(1,11):
2.     print i
3.     for j in range(1,11):
4.         print "\t%i" % j
5.         for k in range(1,11):
6.             print "\t\t%i" % k
7.
You MUST remember to indent each for loop by a consistent amount more than it's enclosing loop. Always be sure to use SPACES or TABS but DO NOT MIX THEM - USE ONE OR THE OTHER. Spaces (usually in blocks of four) are the preferred indentation method. If you mix them, you WILL get confusing errors.

hth,
-cybervegan
Feb 21 '07 #2
Thekid
145 100+
Thank you for the reply and advice. I tried your script and it didn't produce what I was attempting:

.....
8
1
2
3
4
5
6
7
8
9
10
9
1
2
3...etc. is how that came out but it using your script and "==" I got it:
Code:
[code]

for i in range(1,11):
print i
for j in range(1,11):
if i==10:
print "\t%s" % j
for k in range(1,11):
if j==10:
print "\t\t%s" % k

[\code]

Your tab ideas works........ Thanks again!
Feb 21 '07 #3
bvdet
2,851 Expert Mod 2GB
This may interest you:
Expand|Select|Wrap|Line Numbers
1. def gen(s,e):
2.     for x in range(s,e):
3.         yield '%s' % x
4.     for y in range(s,e):
5.         yield '\t%s' % y
6.     for z in range(s,e):
7.         yield '\t\t%s' % z
8.
9. for num in gen(1,11):
10.     print num
Expand|Select|Wrap|Line Numbers
1. def gen(s,e):
2.     for x in range(s,e):
3.         yield '%s\n' % x
4.     for y in range(s,e):
5.         yield '\t%s\n' % y
6.     for z in range(s,e):
7.         yield '\t\t%s\n' % z
8.
9. nList = []
10. for num in gen(1,33):
11.     nList.append(num)
12.
13. print "".join(nList)
Feb 21 '07 #4